3 Commits
Author SHA1 Message Date
w11 872f843c6f refactor(file,shell,process): 去 gin 化——标准库 http.HandlerFunc + webhttp.Router 适配层
- 新增 webhttp 包: Router 最小路由接口(5 动词) + ServeMuxRouter 适配器 + WriteJSON 统一响应
- file/shell/process 三个被控能力包改以标准库 handler 形态注册, 不再绑死 gin
- 由此 gin 及其连带重依赖(quic-go/http3、mongo bson、ugorji codec、goccy、validator)退出被控端二进制
- shell: recDir 死参数修复——原实现硬编码 ./rec, 传入的录制目录不生效; 现录制写入与记录列表同源
- shell: 终端创建失败由 panic 改为记日志后关连接(net/http 按连接兜底恢复, 不再依赖框架 Recovery)
- file: 上传落盘不再沿用 SaveUploadedFile 的 MkdirAll+Chmod(Windows 盘根 Chmod 报参数不正确), 保留 MkdirAll 去掉 Chmod
- 消费方: remote-client 纯 ServeMux 承载; remote-service 保留 gin 栈经 gin.WrapH 桥接(middle 链照常生效)

破坏性变更: RegisterRouters* 形参 gin.RouterGroup → webhttp.Router, 升级 tag v0.5.0
2026-09-29 08:26:23 +08:00
w11 16e6037dba fix(shell): Web 终端 resize 失效修复——前端 resize 消息 Data 字段反序列化为 map[string]interface{}, 对 ResizeDataType 的直接类型断言恒失败被静默吞掉, PTY 固定 180x30 与窗口脱节; 改为二次 marshal+unmarshal 解码行列并校验正值后 SetSize 2026-09-25 10:09:39 +08:00
w11 52593ddd7e docs(remote): VncServerConfig 注明 37 项口径——标准安装落盘全集(经注册表+tvnserver.exe 字符串表双重核对), ViewOnlyPassword/ControlPassword 为条件值暂不覆盖及原因 2026-09-23 20:01:56 +08:00
7 changed files with 451 additions and 563 deletions
+117 -200
View File
@@ -1,217 +1,150 @@
package file
// 移植自 remote-backend-server internal/handlers/file(去 DB 依赖)。
// 标准库 http.HandlerFunc 形态, 路由注册经 webhttp.Router 适配(去 gin 化)。
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/jaypipes/ghw"
"github.com/shirou/gopsutil/v3/disk"
"io"
"net/http"
"os"
"path/filepath"
"git.zeroonesoft.cn/golib/remote-core/common"
"strconv"
"github.com/jaypipes/ghw"
"github.com/shirou/gopsutil/v3/disk"
"git.zeroonesoft.cn/golib/remote-core/common"
"git.zeroonesoft.cn/golib/remote-core/webhttp"
)
// RegisterRoutersGatewayFile 注册路由
func RegisterRoutersGatewayFile(r *gin.RouterGroup) {
r.GET("/file/list", getGatewayFileList())
r.POST("/file/list", postGatewayFileList())
r.DELETE("/file", deleteGatewayFile())
r.PUT("/file/name", putGatewayFileName())
r.GET("/file/download", getGatewayFileDownload())
r.HEAD("/file/download", headGatewayFileDownload())
r.POST("/file/upload", postGatewayFileUpload())
r.POST("/file/dir", postGatewayFileDir())
// RegisterRoutersGatewayFile 注册路由。
// 下载注册的是 GET, ServeMux 模式下 HEAD 自动兼容(响应头一致、无响应体);
// 原 gin 独立 HEAD handler 在文件缺失时会因 fi 空指针 panic, 一并消失。
func RegisterRoutersGatewayFile(r webhttp.Router) {
r.GET("/file/list", getGatewayFileList)
r.POST("/file/list", postGatewayFileList)
r.DELETE("/file", deleteGatewayFile)
r.PUT("/file/name", putGatewayFileName)
r.GET("/file/download", getGatewayFileDownload)
r.HEAD("/file/download", headGatewayFileDownload)
r.POST("/file/upload", postGatewayFileUpload)
r.POST("/file/dir", postGatewayFileDir)
}
type PathData struct {
Path string `json:"path"`
}
// 传递文件路径不方便 比如 路径中包含 #
func getGatewayFileList() gin.HandlerFunc {
return func(c *gin.Context) {
dir := c.Query("path")
data, err := getFileList(dir)
if err != nil {
c.JSON(http.StatusOK, gin.H{
func fail(w http.ResponseWriter, msg string) {
webhttp.WriteJSON(w, http.StatusOK, map[string]any{
"code": 1,
"msg": "error:" + err.Error(),
"msg": msg,
"data": "OK",
})
return
}
c.JSON(http.StatusOK, gin.H{
func ok(w http.ResponseWriter, data any) {
webhttp.WriteJSON(w, http.StatusOK, map[string]any{
"code": 0,
"msg": "操作成功",
"data": gin.H{
"data": data,
})
}
// 传递文件路径不方便 比如 路径中包含 #
func getGatewayFileList(w http.ResponseWriter, r *http.Request) {
dir := r.URL.Query().Get("path")
data, err := getFileList(dir)
if err != nil {
fail(w, "error:"+err.Error())
return
}
ok(w, map[string]any{
"list": data,
"count": len(data),
"path": dir,
},
})
}
}
func deleteGatewayFile() gin.HandlerFunc {
return func(c *gin.Context) {
path := c.Query("path")
ok, err := common.PathExists(path)
func deleteGatewayFile(w http.ResponseWriter, r *http.Request) {
path := r.URL.Query().Get("path")
exists, err := common.PathExists(path)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": 1,
"msg": "error:" + err.Error(),
"data": "OK",
})
fail(w, "error:"+err.Error())
return
}
if !ok {
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": 1,
"msg": "error:" + "文件不存在",
"data": "OK",
})
if !exists {
fail(w, "error:文件不存在")
return
}
}
err = os.Remove(path)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": 1,
"msg": "error:" + err.Error(),
"data": "OK",
})
if err = os.Remove(path); err != nil {
fail(w, "error:"+err.Error())
return
}
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "操作成功",
"data": nil,
})
}
ok(w, nil)
}
func putGatewayFileName() gin.HandlerFunc {
return func(c *gin.Context) {
oldPath := c.Query("old")
newFile := c.Query("new")
func putGatewayFileName(w http.ResponseWriter, r *http.Request) {
oldPath := r.URL.Query().Get("old")
newFile := r.URL.Query().Get("new")
fileInfo, err := os.Stat(oldPath)
if err != nil {
if _, err := os.Stat(oldPath); err != nil {
if os.IsNotExist(err) {
c.JSON(http.StatusOK, gin.H{
"code": 1,
"msg": "error:" + "文件不存在",
"data": "OK",
})
fail(w, "error:文件不存在")
return
}
c.JSON(http.StatusOK, gin.H{
"code": 1,
"msg": "error:" + err.Error(),
"data": "OK",
})
fail(w, "error:"+err.Error())
return
}
dir := filepath.Dir(oldPath)
newPath := filepath.Join(dir, newFile)
fmt.Println(fileInfo)
fmt.Println(oldPath, newPath)
if err := os.Rename(oldPath, newPath); err != nil {
fail(w, "error:"+err.Error())
return
}
ok(w, nil)
}
err = os.Rename(oldPath, newPath)
func postGatewayFileDir(w http.ResponseWriter, r *http.Request) {
dir := r.URL.Query().Get("dir")
exists, err := common.PathExists(dir)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": 1,
"msg": "error:" + err.Error(),
"data": "OK",
})
fail(w, "error:"+err.Error())
return
}
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "操作成功",
"data": nil,
})
}
}
func postGatewayFileDir() gin.HandlerFunc {
return func(c *gin.Context) {
dir := c.Query("dir")
ok, err := common.PathExists(dir)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": 1,
"msg": "error:" + err.Error(),
"data": "OK",
})
if exists {
fail(w, "error:文件不存在")
return
}
if ok {
c.JSON(http.StatusOK, gin.H{
"code": 1,
"msg": "error:" + "文件不存在",
"data": "OK",
})
if err = os.MkdirAll(dir, 0750); err != nil {
fail(w, "error:"+err.Error())
return
}
err = os.MkdirAll(dir, 0750)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": 1,
"msg": "error:" + err.Error(),
"data": "OK",
})
return
}
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "操作成功",
"data": nil,
})
}
ok(w, nil)
}
func postGatewayFileList() gin.HandlerFunc {
return func(c *gin.Context) {
func postGatewayFileList(w http.ResponseWriter, r *http.Request) {
dir := PathData{}
err := c.BindJSON(&dir)
fmt.Println("dir", dir)
// body 解析失败按空路径处理(列盘符), 与原 gin BindJSON 忽略错误的语义一致
_ = json.NewDecoder(r.Body).Decode(&dir)
data, err := getFileList(dir.Path)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": 1,
"msg": "error:" + err.Error(),
"data": "OK",
})
fail(w, "error:"+err.Error())
return
}
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "操作成功",
"data": gin.H{
ok(w, map[string]any{
"list": data,
"count": len(data),
"path": dir.Path,
},
})
}
}
type FileInfo struct {
Name string `json:"name"`
@@ -227,17 +160,6 @@ type FileInfo struct {
func getFileList(dir string) ([]FileInfo, error) {
list := make([]FileInfo, 0)
/*filepath.Walk(dir, func(path string, info fs.FileInfo, err error) error {
list = append(list, FileInfo{
Name: info.Name(),
Size: info.Size(),
Mode: info.Mode().String(),
ModTime: time.Time{},
IsDir: info.IsDir(),
})
fmt.Println(info.Mode().Type())
return nil
})*/
if dir == "" {
partitions, err := disk.Partitions(false)
@@ -306,35 +228,25 @@ func getFileList(dir string) ([]FileInfo, error) {
return list, nil
}
func getGatewayFileDownload() gin.HandlerFunc {
return func(c *gin.Context) {
filePath := c.Query("filename")
func getGatewayFileDownload(w http.ResponseWriter, r *http.Request) {
filePath := r.URL.Query().Get("filename")
fileName := filepath.Base(filePath)
c.Header("Content-Type", "application/octet-stream")
c.Header("Content-Disposition", "attachment; filename="+fileName)
c.Header("Content-Transfer-Encoding", "binary")
fi, err := os.Stat(filePath)
if err == nil {
c.Header("Content-Length", strconv.FormatInt(fi.Size(), 10))
}
c.File(filePath)
}
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment; filename="+fileName)
w.Header().Set("Content-Transfer-Encoding", "binary")
http.ServeFile(w, r, filePath)
}
func headGatewayFileDownload() gin.HandlerFunc {
return func(c *gin.Context) {
filePath := c.Query("filename")
func headGatewayFileDownload(w http.ResponseWriter, r *http.Request) {
filePath := r.URL.Query().Get("filename")
fileName := filepath.Base(filePath)
c.Header("Content-Type", "application/octet-stream")
c.Header("Content-Disposition", "attachment; filename="+fileName)
c.Header("Content-Transfer-Encoding", "binary")
fmt.Println(filePath)
fi, err := os.Stat(filePath)
if err == nil {
fmt.Println("file size is ", fi.Size(), err)
}
c.Header("Content-Length", strconv.FormatInt(fi.Size(), 10))
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment; filename="+fileName)
w.Header().Set("Content-Transfer-Encoding", "binary")
if fi, err := os.Stat(filePath); err == nil {
w.Header().Set("Content-Length", strconv.FormatInt(fi.Size(), 10))
}
w.WriteHeader(http.StatusOK)
}
type Win32_Volume struct {
@@ -350,49 +262,54 @@ type FileData struct {
Md5 string `json:"md5"`
}
func postGatewayFileUpload() gin.HandlerFunc {
return func(c *gin.Context) {
dir := c.Query("dir")
file, err := HttpUploadFile(c, dir)
func postGatewayFileUpload(w http.ResponseWriter, r *http.Request) {
dir := r.URL.Query().Get("dir")
file, err := HttpUploadFile(r, dir)
if err != nil {
c.JSON(http.StatusOK, gin.H{
webhttp.WriteJSON(w, http.StatusOK, map[string]any{
"code": 1,
"msg": "上传失败:" + err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
webhttp.WriteJSON(w, http.StatusOK, map[string]any{
"code": 0,
"msg": "success",
"status": "done",
"file": file,
})
}
}
func HttpUploadFile(c *gin.Context, saveDir string) (*FileData, error) {
file, err := c.FormFile("file")
// HttpUploadFile 接收 multipart 上传并落盘。
// 不沿用 gin SaveUploadedFile 的 MkdirAll+Chmod: Windows 盘根上 Chmod 报
// "参数不正确" 导致盘根上传必败(remote-service 已用流式接管绕开此坑, 这里
// 是非 multipart 请求的兜底路径), 目录创建保留、Chmod 去掉。
func HttpUploadFile(r *http.Request, saveDir string) (*FileData, error) {
fh, head, err := r.FormFile("file")
if err != nil {
return nil, err
}
defer fh.Close()
fileName := file.Filename
// 保存路径 绝对路径
savePath := filepath.Join(saveDir, file.Filename)
err = c.SaveUploadedFile(file, savePath)
if err != nil {
savePath := filepath.Join(saveDir, head.Filename)
if err = os.MkdirAll(filepath.Dir(savePath), 0755); err != nil {
return nil, err
}
fileData := &FileData{
OriginalFileName: file.Filename,
FileName: fileName,
out, err := os.Create(savePath)
if err != nil {
return nil, err
}
defer out.Close()
if _, err = io.Copy(out, fh); err != nil {
return nil, err
}
return &FileData{
OriginalFileName: head.Filename,
FileName: head.Filename,
FilePath: savePath,
Size: file.Size,
}
return fileData, nil
Size: head.Size,
}, nil
}
+4 -29
View File
@@ -4,7 +4,6 @@ go 1.26.0
require (
github.com/KarpelesLab/vncpasswd v1.0.1
github.com/gin-gonic/gin v1.12.0
github.com/gorilla/websocket v1.5.3
github.com/jaypipes/ghw v0.13.0
github.com/kardianos/service v1.2.2
@@ -17,45 +16,21 @@ require (
require (
github.com/StackExchange/wmi v1.2.1 // indirect
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.15.0 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/creack/pty v1.1.17 // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.30.4 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/iamacarpet/go-winpty v1.0.2 // indirect
github.com/jaypipes/pcidb v1.0.1 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.5.0 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect
github.com/rogpeppe/go-internal v1.10.0 // indirect
github.com/shoenig/go-m1cpu v0.1.6 // 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
github.com/ugorji/go/codec v1.3.1 // indirect
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
golang.org/x/arch v0.22.0 // indirect
golang.org/x/crypto v0.57.0 // indirect
golang.org/x/net v0.58.0 // indirect
golang.org/x/text v0.42.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
howett.net/plist v1.0.0 // indirect
)
+6 -75
View File
@@ -2,44 +2,16 @@ github.com/KarpelesLab/vncpasswd v1.0.1 h1:w0dhjSXfo59bm9/LLKhO7hV+GUGEn4WjAZTLX
github.com/KarpelesLab/vncpasswd v1.0.1/go.mod h1:gh6AFDSUqRZwcdjAm/p8V81P9ePtOI65ajs7KT7D+Fc=
github.com/StackExchange/wmi v1.2.1 h1:VIkavFPXSjcnS+O8yTq7NI32k0R5Aj+v39y29VYDOSA=
github.com/StackExchange/wmi v1.2.1/go.mod h1:rcmrprowKIVzvc+NUiLncP2uuArMWLCbu9SBzvHz7e8=
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/creack/pty v1.1.17 h1:QeVUsEDNrLBW4tMgZHvxy18sKtr6VI492kBhUfhDJNI=
github.com/creack/pty v1.1.17/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
github.com/go-ole/go-ole v1.2.5/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.30.4 h1:9Rcod2ZPO6mOEG6b4GqyoHE/H6//Ze0RuhOo1hT1x0w=
github.com/go-playground/validator/v10 v10.30.4/go.mod h1:numpT+RPLE91R9oYWMY/R9zRgJBewr3IXHko4OISPpk=
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.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/iamacarpet/go-winpty v1.0.2 h1:jwPVTYrjAHZx6Mcm6K5i9G4opMp5TblEHH5EQCl/Gzw=
@@ -49,40 +21,26 @@ github.com/jaypipes/ghw v0.13.0/go.mod h1:In8SsaDqlb1oTyrbmTC14uy+fbBMvp+xdqX51M
github.com/jaypipes/pcidb v1.0.1 h1:WB2zh27T3nwg8AE8ei81sNRb9yWBii3JGNJtT7K9Oic=
github.com/jaypipes/pcidb v1.0.1/go.mod h1:6xYUz/yYEyOkIkUt2t2J2folIuZ4Yg6uByCGFXMCeE4=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
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/kardianos/service v1.2.2 h1:ZvePhAHfvo0A7Mftk/tEzqEZ7Q4lgnR8sGz4xu1YX60=
github.com/kardianos/service v1.2.2/go.mod h1:CIMRFEJVL+0DS1a3Nx06NaMn4Dz63Ng6O7dl0qH0zVM=
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.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
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/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/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw=
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/runletapp/go-console v0.0.0-20211204140000-27323a28410a h1:1hh8CSomjZSJPk7AgHV8o33Su13bZby81PrC6pIvJqQ=
@@ -96,52 +54,25 @@ github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnj
github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo=
github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q=
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=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU=
github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=
github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk=
github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
+21 -19
View File
@@ -5,14 +5,16 @@
package process
import (
"encoding/json"
"net/http"
"os/exec"
"runtime"
"sort"
"strconv"
"github.com/gin-gonic/gin"
"github.com/shirou/gopsutil/v3/process"
"git.zeroonesoft.cn/golib/remote-core/webhttp"
)
// ProcItem 进程列表行。
@@ -30,17 +32,20 @@ type ProcItem struct {
}
// RegisterRoutersProcess 装配进程管理路由: GET /process/list, POST /process/kill。
func RegisterRoutersProcess(r *gin.RouterGroup) {
r.GET("/process/list", listProcesses())
r.POST("/process/kill", killProcess())
func RegisterRoutersProcess(r webhttp.Router) {
r.GET("/process/list", listProcesses)
r.POST("/process/kill", killProcess)
}
func fail(w http.ResponseWriter, msg string) {
webhttp.WriteJSON(w, http.StatusOK, map[string]any{"code": 1, "msg": msg, "data": nil})
}
// listProcesses 全量进程列表(按内存占用降序)。
func listProcesses() gin.HandlerFunc {
return func(c *gin.Context) {
func listProcesses(w http.ResponseWriter, _ *http.Request) {
procs, err := process.Processes()
if err != nil {
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "枚举进程失败: " + err.Error(), "data": nil})
fail(w, "枚举进程失败: "+err.Error())
return
}
items := make([]ProcItem, 0, len(procs))
@@ -76,43 +81,40 @@ func listProcesses() gin.HandlerFunc {
items = append(items, item)
}
sort.Slice(items, func(i, j int) bool { return items[i].MemPercent > items[j].MemPercent })
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "OK", "data": gin.H{"list": items}})
}
webhttp.WriteJSON(w, http.StatusOK, map[string]any{"code": 0, "msg": "OK", "data": map[string]any{"list": items}})
}
// killProcess 结束进程: {pid: 必填, name: 可选校验(防 pid 复用误杀)}。
// Windows 上 gopsutil 权限不足时回退 taskkill /F /T(连子进程树强杀)。
func killProcess() gin.HandlerFunc {
return func(c *gin.Context) {
func killProcess(w http.ResponseWriter, r *http.Request) {
var req struct {
Pid int32 `json:"pid"`
Name string `json:"name"`
}
if err := c.ShouldBindJSON(&req); err != nil || req.Pid <= 0 {
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "参数错误: pid 必填且为正整数", "data": nil})
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Pid <= 0 {
fail(w, "参数错误: pid 必填且为正整数")
return
}
p, err := process.NewProcess(req.Pid)
if err != nil {
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "进程不存在: " + err.Error(), "data": nil})
fail(w, "进程不存在: "+err.Error())
return
}
if req.Name != "" {
if name, e := p.Name(); e == nil && name != "" && name != req.Name {
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "进程名不匹配(实际 " + name + "), 已拒绝结束", "data": nil})
fail(w, "进程名不匹配(实际 "+name+"), 已拒绝结束")
return
}
}
if err := p.Kill(); err != nil {
if runtime.GOOS != "windows" {
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "结束进程失败: " + err.Error(), "data": nil})
fail(w, "结束进程失败: "+err.Error())
return
}
if out, e := exec.Command("taskkill", "/F", "/T", "/PID", strconv.Itoa(int(req.Pid))).CombinedOutput(); e != nil {
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "结束进程失败: " + err.Error() + "; taskkill: " + string(out), "data": nil})
fail(w, "结束进程失败: "+err.Error()+"; taskkill: "+string(out))
return
}
}
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "OK", "data": gin.H{"pid": req.Pid}})
}
webhttp.WriteJSON(w, http.StatusOK, map[string]any{"code": 0, "msg": "OK", "data": map[string]any{"pid": req.Pid}})
}
+5 -1
View File
@@ -1,7 +1,11 @@
// Package remote 提供 RDP/VNC 等远程控制的服务状态查询、配置读写与启停控制。
package remote
// VncServerConfig TightVNC 服务端配置(对应注册表 SOFTWARE\TightVNC\Server 下的键值)
// VncServerConfig TightVNC 服务端配置(对应注册表 SOFTWARE\TightVNC\Server 下的键值)。
// 37 项 = 最新版 TightVNC(2.8.x) 标准安装落盘的全集(经本机注册表与 tvnserver.exe
// 字符串表双重核对)。另有 ViewOnlyPassword / ControlPassword 两个条件值(只读密码、
// 控制接口管理密码,开对应功能才会写入,本库暂不覆盖——WriteVncServerConfig 是
// 无条件全量写,加字段会向每台客户机落空值),待产品启用只读接入/控制认证时再扩展。
type VncServerConfig struct {
ExtraPorts string `json:"extraPorts"` // 额外端口
QueryTimeout uint32 `json:"queryTimeout"` // 查询超时
+49 -59
View File
@@ -1,31 +1,25 @@
package shell
// 移植自 remote-backend-server internal/handlers/shell(去 DB 依赖, ConPTY 终端 + asciinema 录制)。
// 标准库 http.HandlerFunc 形态, 路由注册经 webhttp.Router 适配(去 gin 化)。
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/runletapp/go-console"
"github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
"os"
"path"
"git.zeroonesoft.cn/golib/remote-core/common"
"path/filepath"
"runtime"
"strings"
"time"
)
type windowSize struct {
Rows uint16 `json:"rows"`
Cols uint16 `json:"cols"`
X uint16
Y uint16
}
"github.com/gorilla/websocket"
"github.com/runletapp/go-console"
"github.com/sirupsen/logrus"
"git.zeroonesoft.cn/golib/remote-core/common"
"git.zeroonesoft.cn/golib/remote-core/webhttp"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
@@ -46,16 +40,22 @@ type ResizeDataType struct {
Rows int `json:"rows"`
}
// RegisterRoutersWebShell 注册路由
func RegisterRoutersWebShell(r *gin.RouterGroup, recDir string) {
r.GET("/web/shell", getWebShell(recDir))
// recStoreDir 会话录制目录, Register 时注入; 录制写入与记录列表两处共用。
// 原实现硬编码 ./rec, recDir 形参是死参数(remote-service 传 RunDir/rec 不生效)。
var recStoreDir = "./rec"
// RegisterRoutersWebShell 注册路由。recDir 为会话录制目录, 传空退回 ./rec。
func RegisterRoutersWebShell(r webhttp.Router, recDir string) {
if recDir != "" {
recStoreDir = recDir
}
r.GET("/web/shell", getWebShell)
r.GET("/web/shell/record", RecoderList)
}
func getWebShell(recDir string) gin.HandlerFunc {
return func(c *gin.Context) {
func getWebShell(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logrus.Errorf("Unable to upgrade connection")
return
@@ -63,7 +63,9 @@ func getWebShell(recDir string) gin.HandlerFunc {
proc, err := console.New(180, 30)
if err != nil {
panic(err)
logrus.Errorf("创建终端失败:%s", err.Error())
conn.Close()
return
}
arr := make([]string, 0)
@@ -80,12 +82,8 @@ func getWebShell(recDir string) gin.HandlerFunc {
if err := proc.Start(arr); err != nil {
logrus.Errorf("启动出错:%s", err.Error())
panic(err)
}
if err != nil {
logrus.Errorf("Unable to start pty/cmd")
conn.WriteMessage(websocket.TextMessage, []byte(err.Error()))
conn.Close()
return
}
defer func() {
@@ -95,8 +93,8 @@ func getWebShell(recDir string) gin.HandlerFunc {
var recorder *Recorder
os.MkdirAll("./rec", 0766)
fileName := path.Join("./rec/", fmt.Sprintf("%s.cast", time.Now().Format("20060102_150405")))
os.MkdirAll(recStoreDir, 0766)
fileName := filepath.Join(recStoreDir, fmt.Sprintf("%s.cast", time.Now().Format("20060102_150405")))
logrus.Debugf("记录文件名:%s", fileName)
f, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0766)
if err != nil {
@@ -156,7 +154,6 @@ func getWebShell(recDir string) gin.HandlerFunc {
opData := OpDataType{}
newBuf := buf[:n]
fmt.Println("收到数据", string(newBuf))
err = json.Unmarshal(newBuf, &opData)
if err != nil {
logrus.Errorf("解析错误:%s", err.Error())
@@ -164,44 +161,37 @@ func getWebShell(recDir string) gin.HandlerFunc {
if opData.Op == "stdin" {
value, ok := opData.Data.(string)
if ok {
n, err = proc.Write([]byte(value))
if err != nil {
logrus.Errorf("写放数据错误g %d bytes", n)
} else {
fmt.Println("写入成功")
}
} else {
}
} else if opData.Op == "resize" {
fmt.Println("resize")
value, ok := opData.Data.(ResizeDataType)
if ok {
err = proc.SetSize(value.Cols, value.Rows)
// Data 反序列化后是 map[string]interface{}, 不能直接断言 ResizeDataType
// (此前断言恒失败, 前端 resize 被静默吞掉, PTY 固定 180x30)
raw, merr := json.Marshal(opData.Data)
var size ResizeDataType
if merr == nil && json.Unmarshal(raw, &size) == nil && size.Cols > 0 && size.Rows > 0 {
if serr := proc.SetSize(size.Cols, size.Rows); serr != nil {
logrus.Errorf("重置大小错误: %s", serr.Error())
}
}
}
}
}
}
func RecoderList(w http.ResponseWriter, _ *http.Request) {
files, err := os.ReadDir(recStoreDir)
if err != nil {
logrus.Errorf("重置大小错误 %d bytes", n)
} else {
fmt.Println("重置大小成功")
}
} else {
}
}
}
}
}
}
func RecoderList(c *gin.Context) {
files, err := ioutil.ReadDir("./rec")
if err != nil {
c.AbortWithStatusJSON(200, gin.H{"ok": false, "msg": err.Error()})
webhttp.WriteJSON(w, http.StatusOK, map[string]any{"ok": false, "msg": err.Error()})
return
}
var filesName []string
@@ -214,5 +204,5 @@ func RecoderList(c *gin.Context) {
filesName = append(filesName, f.Name())
}
}
c.JSON(200, filesName)
webhttp.WriteJSON(w, http.StatusOK, filesName)
}
+69
View File
@@ -0,0 +1,69 @@
// Package webhttp 被控 HTTP 能力的极薄适配层。
//
// file/shell/process 三个被控能力包统一以标准库 http.HandlerFunc 为 handler
// 形态、以 Router 接口收拢路由注册, 不再绑死任何 Web 框架。消费方按自身
// 技术栈适配: 纯标准库用 ServeMuxRouter 直挂 *http.ServeMux(Go 1.22+ 方法
// +路径模式); 已有 gin 栈的用 gin.WrapH 桥接, 中间件链照常生效。
//
// 由此 gin(连带其拖入的 quic-go/http3、mongo bson、ugorji codec、goccy
// 等重依赖)从被控端二进制中整体消失, 体积近乎减半。
package webhttp
import (
"encoding/json"
"net/http"
)
// Router file/shell/process 声明路由用的最小接口(pattern 形如
// "/file/list", 不含组前缀; 前缀由适配器拼)。
type Router interface {
GET(pattern string, h http.HandlerFunc)
POST(pattern string, h http.HandlerFunc)
PUT(pattern string, h http.HandlerFunc)
DELETE(pattern string, h http.HandlerFunc)
HEAD(pattern string, h http.HandlerFunc)
}
// ServeMuxRouter 把 *http.ServeMux 适配为 Router, 注册
// "METHOD prefix+pattern" 模式路由(如 "GET /api/file/list")。
// 注册了 GET 的路径自动兼容 HEAD。
func ServeMuxRouter(mux *http.ServeMux, prefix string) Router {
return &muxRouter{mux: mux, prefix: prefix}
}
type muxRouter struct {
mux *http.ServeMux
prefix string
}
func (m *muxRouter) route(method, pattern string) string {
return method + " " + m.prefix + pattern
}
func (m *muxRouter) GET(pattern string, h http.HandlerFunc) {
m.mux.HandleFunc(m.route(http.MethodGet, pattern), h)
}
func (m *muxRouter) POST(pattern string, h http.HandlerFunc) {
m.mux.HandleFunc(m.route(http.MethodPost, pattern), h)
}
func (m *muxRouter) PUT(pattern string, h http.HandlerFunc) {
m.mux.HandleFunc(m.route(http.MethodPut, pattern), h)
}
func (m *muxRouter) DELETE(pattern string, h http.HandlerFunc) {
m.mux.HandleFunc(m.route(http.MethodDelete, pattern), h)
}
func (m *muxRouter) HEAD(pattern string, h http.HandlerFunc) {
m.mux.HandleFunc(m.route(http.MethodHead, pattern), h)
}
// WriteJSON 统一 JSON 响应(响应头口径与原 gin c.JSON 一致)。
// 业务码仍在 body 的 code 字段, HTTP 状态恒 200, 与既有前端约定不变。
func WriteJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}