package app import ( "context" "crypto/rand" "encoding/hex" "encoding/json" "errors" "net" "net/http" "os" "sync" "time" "git.asio.asia/TapRemly/desktop/agent/internal/account" "git.asio.asia/TapRemly/desktop/agent/internal/engine" "git.asio.asia/TapRemly/desktop/agent/internal/idutil" "git.asio.asia/TapRemly/desktop/agent/internal/lockfile" "git.asio.asia/TapRemly/desktop/agent/internal/protocol" "git.asio.asia/TapRemly/desktop/agent/internal/shell" "git.asio.asia/TapRemly/desktop/agent/internal/store" nixmsg "git.asio.asia/nixevol/NixMsg/sdk/go" ) // App 是这台电脑唯一的连接和本机接口。 type App struct { dir string st *store.Store eng *engine.Engine mu sync.Mutex token string client *nixmsg.Client stop context.CancelFunc connState string connText string presence map[string]bool presenceOK bool deviceIDs []string serverLogs map[string][]protocol.Log } func New(dir string) (*App, error) { st, err := store.New(dir) if err != nil { return nil, err } return &App{ dir: dir, st: st, eng: engine.New(st, shell.System{}), connText: "未连接", presence: map[string]bool{}, serverLogs: map[string][]protocol.Log{}, }, nil } // Run 监听本机随机端口,并把地址写入锁文件。 func (a *App) Run(ctx context.Context, lock *lockfile.File) error { ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { return err } token := newToken() a.mu.Lock() a.token = token a.mu.Unlock() if err := lock.Publish(ln.Addr().String(), token, os.Getpid()); err != nil { _ = ln.Close() return err } ctx, cancel := context.WithCancel(ctx) a.mu.Lock() a.stop = cancel a.mu.Unlock() srv := &http.Server{ Handler: cors(a.routes()), ReadHeaderTimeout: 5 * time.Second, } go func() { <-ctx.Done() sh, done := context.WithTimeout(context.Background(), 3*time.Second) defer done() _ = srv.Shutdown(sh) a.closeClient() }() go a.autoConnect() err = srv.Serve(ln) if errors.Is(err, http.ErrServerClosed) { return nil } return err } func (a *App) requestStop() { a.mu.Lock() stop := a.stop a.mu.Unlock() if stop != nil { stop() } } func (a *App) autoConnect() { var url, id, session, pending string a.st.View(func(d *store.Data) { url, id, session, pending = d.NixURL, d.EndpointID, d.SessionToken, d.PendingSecret }) if id == "" || url == "" { return } if session != "" { _ = a.connect(url, id, "", session) return } if pending != "" { _ = a.connect(url, id, pending, "") } } func (a *App) connect(rawURL, id, password, session string) error { if !idutil.ValidEndpoint(id) { return engine.Error("端编号不正确") } _ = a.st.Update(func(d *store.Data) error { d.NixURL = rawURL d.EndpointID = id if password != "" { d.PendingSecret = password } return nil }) c := nixmsg.New() c.OnSession(func(tok string) { if tok == "" { return } _ = a.st.Update(func(d *store.Data) error { d.SessionToken = tok d.PendingSecret = "" d.EndpointID = id d.NixURL = rawURL return nil }) }) c.OnMessage(func(msg nixmsg.Message) error { return a.onMessage(c, msg) }) c.OnPresence(func(ev nixmsg.PresenceEvent) { a.onPresence(c, ev) }) c.OnConnection(func(ev nixmsg.ConnectionEvent) { a.onConnection(c, ev) }) a.mu.Lock() old := a.client a.client = c a.connState = string(nixmsg.StateConnecting) a.connText = "正在连接" a.mu.Unlock() if old != nil { _ = old.Close() } cred := nixmsg.Credential{Password: password} if session != "" { cred = nixmsg.Credential{SessionToken: session} } ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second) defer cancel() err := c.Connect(ctx, rawURL, id, cred, nixmsg.Options{ClientLabel: "tapremly/0.1"}) if err != nil { a.noteAuth(err, session != "") a.mu.Lock() if a.client == c { a.client = nil a.connState = string(nixmsg.StateOffline) a.connText = publicErr(nixErr(err)) } a.mu.Unlock() _ = c.Close() return nixErr(err) } go a.rewatch() return nil } func (a *App) noteAuth(err error, usedSession bool) { var api *nixmsg.APIError if !errors.As(err, &api) { return } switch api.Code { case nixmsg.CodeBadCredentials, nixmsg.CodeAuthFailed, nixmsg.CodePasswordReset, nixmsg.CodeSessionInvalid: _ = a.st.Update(func(d *store.Data) error { d.PendingSecret = "" if usedSession || api.Code == nixmsg.CodeSessionInvalid || api.Code == nixmsg.CodePasswordReset { d.SessionToken = "" } return nil }) } } func (a *App) onConnection(c *nixmsg.Client, ev nixmsg.ConnectionEvent) { a.mu.Lock() if a.client != c { a.mu.Unlock() return } a.connState = string(ev.State) a.connText = connText(ev.State) a.mu.Unlock() if ev.State == nixmsg.StateAuthFailed { _ = a.st.Update(func(d *store.Data) error { d.SessionToken = "" d.PendingSecret = "" return nil }) } if ev.State == nixmsg.StateOnline { go a.rewatch() } } func (a *App) onPresence(c *nixmsg.Client, ev nixmsg.PresenceEvent) { a.mu.Lock() defer a.mu.Unlock() if a.client != c { return } if a.presence == nil { a.presence = map[string]bool{} } a.presence[ev.ID] = ev.Online a.presenceOK = true } func (a *App) onMessage(c *nixmsg.Client, msg nixmsg.Message) error { a.mu.Lock() cur := a.client a.mu.Unlock() if cur != c { return nil } outs, logs, err := a.eng.Accept(msg.From, msg.Body.Data) if err != nil { return err } for _, o := range outs { _, _ = a.sendRaw(o.To, o.Body, engine.Delivery{}, false) } if len(logs) > 0 { go a.uploadLogs(logs) } return nil } func (a *App) closeClient() { a.mu.Lock() c := a.client a.client = nil a.connState = string(nixmsg.StateOffline) a.connText = "未连接" a.presenceOK = false a.mu.Unlock() if c != nil { _ = c.Close() } } func (a *App) sendRaw(to string, body []byte, opt engine.Delivery, pinID bool) (nixmsg.SendResult, error) { a.mu.Lock() c := a.client a.mu.Unlock() if c == nil { return nixmsg.SendResult{}, engine.Error("还没有连上") } so := nixmsg.SendOptions{ContentType: "application/json; charset=utf-8"} if opt.Keep { so.Keep = true so.TTL = opt.TTL } so.SendAt = opt.SendAt if pinID { var probe struct { ID string `json:"id"` } if json.Unmarshal(body, &probe) == nil && idutil.ValidMessage(probe.ID) { so.ID = probe.ID } } ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second) defer cancel() res, err := c.Send(ctx, nixmsg.Target{Kind: "endpoint", ID: to}, nixmsg.Body{ Enc: "utf8", ContentType: "application/json; charset=utf-8", Data: string(body), }, so) if err != nil { return res, nixErr(err) } return res, nil } func (a *App) uploadLogs(items []protocol.Log) { var base, token, ep string a.st.View(func(d *store.Data) { base, token, ep = d.ServerURL, d.DeviceToken, d.EndpointID }) ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() _ = account.PutLogs(ctx, base, ep, token, items) } func (a *App) rewatch() { a.mu.Lock() ids := append([]string(nil), a.deviceIDs...) c := a.client a.mu.Unlock() if c == nil || len(ids) == 0 { return } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() _ = c.WatchPresence(ctx, ids, false) items, err := c.Presence(ctx, ids) if err != nil { return } a.mu.Lock() defer a.mu.Unlock() if a.client != c { return } if a.presence == nil { a.presence = map[string]bool{} } for _, it := range items { a.presence[it.ID] = it.Online } a.presenceOK = true } func (a *App) rememberDevices(list []account.Device) { ids := make([]string, 0, len(list)) seen := map[string]bool{} for _, d := range list { if d.EndpointID == "" || seen[d.EndpointID] { continue } seen[d.EndpointID] = true ids = append(ids, d.EndpointID) } a.mu.Lock() a.deviceIDs = ids a.mu.Unlock() go a.rewatch() } func (a *App) limits() engine.Limits { a.mu.Lock() c := a.client a.mu.Unlock() if c == nil { return engine.Limits{} } lim := c.Limits() return engine.Limits{MaxTTL: lim.MaxTTLSeconds, MaxSchedule: lim.MaxScheduleSeconds} } func (a *App) session() (*account.Session, error) { var base string var cookies []store.Cookie a.st.View(func(d *store.Data) { base = d.ServerURL cookies = append([]store.Cookie(nil), d.Cookies...) }) return account.NewSession(base, cookies) } func (a *App) pushPublished() { body, err := protocol.ShortcutsBody("", a.eng.Published()) if err != nil { return } a.mu.Lock() online := a.connState == string(nixmsg.StateOnline) && a.presenceOK presence := a.presence a.mu.Unlock() if !online { return } for _, id := range a.eng.TrustList() { if presence[id] { _, _ = a.sendRaw(id, body, engine.Delivery{}, false) } } } func (a *App) refreshShortcuts(remote string) error { if !idutil.ValidEndpoint(remote) { return engine.Error("端编号不正确") } id := idutil.New() if err := a.eng.BeginShortcutSync(remote, id); err != nil { return err } body, err := protocol.ShortcutsGetBody(id) if err != nil { return err } if _, err := a.sendRaw(remote, body, engine.Delivery{}, false); err != nil { _ = a.eng.FinishShortcutSync(remote, id) return err } go func() { time.Sleep(8 * time.Second) _ = a.eng.FinishShortcutSync(remote, id) }() return nil } func (a *App) refreshLogs(remote string) error { if !idutil.ValidEndpoint(remote) { return engine.Error("端编号不正确") } if sess, err := a.session(); err == nil { ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) items, gerr := sess.GetLogs(ctx, remote) cancel() if gerr == nil { a.mu.Lock() a.serverLogs[remote] = items a.mu.Unlock() } } a.mu.Lock() online := a.connState == string(nixmsg.StateOnline) && a.presenceOK && a.presence[remote] a.mu.Unlock() if !online { return nil } id := idutil.New() if err := a.eng.BeginLogSync(remote, id); err != nil { return err } body, err := protocol.LogsGetBody(id) if err != nil { return err } if _, err := a.sendRaw(remote, body, engine.Delivery{}, false); err != nil { _ = a.eng.FinishLogSync(remote, id, "") return err } go func() { time.Sleep(8 * time.Second) _ = a.eng.FinishLogSync(remote, id, "") }() return nil } func connText(st nixmsg.ConnectionState) string { switch st { case nixmsg.StateOnline: return "在线" case nixmsg.StateConnecting, nixmsg.StateReconnecting: return "正在连接" case nixmsg.StateKicked: return "已在其他地方登录" case nixmsg.StateAuthFailed: return "登录失败" default: return "未连接" } } func nixErr(err error) error { if err == nil { return nil } var api *nixmsg.APIError if errors.As(err, &api) { switch api.Code { case nixmsg.CodeBadCredentials, nixmsg.CodeAuthFailed, nixmsg.CodePasswordReset: return engine.Error("端编号或密码不正确") case nixmsg.CodeTakenOver, nixmsg.CodeKicked: return engine.Error("这个端已在其他地方登录") case nixmsg.CodeSessionInvalid: return engine.Error("登录已失效,请重新登录") default: return engine.Error("连不上") } } if errors.Is(err, context.DeadlineExceeded) { return engine.Error("连不上") } return engine.Error("连不上") } func publicErr(err error) string { var ee engine.Error if errors.As(err, &ee) { return ee.Error() } var ae account.Error if errors.As(err, &ae) { return ae.Error() } if err == nil { return "" } return "没有成功" } func newToken() string { var b [32]byte _, _ = rand.Read(b[:]) return hex.EncodeToString(b[:]) }