feat: 实现电脑端被控与控制界面
This commit is contained in:
@@ -0,0 +1,811 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/idutil"
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/protocol"
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/shell"
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
dedupWindow = 24 * time.Hour
|
||||
defaultMaxTTL = int64(2592000)
|
||||
defaultMaxSchedule = int64(31536000)
|
||||
)
|
||||
|
||||
// Outbox 是要发出的一条正文。
|
||||
type Outbox struct {
|
||||
To string
|
||||
Body []byte
|
||||
}
|
||||
|
||||
// Delivery 是发送选项,不写入正文。
|
||||
type Delivery struct {
|
||||
SendAt *time.Time
|
||||
Keep bool
|
||||
TTL *int64
|
||||
}
|
||||
|
||||
// Limits 来自连接握手,为零时用默认上限。
|
||||
type Limits struct {
|
||||
MaxTTL int64
|
||||
MaxSchedule int64
|
||||
}
|
||||
|
||||
func (l Limits) ttl() int64 {
|
||||
if l.MaxTTL > 0 {
|
||||
return l.MaxTTL
|
||||
}
|
||||
return defaultMaxTTL
|
||||
}
|
||||
|
||||
func (l Limits) schedule() int64 {
|
||||
if l.MaxSchedule > 0 {
|
||||
return l.MaxSchedule
|
||||
}
|
||||
return defaultMaxSchedule
|
||||
}
|
||||
|
||||
// Engine 处理信任、执行、快捷命令和去重。不连接网络。
|
||||
type Engine struct {
|
||||
st *store.Store
|
||||
run shell.Runner
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func New(st *store.Store, run shell.Runner) *Engine {
|
||||
if run == nil {
|
||||
run = shell.System{}
|
||||
}
|
||||
return &Engine{st: st, run: run, now: time.Now}
|
||||
}
|
||||
|
||||
// Accept 处理一条收到的正文,返回需要回复的消息。
|
||||
// 同一 id 在 24 小时内只执行一次。未信任不执行。
|
||||
func (e *Engine) Accept(from, raw string) ([]Outbox, []protocol.Log, error) {
|
||||
msg, err := protocol.Parse(raw)
|
||||
if err != nil || msg.V != protocol.Version {
|
||||
return nil, nil, nil
|
||||
}
|
||||
switch msg.Type {
|
||||
case protocol.TypeShell:
|
||||
return e.acceptCommand(from, msg.ID, msg.Shell, false, "")
|
||||
case protocol.TypeShortcut:
|
||||
return e.acceptCommand(from, msg.ID, "", true, msg.ShortcutID)
|
||||
case protocol.TypeText:
|
||||
return nil, nil, e.acceptText(from, msg)
|
||||
case protocol.TypeShortcuts:
|
||||
return nil, nil, e.acceptShortcuts(from, msg)
|
||||
case protocol.TypeShortcutsGet:
|
||||
return e.replyShortcuts(from, msg.ID)
|
||||
case protocol.TypeLogsGet:
|
||||
return e.replyLogs(from, msg.ID)
|
||||
case protocol.TypeLogs:
|
||||
return nil, nil, e.acceptLogs(from, msg)
|
||||
case protocol.TypeResult:
|
||||
return nil, nil, e.acceptResult(from, msg)
|
||||
default:
|
||||
return nil, nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Engine) acceptCommand(from, id, script string, shortcut bool, shortcutID string) ([]Outbox, []protocol.Log, error) {
|
||||
if !idutil.ValidMessage(id) {
|
||||
return nil, nil, nil
|
||||
}
|
||||
now := e.now()
|
||||
var (
|
||||
reply []byte
|
||||
fresh bool
|
||||
runSh string
|
||||
)
|
||||
err := e.st.Update(func(d *store.Data) error {
|
||||
store.TrimExecuted(d, now, dedupWindow)
|
||||
if prev, ok := findExecuted(d, id); ok {
|
||||
body, err := protocol.ResultBody(id, prev.OK, prev.Error, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reply = body
|
||||
return nil
|
||||
}
|
||||
fresh = true
|
||||
if !trusted(d, from) {
|
||||
body, err := protocol.ResultBody(id, false, protocol.ErrNotTrusted, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reply = body
|
||||
d.Executed = append(d.Executed, store.Executed{ID: id, At: now, OK: false, Error: protocol.ErrNotTrusted})
|
||||
return nil
|
||||
}
|
||||
if shortcut {
|
||||
item, ok := findPublished(d, shortcutID)
|
||||
if !ok {
|
||||
body, err := protocol.ResultBody(id, false, "没有这条命令", false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reply = body
|
||||
d.Executed = append(d.Executed, store.Executed{ID: id, At: now, OK: false, Error: "没有这条命令"})
|
||||
return nil
|
||||
}
|
||||
script = item.Shell
|
||||
}
|
||||
script = strings.TrimSpace(script)
|
||||
if script == "" {
|
||||
body, err := protocol.ResultBody(id, false, "命令是空的", false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reply = body
|
||||
d.Executed = append(d.Executed, store.Executed{ID: id, At: now, OK: false, Error: "命令是空的"})
|
||||
return nil
|
||||
}
|
||||
runSh = script
|
||||
// 先占住这个 id,避免执行过程中的重复投递再跑一次。
|
||||
d.Executed = append(d.Executed, store.Executed{ID: id, At: now, OK: false, Error: "正在执行"})
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !fresh || runSh == "" {
|
||||
if reply == nil {
|
||||
return nil, nil, nil
|
||||
}
|
||||
return []Outbox{{To: from, Body: reply}}, nil, nil
|
||||
}
|
||||
|
||||
out, runErr := e.run.Run(context.Background(), runSh)
|
||||
ok, detail := shell.Summarize(out, runErr)
|
||||
body, err := protocol.ResultBody(id, ok, errText(ok, detail), false)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
logItem := protocol.Log{
|
||||
At: now.UTC().Format(time.RFC3339),
|
||||
Summary: shell.Summary(runSh),
|
||||
OK: ok,
|
||||
Detail: detail,
|
||||
}
|
||||
var upload []protocol.Log
|
||||
err = e.st.Update(func(d *store.Data) error {
|
||||
for i := range d.Executed {
|
||||
if d.Executed[i].ID == id {
|
||||
d.Executed[i].OK = ok
|
||||
d.Executed[i].Error = errText(ok, detail)
|
||||
d.Executed[i].Detail = detail
|
||||
break
|
||||
}
|
||||
}
|
||||
upload = store.AppendLog(d, logItem)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return []Outbox{{To: from, Body: body}}, upload, nil
|
||||
}
|
||||
|
||||
func errText(ok bool, detail string) string {
|
||||
if ok {
|
||||
return ""
|
||||
}
|
||||
if detail == "" {
|
||||
return "没有成功"
|
||||
}
|
||||
return detail
|
||||
}
|
||||
|
||||
func (e *Engine) acceptText(from string, msg protocol.Message) error {
|
||||
text := strings.TrimSpace(msg.Text)
|
||||
if text == "" {
|
||||
return nil
|
||||
}
|
||||
return e.st.Update(func(d *store.Data) error {
|
||||
d.Inbox = append(d.Inbox, store.TextMsg{
|
||||
ID: msg.ID,
|
||||
From: from,
|
||||
Text: text,
|
||||
At: e.now(),
|
||||
})
|
||||
if len(d.Inbox) > 200 {
|
||||
d.Inbox = append([]store.TextMsg(nil), d.Inbox[len(d.Inbox)-200:]...)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (e *Engine) acceptShortcuts(from string, msg protocol.Message) error {
|
||||
items := append([]protocol.Shortcut(nil), msg.Items...)
|
||||
return e.st.Update(func(d *store.Data) error {
|
||||
prev := d.Remote[from]
|
||||
prev.Items = items
|
||||
prev.SyncedAt = e.now()
|
||||
prev.Syncing = false
|
||||
prev.ReqID = ""
|
||||
d.Remote[from] = prev
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (e *Engine) acceptLogs(from string, msg protocol.Message) error {
|
||||
items := append([]protocol.Log(nil), msg.Logs...)
|
||||
return e.st.Update(func(d *store.Data) error {
|
||||
prev := d.RemoteLogs[from]
|
||||
prev.Items = items
|
||||
prev.SyncedAt = e.now()
|
||||
prev.Syncing = false
|
||||
prev.ReqID = ""
|
||||
prev.Error = msg.Error
|
||||
d.RemoteLogs[from] = prev
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (e *Engine) acceptResult(from string, msg protocol.Message) error {
|
||||
if msg.ID == "" || msg.OK == nil {
|
||||
return nil
|
||||
}
|
||||
ok := *msg.OK
|
||||
return e.st.Update(func(d *store.Data) error {
|
||||
d.Results = append(d.Results, store.CmdResult{
|
||||
ID: msg.ID,
|
||||
Remote: from,
|
||||
OK: ok,
|
||||
Error: msg.Error,
|
||||
Duplicate: msg.Duplicate,
|
||||
At: e.now(),
|
||||
})
|
||||
if len(d.Results) > 200 {
|
||||
d.Results = append([]store.CmdResult(nil), d.Results[len(d.Results)-200:]...)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (e *Engine) replyShortcuts(from, id string) ([]Outbox, []protocol.Log, error) {
|
||||
var items []protocol.Shortcut
|
||||
e.st.View(func(d *store.Data) {
|
||||
items = append([]protocol.Shortcut(nil), d.Published...)
|
||||
})
|
||||
body, err := protocol.ShortcutsBody(id, items)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return []Outbox{{To: from, Body: body}}, nil, nil
|
||||
}
|
||||
|
||||
func (e *Engine) replyLogs(from, id string) ([]Outbox, []protocol.Log, error) {
|
||||
var (
|
||||
trustedPeer bool
|
||||
items []protocol.Log
|
||||
)
|
||||
e.st.View(func(d *store.Data) {
|
||||
trustedPeer = trusted(d, from)
|
||||
if trustedPeer {
|
||||
items = append([]protocol.Log(nil), d.Logs...)
|
||||
}
|
||||
})
|
||||
if !trustedPeer {
|
||||
body, err := protocol.LogsBody(id, false, protocol.ErrNotTrusted, nil)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return []Outbox{{To: from, Body: body}}, nil, nil
|
||||
}
|
||||
body, err := protocol.LogsBody(id, true, "", items)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return []Outbox{{To: from, Body: body}}, nil, nil
|
||||
}
|
||||
|
||||
// SendShell 只组一条临时命令,不写入快捷命令。
|
||||
func (e *Engine) SendShell(remote, script string, opt Delivery, lim Limits) (string, []byte, error) {
|
||||
script = strings.TrimSpace(script)
|
||||
if script == "" {
|
||||
return "", nil, errStr("请输入要执行的内容")
|
||||
}
|
||||
if err := checkDelivery(opt, lim, e.now()); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if !idutil.ValidEndpoint(remote) {
|
||||
return "", nil, errStr("端编号不正确")
|
||||
}
|
||||
id := idutil.New()
|
||||
body, err := protocol.ShellBody(id, script)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return id, body, nil
|
||||
}
|
||||
|
||||
// SendText 只组文字,不进入 shell。
|
||||
func (e *Engine) SendText(remote, text string, opt Delivery, lim Limits) (string, []byte, error) {
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
return "", nil, errStr("请输入文字")
|
||||
}
|
||||
if err := checkDelivery(opt, lim, e.now()); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if !idutil.ValidEndpoint(remote) {
|
||||
return "", nil, errStr("端编号不正确")
|
||||
}
|
||||
id := idutil.New()
|
||||
body, err := protocol.TextBody(id, text)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return id, body, nil
|
||||
}
|
||||
|
||||
// SendRemoteShortcut 让远端执行它自己保存的快捷命令。
|
||||
func (e *Engine) SendRemoteShortcut(remote, shortcutID string, opt Delivery, lim Limits) (string, []byte, error) {
|
||||
if !idutil.ValidMessage(shortcutID) {
|
||||
return "", nil, errStr("没有这条命令")
|
||||
}
|
||||
if err := checkDelivery(opt, lim, e.now()); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if !idutil.ValidEndpoint(remote) {
|
||||
return "", nil, errStr("端编号不正确")
|
||||
}
|
||||
id := idutil.New()
|
||||
body, err := protocol.ShortcutBody(id, shortcutID)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return id, body, nil
|
||||
}
|
||||
|
||||
// LocalShell 取出本端快捷命令的 shell,供发送使用。不新增记录。
|
||||
func (e *Engine) LocalShell(id string) (remote, script string, confirm bool, err error) {
|
||||
err = errStr("没有这条命令")
|
||||
e.st.View(func(d *store.Data) {
|
||||
for _, it := range d.Local {
|
||||
if it.ID == id {
|
||||
remote = it.RemoteID
|
||||
script = it.Shell
|
||||
confirm = it.Confirm
|
||||
err = nil
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
return remote, script, confirm, err
|
||||
}
|
||||
|
||||
// SaveLocal 把当前内容存进这一台远端的本端列表。
|
||||
func (e *Engine) SaveLocal(remote, name, script string, confirm bool) (protocol.Shortcut, error) {
|
||||
remote = strings.TrimSpace(remote)
|
||||
name = strings.TrimSpace(name)
|
||||
script = strings.TrimSpace(script)
|
||||
if !idutil.ValidEndpoint(remote) {
|
||||
return protocol.Shortcut{}, errStr("端编号不正确")
|
||||
}
|
||||
if !idutil.ValidName(name) {
|
||||
return protocol.Shortcut{}, errStr("请填写名称")
|
||||
}
|
||||
if script == "" {
|
||||
return protocol.Shortcut{}, errStr("请填写要执行的内容")
|
||||
}
|
||||
item := protocol.Shortcut{ID: idutil.New(), Name: name, Shell: script, Confirm: confirm}
|
||||
err := e.st.Update(func(d *store.Data) error {
|
||||
d.Local = append(d.Local, store.LocalShortcut{Shortcut: item, RemoteID: remote})
|
||||
return nil
|
||||
})
|
||||
return item, err
|
||||
}
|
||||
|
||||
// UpdateLocal 只改本端快捷命令。
|
||||
func (e *Engine) UpdateLocal(id, name, script string, confirm bool) error {
|
||||
name = strings.TrimSpace(name)
|
||||
script = strings.TrimSpace(script)
|
||||
if !idutil.ValidName(name) {
|
||||
return errStr("请填写名称")
|
||||
}
|
||||
if script == "" {
|
||||
return errStr("请填写要执行的内容")
|
||||
}
|
||||
found := false
|
||||
err := e.st.Update(func(d *store.Data) error {
|
||||
for i := range d.Local {
|
||||
if d.Local[i].ID == id {
|
||||
d.Local[i].Name = name
|
||||
d.Local[i].Shell = script
|
||||
d.Local[i].Confirm = confirm
|
||||
found = true
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errStr("没有这条命令")
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
return errStr("没有这条命令")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteLocal 删除本端快捷命令。
|
||||
func (e *Engine) DeleteLocal(id string) error {
|
||||
found := false
|
||||
err := e.st.Update(func(d *store.Data) error {
|
||||
out := d.Local[:0]
|
||||
for _, it := range d.Local {
|
||||
if it.ID == id {
|
||||
found = true
|
||||
continue
|
||||
}
|
||||
out = append(out, it)
|
||||
}
|
||||
d.Local = out
|
||||
if !found {
|
||||
return errStr("没有这条命令")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// ListLocal 返回某一台远端的本端快捷命令。
|
||||
func (e *Engine) ListLocal(remote string) []store.LocalShortcut {
|
||||
var out []store.LocalShortcut
|
||||
e.st.View(func(d *store.Data) {
|
||||
for _, it := range d.Local {
|
||||
if it.RemoteID == remote {
|
||||
out = append(out, it)
|
||||
}
|
||||
}
|
||||
})
|
||||
if out == nil {
|
||||
out = []store.LocalShortcut{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// CopyLocal 把一条本端或远端缓存的快捷命令复制到其他远端的本端列表,生成新编号。
|
||||
func (e *Engine) CopyTo(sourceRemote, shortcutID string, fromRemote bool, targets []string) ([]protocol.Shortcut, error) {
|
||||
if len(targets) == 0 {
|
||||
return nil, errStr("请选择设备")
|
||||
}
|
||||
var src protocol.Shortcut
|
||||
found := false
|
||||
e.st.View(func(d *store.Data) {
|
||||
if fromRemote {
|
||||
cache := d.Remote[sourceRemote]
|
||||
for _, it := range cache.Items {
|
||||
if it.ID == shortcutID {
|
||||
src = it
|
||||
found = true
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, it := range d.Local {
|
||||
if it.ID == shortcutID && it.RemoteID == sourceRemote {
|
||||
src = it.Shortcut
|
||||
found = true
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
if !found {
|
||||
return nil, errStr("没有这条命令")
|
||||
}
|
||||
created := make([]protocol.Shortcut, 0, len(targets))
|
||||
err := e.st.Update(func(d *store.Data) error {
|
||||
seen := map[string]bool{}
|
||||
for _, remote := range targets {
|
||||
remote = strings.TrimSpace(remote)
|
||||
if !idutil.ValidEndpoint(remote) {
|
||||
return errStr("端编号不正确")
|
||||
}
|
||||
if seen[remote] {
|
||||
continue
|
||||
}
|
||||
seen[remote] = true
|
||||
item := protocol.Shortcut{
|
||||
ID: idutil.New(),
|
||||
Name: src.Name,
|
||||
Shell: src.Shell,
|
||||
Confirm: src.Confirm,
|
||||
}
|
||||
d.Local = append(d.Local, store.LocalShortcut{Shortcut: item, RemoteID: remote})
|
||||
created = append(created, item)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return created, err
|
||||
}
|
||||
|
||||
// RemoteCache 返回上次同步的远端快捷命令。
|
||||
func (e *Engine) RemoteCache(remote string) store.RemoteCache {
|
||||
var c store.RemoteCache
|
||||
e.st.View(func(d *store.Data) {
|
||||
c = d.Remote[remote]
|
||||
c.Items = append([]protocol.Shortcut(nil), c.Items...)
|
||||
})
|
||||
if c.Items == nil {
|
||||
c.Items = []protocol.Shortcut{}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// BeginShortcutSync 标记正在同步。
|
||||
func (e *Engine) BeginShortcutSync(remote, reqID string) error {
|
||||
return e.st.Update(func(d *store.Data) error {
|
||||
prev := d.Remote[remote]
|
||||
prev.Syncing = true
|
||||
prev.ReqID = reqID
|
||||
d.Remote[remote] = prev
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// BeginLogSync 标记正在拉取日志。
|
||||
func (e *Engine) BeginLogSync(remote, reqID string) error {
|
||||
return e.st.Update(func(d *store.Data) error {
|
||||
prev := d.RemoteLogs[remote]
|
||||
prev.Syncing = true
|
||||
prev.ReqID = reqID
|
||||
prev.Error = ""
|
||||
d.RemoteLogs[remote] = prev
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// FinishShortcutSync 在超时或失败时结束同步。已经收到列表则不动。
|
||||
func (e *Engine) FinishShortcutSync(remote, reqID string) error {
|
||||
return e.st.Update(func(d *store.Data) error {
|
||||
prev := d.Remote[remote]
|
||||
if prev.ReqID == reqID {
|
||||
prev.Syncing = false
|
||||
prev.ReqID = ""
|
||||
d.Remote[remote] = prev
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// FinishLogSync 在超时或失败时结束日志拉取。
|
||||
func (e *Engine) FinishLogSync(remote, reqID, errText string) error {
|
||||
return e.st.Update(func(d *store.Data) error {
|
||||
prev := d.RemoteLogs[remote]
|
||||
if prev.ReqID == reqID {
|
||||
prev.Syncing = false
|
||||
prev.ReqID = ""
|
||||
if errText != "" && prev.Error == "" {
|
||||
prev.Error = errText
|
||||
}
|
||||
d.RemoteLogs[remote] = prev
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// RemoteLogs 返回向对方要来的日志。
|
||||
func (e *Engine) RemoteLogs(remote string) store.LogCache {
|
||||
var c store.LogCache
|
||||
e.st.View(func(d *store.Data) {
|
||||
c = d.RemoteLogs[remote]
|
||||
c.Items = append([]protocol.Log(nil), c.Items...)
|
||||
})
|
||||
if c.Items == nil {
|
||||
c.Items = []protocol.Log{}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// LocalLogs 返回本机执行记录。
|
||||
func (e *Engine) LocalLogs() []protocol.Log {
|
||||
var out []protocol.Log
|
||||
e.st.View(func(d *store.Data) {
|
||||
out = append([]protocol.Log(nil), d.Logs...)
|
||||
})
|
||||
if out == nil {
|
||||
out = []protocol.Log{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (e *Engine) TrustList() []string {
|
||||
var out []string
|
||||
e.st.View(func(d *store.Data) {
|
||||
out = append([]string(nil), d.Trust...)
|
||||
})
|
||||
if out == nil {
|
||||
out = []string{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (e *Engine) TrustAdd(id string) error {
|
||||
id = strings.TrimSpace(id)
|
||||
if !idutil.ValidEndpoint(id) {
|
||||
return errStr("端编号不正确")
|
||||
}
|
||||
return e.st.Update(func(d *store.Data) error {
|
||||
if trusted(d, id) {
|
||||
return nil
|
||||
}
|
||||
d.Trust = append(d.Trust, id)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (e *Engine) TrustRemove(id string) error {
|
||||
return e.st.Update(func(d *store.Data) error {
|
||||
out := d.Trust[:0]
|
||||
for _, it := range d.Trust {
|
||||
if it == id {
|
||||
continue
|
||||
}
|
||||
out = append(out, it)
|
||||
}
|
||||
d.Trust = out
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (e *Engine) Published() []protocol.Shortcut {
|
||||
var out []protocol.Shortcut
|
||||
e.st.View(func(d *store.Data) {
|
||||
out = append([]protocol.Shortcut(nil), d.Published...)
|
||||
})
|
||||
if out == nil {
|
||||
out = []protocol.Shortcut{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// SavePublished 新增本机发布的快捷命令,返回是否需要推送。
|
||||
func (e *Engine) SavePublished(name, script string, confirm bool) (protocol.Shortcut, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
script = strings.TrimSpace(script)
|
||||
if !idutil.ValidName(name) {
|
||||
return protocol.Shortcut{}, errStr("请填写名称")
|
||||
}
|
||||
if script == "" {
|
||||
return protocol.Shortcut{}, errStr("请填写要执行的内容")
|
||||
}
|
||||
item := protocol.Shortcut{ID: idutil.New(), Name: name, Shell: script, Confirm: confirm}
|
||||
err := e.st.Update(func(d *store.Data) error {
|
||||
d.Published = append(d.Published, item)
|
||||
return nil
|
||||
})
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (e *Engine) UpdatePublished(id, name, script string, confirm bool) error {
|
||||
name = strings.TrimSpace(name)
|
||||
script = strings.TrimSpace(script)
|
||||
if !idutil.ValidName(name) {
|
||||
return errStr("请填写名称")
|
||||
}
|
||||
if script == "" {
|
||||
return errStr("请填写要执行的内容")
|
||||
}
|
||||
return e.st.Update(func(d *store.Data) error {
|
||||
for i := range d.Published {
|
||||
if d.Published[i].ID == id {
|
||||
d.Published[i].Name = name
|
||||
d.Published[i].Shell = script
|
||||
d.Published[i].Confirm = confirm
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errStr("没有这条命令")
|
||||
})
|
||||
}
|
||||
|
||||
func (e *Engine) DeletePublished(id string) error {
|
||||
return e.st.Update(func(d *store.Data) error {
|
||||
out := d.Published[:0]
|
||||
found := false
|
||||
for _, it := range d.Published {
|
||||
if it.ID == id {
|
||||
found = true
|
||||
continue
|
||||
}
|
||||
out = append(out, it)
|
||||
}
|
||||
if !found {
|
||||
return errStr("没有这条命令")
|
||||
}
|
||||
d.Published = out
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (e *Engine) Inbox() []store.TextMsg {
|
||||
var out []store.TextMsg
|
||||
e.st.View(func(d *store.Data) {
|
||||
out = append([]store.TextMsg(nil), d.Inbox...)
|
||||
})
|
||||
if out == nil {
|
||||
out = []store.TextMsg{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (e *Engine) MarkInboxRead() error {
|
||||
return e.st.Update(func(d *store.Data) error {
|
||||
for i := range d.Inbox {
|
||||
d.Inbox[i].Read = true
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (e *Engine) Results() []store.CmdResult {
|
||||
var out []store.CmdResult
|
||||
e.st.View(func(d *store.Data) {
|
||||
out = append([]store.CmdResult(nil), d.Results...)
|
||||
})
|
||||
if out == nil {
|
||||
out = []store.CmdResult{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func checkDelivery(opt Delivery, lim Limits, now time.Time) error {
|
||||
if opt.Keep {
|
||||
if opt.TTL == nil || *opt.TTL <= 0 {
|
||||
return errStr("请填写有效期")
|
||||
}
|
||||
if *opt.TTL > lim.ttl() {
|
||||
return errStr("有效期超出上限")
|
||||
}
|
||||
}
|
||||
if opt.SendAt != nil {
|
||||
if opt.SendAt.After(now.Add(time.Duration(lim.schedule()) * time.Second)) {
|
||||
return errStr("定时超出上限")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func trusted(d *store.Data, id string) bool {
|
||||
for _, it := range d.Trust {
|
||||
if it == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func findExecuted(d *store.Data, id string) (store.Executed, bool) {
|
||||
for _, it := range d.Executed {
|
||||
if it.ID == id {
|
||||
return it, true
|
||||
}
|
||||
}
|
||||
return store.Executed{}, false
|
||||
}
|
||||
|
||||
func findPublished(d *store.Data, id string) (protocol.Shortcut, bool) {
|
||||
for _, it := range d.Published {
|
||||
if it.ID == id {
|
||||
return it, true
|
||||
}
|
||||
}
|
||||
return protocol.Shortcut{}, false
|
||||
}
|
||||
|
||||
// Error 是可以显示给用户的短句。
|
||||
type Error string
|
||||
|
||||
func (e Error) Error() string { return string(e) }
|
||||
|
||||
func errStr(s string) error { return Error(s) }
|
||||
@@ -0,0 +1,253 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/protocol"
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/store"
|
||||
)
|
||||
|
||||
type fakeRun struct {
|
||||
calls []string
|
||||
}
|
||||
|
||||
func (f *fakeRun) Run(_ context.Context, script string) (string, error) {
|
||||
f.calls = append(f.calls, script)
|
||||
return "done", nil
|
||||
}
|
||||
|
||||
func newTest(t *testing.T) (*Engine, *fakeRun) {
|
||||
t.Helper()
|
||||
st, err := store.New(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fake := &fakeRun{}
|
||||
return New(st, fake), fake
|
||||
}
|
||||
|
||||
func shellRaw(id, script string) string {
|
||||
b, _ := protocol.ShellBody(id, script)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func resultOf(t *testing.T, body []byte) protocol.Message {
|
||||
t.Helper()
|
||||
m, err := protocol.Parse(string(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestUntrustedDoesNotRun(t *testing.T) {
|
||||
e, fake := newTest(t)
|
||||
outs, logs, err := e.Accept("stranger", shellRaw("cmd-1", "echo hi"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fake.calls) != 0 {
|
||||
t.Fatalf("executed: %v", fake.calls)
|
||||
}
|
||||
if len(logs) != 0 {
|
||||
t.Fatal("logged untrusted command")
|
||||
}
|
||||
if len(outs) != 1 {
|
||||
t.Fatalf("outs %d", len(outs))
|
||||
}
|
||||
got := resultOf(t, outs[0].Body)
|
||||
if got.OK == nil || *got.OK || got.Error != protocol.ErrNotTrusted || got.Duplicate {
|
||||
t.Fatalf("result %+v", got)
|
||||
}
|
||||
|
||||
outs, _, err = e.Accept("stranger", shellRaw("cmd-1", "echo hi"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fake.calls) != 0 {
|
||||
t.Fatal("second delivery executed")
|
||||
}
|
||||
got = resultOf(t, outs[0].Body)
|
||||
if got.Error != protocol.ErrNotTrusted || !got.Duplicate {
|
||||
t.Fatalf("duplicate result %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameIDRunsOnce(t *testing.T) {
|
||||
e, fake := newTest(t)
|
||||
if err := e.TrustAdd("friend"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outs, _, err := e.Accept("friend", shellRaw("cmd-9", "echo once"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fake.calls) != 1 || fake.calls[0] != "echo once" {
|
||||
t.Fatalf("calls %v", fake.calls)
|
||||
}
|
||||
first := resultOf(t, outs[0].Body)
|
||||
if first.OK == nil || !*first.OK || first.Duplicate {
|
||||
t.Fatalf("first %+v", first)
|
||||
}
|
||||
|
||||
outs, _, err = e.Accept("friend", shellRaw("cmd-9", "echo once"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fake.calls) != 1 {
|
||||
t.Fatalf("ran again: %v", fake.calls)
|
||||
}
|
||||
second := resultOf(t, outs[0].Body)
|
||||
if second.OK == nil || !*second.OK || !second.Duplicate {
|
||||
t.Fatalf("second %+v", second)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDuplicateExpiresAfter24h(t *testing.T) {
|
||||
e, fake := newTest(t)
|
||||
start := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
|
||||
e.now = func() time.Time { return start }
|
||||
if err := e.TrustAdd("friend"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := e.Accept("friend", shellRaw("cmd-9", "echo once")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e.now = func() time.Time { return start.Add(25 * time.Hour) }
|
||||
if _, _, err := e.Accept("friend", shellRaw("cmd-9", "echo once")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fake.calls) != 2 {
|
||||
t.Fatalf("calls %d", len(fake.calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTempShellDoesNotCreateShortcut(t *testing.T) {
|
||||
e, _ := newTest(t)
|
||||
if _, _, err := e.SendShell("peer-a", "echo hi", Delivery{}, Limits{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n := len(e.ListLocal("peer-a")); n != 0 {
|
||||
t.Fatalf("temp shell created %d shortcuts", n)
|
||||
}
|
||||
if _, err := e.SaveLocal("peer-a", "打招呼", "echo hi", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := e.ListLocal("peer-a")
|
||||
if len(got) != 1 || got[0].Name != "打招呼" || got[0].Shell != "echo hi" {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
if n := len(e.ListLocal("peer-b")); n != 0 {
|
||||
t.Fatalf("leaked to other remote: %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShortcutsStayWithRemote(t *testing.T) {
|
||||
e, _ := newTest(t)
|
||||
if _, err := e.SaveLocal("peer-a", "关机", "shutdown -s -t 1", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := e.SaveLocal("peer-b", "查看", "dir", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := e.ListLocal("peer-a")
|
||||
b := e.ListLocal("peer-b")
|
||||
if len(a) != 1 || a[0].Name != "关机" || len(b) != 1 || b[0].Name != "查看" {
|
||||
t.Fatalf("a=%+v b=%+v", a, b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyCreatesNewIDs(t *testing.T) {
|
||||
e, _ := newTest(t)
|
||||
src, err := e.SaveLocal("peer-a", "关机", "shutdown -s -t 1", true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
created, err := e.CopyTo("peer-a", src.ID, false, []string{"peer-b", "peer-c"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(created) != 2 {
|
||||
t.Fatalf("created %d", len(created))
|
||||
}
|
||||
seen := map[string]bool{src.ID: true}
|
||||
for _, it := range created {
|
||||
if seen[it.ID] {
|
||||
t.Fatalf("id reused: %s", it.ID)
|
||||
}
|
||||
seen[it.ID] = true
|
||||
if it.Name != "关机" || it.Shell != "shutdown -s -t 1" || !it.Confirm {
|
||||
t.Fatalf("copy changed fields: %+v", it)
|
||||
}
|
||||
}
|
||||
if len(e.ListLocal("peer-a")) != 1 {
|
||||
t.Fatal("source changed")
|
||||
}
|
||||
if len(e.ListLocal("peer-b")) != 1 || len(e.ListLocal("peer-c")) != 1 {
|
||||
t.Fatal("missing copy")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTextDoesNotRunShell(t *testing.T) {
|
||||
e, fake := newTest(t)
|
||||
if err := e.TrustAdd("friend"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ := protocol.TextBody("msg-1", "你好")
|
||||
outs, logs, err := e.Accept("friend", string(raw))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fake.calls) != 0 || len(outs) != 0 || len(logs) != 0 {
|
||||
t.Fatalf("text entered shell calls=%v outs=%d logs=%d", fake.calls, len(outs), len(logs))
|
||||
}
|
||||
inbox := e.Inbox()
|
||||
if len(inbox) != 1 || inbox[0].Text != "你好" || inbox[0].From != "friend" {
|
||||
t.Fatalf("inbox %+v", inbox)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishedShortcutUsesStoredShell(t *testing.T) {
|
||||
e, fake := newTest(t)
|
||||
if err := e.TrustAdd("friend"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
item, err := e.SavePublished("列目录", "dir", false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := protocol.ShortcutBody("cmd-3", item.ID)
|
||||
if _, _, err := e.Accept("friend", string(body)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fake.calls) != 1 || fake.calls[0] != "dir" {
|
||||
t.Fatalf("calls %v", fake.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingShortcutDoesNotRun(t *testing.T) {
|
||||
e, fake := newTest(t)
|
||||
if err := e.TrustAdd("friend"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := protocol.ShortcutBody("cmd-4", "missing-id")
|
||||
outs, _, err := e.Accept("friend", string(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fake.calls) != 0 {
|
||||
t.Fatal("ran missing shortcut")
|
||||
}
|
||||
got := resultOf(t, outs[0].Body)
|
||||
if got.OK == nil || *got.OK || got.Error == "" {
|
||||
b, _ := json.Marshal(got)
|
||||
t.Fatalf("result %s", b)
|
||||
}
|
||||
if strings.Contains(got.Error, "not_trusted") {
|
||||
t.Fatal("trusted peer reported not trusted")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user