Files
desktop/agent/internal/engine/engine.go
T

825 lines
20 KiB
Go

package engine
import (
"context"
"encoding/json"
"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, protocol.TypeShortcutsGet:
if msg.Type == protocol.TypeShortcutsGet || !jsonHasItems(raw) {
return e.replyShortcuts(from, msg.ID)
}
return nil, nil, e.acceptShortcuts(from, msg)
case protocol.TypeLogs, protocol.TypeLogsGet:
if msg.Type == protocol.TypeLogsGet || !jsonHasItems(raw) {
return e.replyLogs(from, msg.ID)
}
return nil, nil, e.acceptLogs(from, msg)
case protocol.TypeResult:
return nil, nil, e.acceptResult(from, msg)
default:
return nil, nil, nil
}
}
func jsonHasItems(raw string) bool {
var probe struct {
Items json.RawMessage `json:"items"`
}
if json.Unmarshal([]byte(raw), &probe) != nil || len(probe.Items) == 0 {
return false
}
return string(probe.Items) != "null"
}
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) }