feat(device): 文件通道 pull/push

core 与设备复用同一条 WS 搬文件:256KiB 分块、base64、50MiB 上限,
写盘先 .part 再校验 size/sha256 后 rename;device 工具新增 pull/push 两个动作。
This commit is contained in:
2026-11-19 19:01:34 +08:00
parent 4a36cc0266
commit 3c9f9d2bdb
7 changed files with 443 additions and 4 deletions
+14
View File
@@ -98,6 +98,7 @@ sh scripts/build.sh all
|---|---|
| 设备 → core | `{t:"hello", ver, name, os, arch, shell, shell_path, shell_ver, root}` |
| core → 设备 | `{t:"exec", id, cmd, cwd, timeout_ms}` · `{t:"kill", id}` · `{t:"ping"}` · `{t:"health", id}` |
| 文件通道 | `{t:"file", id, op:"read"\|"write", path, size?, sha256?}` · `{t:"file.chunk", id, data:<base64>}` ×N · `{t:"file.done", id, size?, sha256?, err?}` |
| 设备 → core | `{t:"chunk", id, out:"out"\|"err", chunk:<base64>}` · `{t:"exit", id, code, killed_by, ms, truncated}` · `{t:"pong"}` · `{t:"health", …}` |
- 保活:core 每 20 秒发 `ping`,设备回 `pong`;90 秒无任何消息即断开重连。
@@ -106,6 +107,19 @@ sh scripts/build.sh all
- 输出:单流超过上限截断并置 `truncated`。
- `shell` 报的是实际解释器(`/bin/sh` 可能是 dash / bash / busybox),连同版本,供模型决定命令语法。
## 文件通道
core 通过同一条连接搬文件,**设备不需要任何额外端口**:
| 方向 | 流程 |
|---|---|
| 拉取(设备 → 会话目录) | `file{op:read}` → 设备分块回 `file.chunk` → `file.done{size,sha256}` |
| 推送(会话目录 → 设备) | `file{op:write,size,sha256}` → 分块 `file.chunk` → `file.done` |
- 每块 256 KiB(base64 后约 341 KiB),单文件上限 50 MiB;
- 写盘先落 `<path>.part`,`size` 与 `sha256` 都对上才 `rename`;
- 设备侧路径必须在工作根内(与 `exec` 的 cwd 校验同一套)。
## 安全边界
- 设备主动出站,服务端不需要知道设备 IP;
+237
View File
@@ -0,0 +1,237 @@
package main
// 文件通道:core 通过同一条 WS 拉取 / 推送文件。
//
// 协议(与 core 的 devices.js 一一对应):
//
// core → 节点 {t:"file", id, op:"read", path}
// 节点 → core {t:"file.chunk", id, data:<base64>} ×N → {t:"file.done", id, size, sha256}
//
// core → 节点 {t:"file", id, op:"write", path, size, sha256}
// core → 节点 {t:"file.chunk", id, data} ×N → {t:"file.done", id}
// 节点 → core {t:"file.done", id, size} 或 {t:"file.done", id, err}
//
// 写盘一律先落 <path>.part,校验通过再 rename——半截文件不能留在原地。
import (
"crypto/sha256"
"encoding/hex"
"errors"
"hash"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"agent-device/pkg/wsnode"
"agent-device/pkg/proto"
)
const (
fileChunkSize = 256 << 10 // 每块 256 KiB(base64 后约 341 KiB)
maxFileBytes = 50 << 20 // 单文件上限 50 MiB
)
type fileWriter struct {
path string
tmp *os.File
tmpPath string
hash hash.Hash
got int64
// 期望值(core 下发时给的,用于对账)
size int64
sha string
}
type fileMgr struct {
mu sync.Mutex
writers map[string]*fileWriter
}
func newFileMgr() *fileMgr {
return &fileMgr{writers: map[string]*fileWriter{}}
}
// safePath 把设备侧路径限制在 root 之内(与 exec 的 cwd 校验同一套语义)。
func (r *runner) safePath(raw string) (string, error) {
if raw == "" {
return "", errors.New("path 不能为空")
}
p := raw
if !filepath.IsAbs(p) {
p = filepath.Join(r.root, p)
}
p = filepath.Clean(p)
rel, err := filepath.Rel(r.root, p)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return "", errors.New("path 超出工作根:" + raw)
}
return p, nil
}
func (r *runner) fileStart(c *wsnode.Conn, m proto.Msg) {
switch m.Op {
case "read":
go r.fileRead(c, m)
case "write":
r.fileBegin(c, m)
default:
r.fileFail(c, m.ID, "未知的 file.op:"+m.Op)
}
}
func (r *runner) fileFail(c *wsnode.Conn, id, msg string) {
_ = c.Send(proto.Msg{T: proto.TKindFileDone, ID: id, Err: msg})
}
// fileRead 把设备上的文件分块推回 core。
func (r *runner) fileRead(c *wsnode.Conn, m proto.Msg) {
p, err := r.safePath(m.Path)
if err != nil {
r.fileFail(c, m.ID, err.Error())
return
}
f, err := os.Open(p)
if err != nil {
r.fileFail(c, m.ID, err.Error())
return
}
defer f.Close()
st, err := f.Stat()
if err != nil {
r.fileFail(c, m.ID, err.Error())
return
}
if st.IsDir() {
r.fileFail(c, m.ID, "是目录,不是文件:"+p)
return
}
if st.Size() > maxFileBytes {
r.fileFail(c, m.ID, "文件超过 50MiB 上限")
return
}
h := sha256.New()
buf := make([]byte, fileChunkSize)
var sent int64
for {
n, rerr := f.Read(buf)
if n > 0 {
h.Write(buf[:n])
sent += int64(n)
if err := c.Send(proto.Msg{
T: proto.TKindFileChunk, ID: m.ID,
Data: append([]byte(nil), buf[:n]...),
}); err != nil {
return
}
}
if rerr == io.EOF {
break
}
if rerr != nil {
r.fileFail(c, m.ID, rerr.Error())
return
}
}
_ = c.Send(proto.Msg{
T: proto.TKindFileDone, ID: m.ID,
Size: sent, SHA: hex.EncodeToString(h.Sum(nil)),
})
}
// fileBegin 为一次 write 建立临时文件。
func (r *runner) fileBegin(c *wsnode.Conn, m proto.Msg) {
p, err := r.safePath(m.Path)
if err != nil {
r.fileFail(c, m.ID, err.Error())
return
}
if m.Size > maxFileBytes {
r.fileFail(c, m.ID, "文件超过 50MiB 上限")
return
}
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
r.fileFail(c, m.ID, err.Error())
return
}
tmpPath := p + ".part"
f, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644)
if err != nil {
r.fileFail(c, m.ID, err.Error())
return
}
r.files.mu.Lock()
r.files.writers[m.ID] = &fileWriter{
path: p, tmp: f, tmpPath: tmpPath, hash: sha256.New(),
size: m.Size, sha: m.SHA,
}
r.files.mu.Unlock()
}
func (r *runner) fileChunk(c *wsnode.Conn, m proto.Msg) {
r.files.mu.Lock()
w := r.files.writers[m.ID]
r.files.mu.Unlock()
if w == nil {
return
}
if w.got+int64(len(m.Data)) > maxFileBytes {
r.abortWriter(m.ID, w, "超过 50MiB 上限")
r.fileFail(c, m.ID, "超过 50MiB 上限")
return
}
if _, err := w.tmp.Write(m.Data); err != nil {
r.abortWriter(m.ID, w, err.Error())
r.fileFail(c, m.ID, err.Error())
return
}
w.hash.Write(m.Data)
w.got += int64(len(m.Data))
}
// fileEnd 收尾写入:校验大小与 sha256,通过才改名到正式路径。
func (r *runner) fileEnd(c *wsnode.Conn, m proto.Msg) {
r.files.mu.Lock()
w := r.files.writers[m.ID]
delete(r.files.writers, m.ID)
r.files.mu.Unlock()
if w == nil {
return
}
defer func() { _ = w.tmp.Close() }()
sum := hex.EncodeToString(w.hash.Sum(nil))
if w.size > 0 && w.got != w.size {
_ = os.Remove(w.tmpPath)
r.fileFail(c, m.ID, "大小不符:收到 "+strconv.FormatInt(w.got, 10)+",应为 "+strconv.FormatInt(w.size, 10))
return
}
if w.sha != "" && !strings.EqualFold(w.sha, sum) {
_ = os.Remove(w.tmpPath)
r.fileFail(c, m.ID, "sha256 不符")
return
}
if err := w.tmp.Close(); err != nil {
_ = os.Remove(w.tmpPath)
r.fileFail(c, m.ID, err.Error())
return
}
if err := os.Rename(w.tmpPath, w.path); err != nil {
_ = os.Remove(w.tmpPath)
r.fileFail(c, m.ID, err.Error())
return
}
_ = c.Send(proto.Msg{T: proto.TKindFileDone, ID: m.ID, Size: w.got, SHA: sum})
}
func (r *runner) abortWriter(id string, w *fileWriter, why string) {
r.files.mu.Lock()
delete(r.files.writers, id)
r.files.mu.Unlock()
_ = w.tmp.Close()
_ = os.Remove(w.tmpPath)
}
+10
View File
@@ -78,6 +78,8 @@ type runner struct {
mu sync.Mutex
procs map[string]*proc
files *fileMgr // 文件通道:core 拉取/推送文件时的在途写入
}
func main() {
@@ -154,6 +156,7 @@ func main() {
shell: *shellName,
sem: make(chan struct{}, maxParallel),
procs: map[string]*proc{},
files: newFileMgr(),
}
if r.root == "" {
home, _ := os.UserHomeDir()
@@ -202,6 +205,13 @@ func main() {
}
case proto.TKindPing:
_ = c.Send(proto.Msg{T: proto.TKindPong})
case proto.TKindFile:
// write 的建栅必须同步完成:core 紧接着就发 chunk,异步会先到后建、丢块
r.fileStart(c, m)
case proto.TKindFileChunk:
r.fileChunk(c, m)
case proto.TKindFileDone:
r.fileEnd(c, m)
case proto.TKindHealth:
h := hostHealth()
m := proto.Msg{
+10
View File
@@ -12,6 +12,9 @@ const (
TKindPing = "ping" // hub → 节点:保活
TKindPong = "pong" // 节点 → hub:保活回应
TKindHealth = "health" // 双向:hub 要指标 / 节点回指标
TKindFile = "file" // 双向:core 发起一次 read/write
TKindFileChunk = "file.chunk" // 双向:文件数据块(base64)
TKindFileDone = "file.done" // 双向:结束,带 size / sha256 / err
)
// Msg 是双向通用信封:不同 t 只用其中一部分字段,其余 omitempty。
@@ -55,4 +58,11 @@ type Msg struct {
DiskTotalGB float64 `json:"disk_total_gb,omitempty"`
DiskFreeGB float64 `json:"disk_free_gb,omitempty"`
TempC float64 `json:"temp_c,omitempty"`
// file(read/write 共用一个 信封)
Op string `json:"op,omitempty"` // read | write
Path string `json:"path,omitempty"` // 设备侧绝对路径,必须在 root 内
Size int64 `json:"size,omitempty"` // 文件字节数
SHA string `json:"sha256,omitempty"` // 文件内容的 sha256(传完对账)
Data []byte `json:"data,omitempty"` // 数据块(JSON 里是 base64)
}