1
0

main.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. // ============================================================================
  2. // cmd/toolbox-service/main.go — 独立服务模式程序(无 GUI 依赖)
  3. //
  4. // 与主程序完全分离的最小实现:不链接 Wails、Gin、beeep/Toast、systray 等
  5. // 任何 GUI 组件,仅用标准库 + golang.org/x/sys/windows/svc。
  6. // 供 Windows SCM 以 `sc create TengTuToolboxService binPath= "<exe> --service"`
  7. // 启动,运行电源类 HTTP API + 指令信箱 + 界面代理,常驻内存与分发体积最小。
  8. //
  9. // 构建:go build -trimpath -ldflags "-s -w" -o bin/TengTuToolbox-service.exe ./cmd/toolbox-service
  10. // ============================================================================
  11. package main
  12. import (
  13. "encoding/json"
  14. "fmt"
  15. "io"
  16. "log"
  17. "net"
  18. "net/http"
  19. "os"
  20. "os/exec"
  21. "path/filepath"
  22. "runtime"
  23. "runtime/debug"
  24. "strconv"
  25. "strings"
  26. "sync"
  27. "time"
  28. "unicode/utf8"
  29. "golang.org/x/sys/windows/svc"
  30. )
  31. const (
  32. serviceName = "TengTuToolboxService" // Windows 服务名(与 GUI 侧一致)
  33. appVersion = "0.1.11" // 应用版本(与主程序一致)
  34. defaultAddr = "0.0.0.0:9090" // 默认监听地址
  35. legacyAddr = "127.0.0.1:17891" // 旧版默认服务地址(读取时自动迁移)
  36. pcShutdownDelay = 30 * time.Second // 电源命令默认延迟
  37. xzCmdMaxLen = 200 // 指令最大长度(字符数)
  38. // 内存/连接约束:常驻服务保持低占用,防止堆无谓膨胀与连接池积累
  39. heapSoftLimitMB = 16 // GOMEMLIMIT 软上限,堆接近此值即提前 GC,避免膨胀到 40MB+
  40. goGCPercent = 50 // 更积极的 GC(默认 100),以 CPU 换常驻内存
  41. proxyTimeout = 20 * time.Second
  42. )
  43. func main() {
  44. // 常驻服务优先低内存:设软上限 + 更激进 GC(在 runtime 启动后尽早设置)
  45. debug.SetMemoryLimit(int64(heapSoftLimitMB) << 20)
  46. debug.SetGCPercent(goGCPercent)
  47. isService, err := svc.IsWindowsService()
  48. if err != nil {
  49. fmt.Println("检测服务状态失败:", err)
  50. os.Exit(1)
  51. }
  52. if !isService {
  53. fmt.Printf("这不是由 Windows 服务管理器启动的进程,请用 sc start %s 启动\n", serviceName)
  54. os.Exit(1)
  55. }
  56. if err := svc.Run(serviceName, &toolboxService{}); err != nil {
  57. os.Exit(1)
  58. }
  59. }
  60. // toolboxService SCM 服务实现:启动电源 API,收到 Stop/Shutdown 平滑退出
  61. type toolboxService struct{}
  62. func (s *toolboxService) Execute(_ []string, requests <-chan svc.ChangeRequest, status chan<- svc.Status) (bool, uint32) {
  63. status <- svc.Status{State: svc.StartPending}
  64. setupServiceLog()
  65. srv := startServicePowerAPI(serviceListenAddr())
  66. status <- svc.Status{State: svc.Running, Accepts: svc.AcceptStop | svc.AcceptShutdown}
  67. for req := range requests {
  68. switch req.Cmd {
  69. case svc.Interrogate:
  70. status <- req.CurrentStatus
  71. case svc.Stop, svc.Shutdown:
  72. status <- svc.Status{State: svc.StopPending}
  73. stopServicePowerAPI(srv)
  74. return false, 0
  75. }
  76. }
  77. stopServicePowerAPI(srv)
  78. return false, 0
  79. }
  80. // setupServiceLog 服务没有控制台,日志写入 %ProgramData%\TengTuToolbox\service.log
  81. func setupServiceLog() {
  82. dir := filepath.Join(os.Getenv("ProgramData"), "TengTuToolbox")
  83. if dir == "" || os.MkdirAll(dir, 0o755) != nil {
  84. return
  85. }
  86. f, err := os.OpenFile(filepath.Join(dir, "service.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
  87. if err != nil {
  88. return
  89. }
  90. log.SetOutput(f)
  91. log.Printf("service starting: addr=%s version=%s", serviceListenAddr(), appVersion)
  92. }
  93. // serviceListenAddr 监听地址:读 %APPDATA%\TengTuToolbox\settings.json 的 serviceAddr,
  94. // 留空或读取失败用默认值;旧版地址自动迁移(与主程序 normalize 行为一致)。
  95. func serviceListenAddr() string {
  96. path := filepath.Join(os.Getenv("APPDATA"), "TengTuToolbox", "settings.json")
  97. if data, err := os.ReadFile(path); err == nil {
  98. var s struct {
  99. ServiceAddr string `json:"serviceAddr"`
  100. }
  101. if json.Unmarshal(data, &s) == nil {
  102. addr := strings.TrimSpace(s.ServiceAddr)
  103. if addr == legacyAddr {
  104. addr = defaultAddr
  105. }
  106. if addr != "" {
  107. return addr
  108. }
  109. }
  110. }
  111. return defaultAddr
  112. }
  113. // ----------------------------------------------------------------------------
  114. // HTTP API:仅标准库 net/http,不引入 Gin
  115. // ----------------------------------------------------------------------------
  116. // startServicePowerAPI 启动仅含电源接口的 HTTP 服务,返回句柄用于停止
  117. func startServicePowerAPI(addr string) *http.Server {
  118. mux := http.NewServeMux()
  119. mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
  120. writeJSON(w, http.StatusOK, map[string]any{"service": true, "version": appVersion, "ui": uiPeerOnline()})
  121. })
  122. mux.HandleFunc("/api/ui/register", handleUIRegister) // 界面登记自己的 API 地址
  123. mux.HandleFunc("/api/ui/status", handleUIStatus) // 查询界面是否在线
  124. // 电源接口:与界面内置 API 路径保持一致(/api/pc/* 界面版路径 与 /api/power/* 服务版路径)
  125. for _, prefix := range []string{"/api/power", "/api/pc"} {
  126. mux.HandleFunc(prefix+"/poweroff", handlePoweroff) // 30 秒后关机
  127. mux.HandleFunc(prefix+"/restart", handleRestart) // 30 秒后重启
  128. mux.HandleFunc(prefix+"/sleep", handleSleep) // 30 秒后休眠
  129. mux.HandleFunc(prefix+"/cancel", handleCancel) // 取消待执行命令
  130. mux.HandleFunc(prefix+"/status", handlePCStatus) // 查询命令状态
  131. }
  132. // 指令信箱:POST 下发,GET 读取,GET /cmd/<命令> 路径下发
  133. mux.HandleFunc("/api/xz/cmd", handleXZCmd) // POST=下发 / GET=取走
  134. mux.HandleFunc("/api/xz/cmd/", handleXZCmdPath) // 路径参数下发(URL 编码)
  135. mux.HandleFunc("/", proxyToUI) // 其余接口交给界面 API 处理
  136. // 先同步绑定:端口被占用时自动切换到备用端口(+1)
  137. ln, actualAddr, err := listenFirst(addr, nextPortAddr(addr))
  138. srv := &http.Server{
  139. Addr: actualAddr,
  140. Handler: mux,
  141. ReadHeaderTimeout: 10 * time.Second, // 防 slowloris,避免连接长期占住
  142. ReadTimeout: 30 * time.Second, // 防慢速 body 拖住连接
  143. WriteTimeout: 30 * time.Second, // 响应超时上限
  144. IdleTimeout: 60 * time.Second, // keep-alive 空闲连接回收,降低常驻连接数
  145. MaxHeaderBytes: 1 << 20, // 1MB 头上限,防超大头占用内存
  146. }
  147. if err != nil {
  148. log.Printf("service api listen failed on %s (fallback %s): %v", addr, nextPortAddr(addr), err)
  149. return srv // 未监听,但返回句柄供停止安全调用
  150. }
  151. if actualAddr != addr {
  152. log.Printf("service api fallback: %s occupied, using %s", addr, actualAddr)
  153. }
  154. log.Printf("service api listening on %s", actualAddr)
  155. go func() {
  156. if err := srv.Serve(ln); err != nil && err != http.ErrServerClosed {
  157. log.Printf("service api listening on %s failed: %v", actualAddr, err)
  158. }
  159. }()
  160. return srv
  161. }
  162. // stopServicePowerAPI 平滑关闭
  163. func stopServicePowerAPI(srv *http.Server) {
  164. if srv == nil {
  165. return
  166. }
  167. done := make(chan struct{})
  168. go func() { srv.Close(); close(done) }()
  169. select {
  170. case <-done:
  171. case <-time.After(5 * time.Second):
  172. }
  173. }
  174. // ----------------------------------------------------------------------------
  175. // 响应辅助:保持与原 Gin 版相同的响应格式(JSON / text)
  176. // ----------------------------------------------------------------------------
  177. func writeJSON(w http.ResponseWriter, code int, v any) {
  178. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  179. w.WriteHeader(code)
  180. _ = json.NewEncoder(w).Encode(v)
  181. }
  182. func writeText(w http.ResponseWriter, code int, format string, args ...any) {
  183. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  184. w.WriteHeader(code)
  185. fmt.Fprintf(w, format, args...)
  186. }
  187. // clientIP 从 RemoteAddr 提取客户端 IP
  188. func clientIP(r *http.Request) string {
  189. host, _, err := net.SplitHostPort(r.RemoteAddr)
  190. if err != nil {
  191. return r.RemoteAddr
  192. }
  193. return host
  194. }
  195. // ----------------------------------------------------------------------------
  196. // 电源控制:shutdown /t 系统计时优先,休眠用 Go 计时;服务运行在 Session 0,
  197. // 无法弹 Toast 通知(原 GUI 版的 beeep 通知在此省略,改为写日志)
  198. // ----------------------------------------------------------------------------
  199. type pcCommand string
  200. const (
  201. pcPoweroff pcCommand = "poweroff"
  202. pcRestart pcCommand = "restart"
  203. pcSleep pcCommand = "sleep"
  204. )
  205. // PCStatus 电源命令状态快照(JSON 字段与 GUI 版一致)
  206. type PCStatus struct {
  207. Command string `json:"command"`
  208. Pending bool `json:"pending"`
  209. ExecuteAt string `json:"executeAt"`
  210. RemainingSecs int `json:"remainingSecs"`
  211. ClientIP string `json:"clientIp"`
  212. RequestTime string `json:"requestTime"`
  213. Requested bool `json:"requested"`
  214. }
  215. var (
  216. pcMu sync.Mutex
  217. pcTimer *time.Timer
  218. pcExecuteAt time.Time
  219. pcPending bool
  220. pcPendingCmd pcCommand
  221. pcSystemTimer bool // 是否已交给系统计时(shutdown /t)
  222. pcLastClientIP string
  223. pcLastTime time.Time
  224. pcLastCmd pcCommand
  225. pcRequested bool
  226. )
  227. // pcSystemCommand 构造系统命令;返回 nil 表示该命令需 Go 计时后立即执行
  228. func pcSystemCommand(cmd pcCommand, delaySec int) *exec.Cmd {
  229. switch runtime.GOOS {
  230. case "windows":
  231. switch cmd {
  232. case pcPoweroff:
  233. return exec.Command("shutdown", "/s", "/t", strconv.Itoa(delaySec), "/f")
  234. case pcRestart:
  235. return exec.Command("shutdown", "/r", "/t", strconv.Itoa(delaySec), "/f")
  236. }
  237. case "darwin":
  238. switch cmd {
  239. case pcPoweroff:
  240. return exec.Command("sudo", "shutdown", "-h", "+0")
  241. case pcRestart:
  242. return exec.Command("sudo", "shutdown", "-r", "+0")
  243. }
  244. case "linux":
  245. switch cmd {
  246. case pcPoweroff:
  247. return exec.Command("shutdown", "-h", "+0")
  248. case pcRestart:
  249. return exec.Command("shutdown", "-r", "+0")
  250. }
  251. }
  252. return nil
  253. }
  254. // pcExecuteNow 立即执行休眠(无系统计时,直接执行)
  255. func pcExecuteNow(cmd pcCommand) {
  256. var execCmd *exec.Cmd
  257. switch cmd {
  258. case pcSleep:
  259. switch runtime.GOOS {
  260. case "windows":
  261. execCmd = exec.Command("rundll32.exe", "powrprof.dll,SetSuspendState", "0,1,0")
  262. case "darwin":
  263. execCmd = exec.Command("pmset", "sleepnow")
  264. default:
  265. execCmd = exec.Command("systemctl", "suspend")
  266. }
  267. }
  268. if execCmd == nil {
  269. log.Printf("[SYS] 不支持的命令 %s (OS: %s)", cmd, runtime.GOOS)
  270. return
  271. }
  272. if output, err := execCmd.CombinedOutput(); err != nil {
  273. log.Printf("[SYS] 命令 %s 执行失败: %v | %s", cmd, err, string(output))
  274. } else {
  275. log.Printf("[SYS] 命令 %s 执行成功", cmd)
  276. }
  277. }
  278. // pcAbortShutdown 取消系统关机 / 重启倒计时
  279. func pcAbortShutdown() {
  280. if runtime.GOOS == "windows" {
  281. if output, err := exec.Command("shutdown", "/a").CombinedOutput(); err != nil {
  282. log.Printf("[SYS] 取消关机失败: %v | %s", err, string(output))
  283. } else {
  284. log.Println("[SYS] 系统关机已取消")
  285. }
  286. } else {
  287. _ = exec.Command("shutdown", "-c").Run()
  288. }
  289. }
  290. // getPCStatus 返回当前电源命令状态快照
  291. func getPCStatus() PCStatus {
  292. pcMu.Lock()
  293. defer pcMu.Unlock()
  294. status := PCStatus{
  295. Command: string(pcLastCmd),
  296. Pending: pcPending,
  297. ClientIP: pcLastClientIP,
  298. Requested: pcRequested,
  299. }
  300. if !pcLastTime.IsZero() {
  301. status.RequestTime = pcLastTime.Format("01-02 15:04:05")
  302. }
  303. if pcPending {
  304. status.ExecuteAt = pcExecuteAt.Format("01-02 15:04:05")
  305. remaining := int(time.Until(pcExecuteAt).Seconds())
  306. if remaining < 0 {
  307. remaining = 0
  308. }
  309. status.RemainingSecs = remaining
  310. }
  311. return status
  312. }
  313. // handleDelayedCommand 通用延迟命令:优先交给系统计时,不支持则用 Go 计时
  314. func handleDelayedCommand(w http.ResponseWriter, r *http.Request, cmd pcCommand, delay time.Duration, title string) {
  315. ip := clientIP(r)
  316. delaySec := int(delay.Seconds())
  317. pcMu.Lock()
  318. pcLastClientIP = ip
  319. pcLastTime = time.Now()
  320. pcLastCmd = cmd
  321. pcRequested = true
  322. if pcPending {
  323. remaining := time.Until(pcExecuteAt).Round(time.Second)
  324. pendingCmd := pcPendingCmd
  325. pcMu.Unlock()
  326. writeText(w, http.StatusOK, "命令 %s 已在待执行,剩余 %v\n", pendingCmd, remaining)
  327. return
  328. }
  329. pcPending = true
  330. pcPendingCmd = cmd
  331. pcExecuteAt = time.Now().Add(delay)
  332. sysCmd := pcSystemCommand(cmd, delaySec)
  333. if sysCmd != nil {
  334. pcSystemTimer = true
  335. pcMu.Unlock()
  336. if output, err := sysCmd.CombinedOutput(); err != nil {
  337. pcMu.Lock()
  338. pcPending = false
  339. pcPendingCmd = ""
  340. pcExecuteAt = time.Time{}
  341. pcSystemTimer = false
  342. pcMu.Unlock()
  343. log.Printf("[SYS] 命令 %s 下发失败: %v | %s", cmd, err, string(output))
  344. writeText(w, http.StatusInternalServerError, "命令执行失败: %v\n", err)
  345. return
  346. }
  347. log.Printf("[SYS] 命令 %s 交由系统计时 | %ds | 客户端 %s", cmd, delaySec, ip)
  348. } else {
  349. pcSystemTimer = false
  350. cmdToExec := cmd
  351. pcTimer = time.AfterFunc(delay, func() {
  352. pcMu.Lock()
  353. pcPending = false
  354. pcPendingCmd = ""
  355. pcMu.Unlock()
  356. pcExecuteNow(cmdToExec)
  357. })
  358. pcMu.Unlock()
  359. log.Printf("[SYS] 命令 %s 使用 Go 计时 | %ds | 客户端 %s", cmd, delaySec, ip)
  360. }
  361. writeText(w, http.StatusOK, "OK: %s\n", title)
  362. }
  363. func handlePoweroff(w http.ResponseWriter, r *http.Request) {
  364. handleDelayedCommand(w, r, pcPoweroff, pcShutdownDelay, "收到关机请求")
  365. }
  366. func handleRestart(w http.ResponseWriter, r *http.Request) {
  367. handleDelayedCommand(w, r, pcRestart, pcShutdownDelay, "收到重启请求")
  368. }
  369. func handleSleep(w http.ResponseWriter, r *http.Request) {
  370. handleDelayedCommand(w, r, pcSleep, pcShutdownDelay, "收到休眠请求")
  371. }
  372. // handleCancel 取消待执行命令:系统计时调 shutdown /a,Go 计时停定时器
  373. func handleCancel(w http.ResponseWriter, r *http.Request) {
  374. pcMu.Lock()
  375. if !pcPending {
  376. pcMu.Unlock()
  377. writeText(w, http.StatusOK, "无待执行命令\n")
  378. return
  379. }
  380. cancelled := pcPendingCmd
  381. wasSystemTimer := pcSystemTimer
  382. pcPending = false
  383. pcPendingCmd = ""
  384. pcExecuteAt = time.Time{}
  385. pcSystemTimer = false
  386. if pcTimer != nil {
  387. pcTimer.Stop()
  388. pcTimer = nil
  389. }
  390. pcMu.Unlock()
  391. if wasSystemTimer {
  392. pcAbortShutdown()
  393. }
  394. log.Printf("[SYS] 命令 %s 已取消 | 客户端 %s", cancelled, clientIP(r))
  395. writeText(w, http.StatusOK, "命令已取消\n")
  396. }
  397. func handlePCStatus(w http.ResponseWriter, r *http.Request) {
  398. writeJSON(w, http.StatusOK, getPCStatus())
  399. }
  400. // ----------------------------------------------------------------------------
  401. // 界面在线登记 + 请求代理(「服务打底 + 界面补全」)
  402. // ----------------------------------------------------------------------------
  403. var (
  404. uiPeerMu sync.RWMutex
  405. uiPeerAddr string
  406. uiPeerSeenAt time.Time
  407. // uiProxyClient 复用的转发客户端:每次请求 new http.Client 会各自创建独立
  408. // Transport/连接池,代理频繁时连接池资源只增不减,是常驻内存增长的来源。
  409. uiProxyClient = &http.Client{
  410. Timeout: proxyTimeout,
  411. Transport: &http.Transport{
  412. MaxIdleConns: 8, // 上限连接数,防连接池无界膨胀
  413. MaxIdleConnsPerHost: 4, // 单主机空闲连接上限
  414. IdleConnTimeout: 60 * time.Second, // 空闲连接回收
  415. },
  416. }
  417. )
  418. // uiPeerOnline 界面上次登记是否在 90 秒内(心跳 30 秒一次)
  419. func uiPeerOnline() bool {
  420. uiPeerMu.RLock()
  421. defer uiPeerMu.RUnlock()
  422. return uiPeerAddr != "" && time.Since(uiPeerSeenAt) < 90*time.Second
  423. }
  424. // handleUIRegister 界面登记/心跳:POST /api/ui/register {"addr":"127.0.0.1:17891"}
  425. // 仅接受本机回环请求,避免局域网内被恶意登记后劫持转发。
  426. func handleUIRegister(w http.ResponseWriter, r *http.Request) {
  427. host, _, err := net.SplitHostPort(r.RemoteAddr)
  428. ip := net.ParseIP(host)
  429. if err != nil || ip == nil || !ip.IsLoopback() {
  430. writeJSON(w, http.StatusForbidden, map[string]any{"error": "仅允许本机登记"})
  431. return
  432. }
  433. var req struct {
  434. Addr string `json:"addr"`
  435. }
  436. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  437. writeJSON(w, http.StatusBadRequest, map[string]any{"error": "参数格式错误"})
  438. return
  439. }
  440. addr := strings.TrimSpace(req.Addr)
  441. if _, _, err := net.SplitHostPort(addr); err != nil {
  442. writeJSON(w, http.StatusBadRequest, map[string]any{"error": "addr 需为 host:port"})
  443. return
  444. }
  445. uiPeerMu.Lock()
  446. uiPeerAddr = addr
  447. uiPeerSeenAt = time.Now()
  448. uiPeerMu.Unlock()
  449. log.Printf("ui registered: %s", addr)
  450. writeJSON(w, http.StatusOK, map[string]any{"ok": true})
  451. }
  452. // handleUIStatus 查询界面登记情况
  453. func handleUIStatus(w http.ResponseWriter, r *http.Request) {
  454. uiPeerMu.RLock()
  455. addr, seen := uiPeerAddr, uiPeerSeenAt
  456. uiPeerMu.RUnlock()
  457. writeJSON(w, http.StatusOK, map[string]any{
  458. "uiAddr": addr,
  459. "online": uiPeerOnline(),
  460. "lastSee": seen.Format(time.RFC3339),
  461. })
  462. }
  463. // proxyToUI 把服务模式未实现的请求转发给界面 API;界面未上线时返回 503
  464. func proxyToUI(w http.ResponseWriter, r *http.Request) {
  465. uiPeerMu.RLock()
  466. addr := uiPeerAddr
  467. uiPeerMu.RUnlock()
  468. if addr == "" || !uiPeerOnline() {
  469. writeJSON(w, http.StatusServiceUnavailable, map[string]any{
  470. "service": true,
  471. "error": "界面未启动或未登记,该接口暂不可用(电源类接口仍可用)",
  472. })
  473. return
  474. }
  475. target := "http://" + addr + r.URL.RequestURI()
  476. req, err := http.NewRequestWithContext(r.Context(), r.Method, target, r.Body)
  477. if err != nil {
  478. writeJSON(w, http.StatusBadGateway, map[string]any{"error": "构造转发请求失败"})
  479. return
  480. }
  481. for k, values := range r.Header {
  482. for _, v := range values {
  483. req.Header.Add(k, v)
  484. }
  485. }
  486. req.Header.Set("X-Forwarded-Host", r.Host)
  487. req.Header.Set("X-TengTu-Via", "service")
  488. if ip := clientIP(r); ip != "" {
  489. req.Header.Set("X-Forwarded-For", ip)
  490. }
  491. resp, err := uiProxyClient.Do(req)
  492. if err != nil {
  493. writeJSON(w, http.StatusBadGateway, map[string]any{"error": "界面接口无响应: " + err.Error()})
  494. return
  495. }
  496. defer resp.Body.Close()
  497. for k, values := range resp.Header {
  498. for _, v := range values {
  499. w.Header().Add(k, v)
  500. }
  501. }
  502. w.WriteHeader(resp.StatusCode)
  503. _, _ = io.Copy(w, resp.Body)
  504. }
  505. // ----------------------------------------------------------------------------
  506. // 指令信箱:POST /api/xz/cmd 下发指令(left / right / up / down,支持任意文本),
  507. // GET /api/xz/cmd 取走最近一条指令(读取后清除);GET /api/xz/cmd/<命令> 路径下发。
  508. // 界面在线时转发给界面(指令信箱与界面共享),离线时本地兜底。
  509. // ----------------------------------------------------------------------------
  510. var (
  511. xzCmdMu sync.Mutex
  512. xzCmdLast string
  513. xzCmdSeq int64
  514. )
  515. // handleXZCmd POST=下发(body {"cmd":"left"} 或 ?cmd=left),GET=取走
  516. func handleXZCmd(w http.ResponseWriter, r *http.Request) {
  517. if forwardToUI(w, r) {
  518. return
  519. }
  520. if r.Method == http.MethodPost {
  521. xzPost(w, r, strings.TrimPrefix(r.URL.Path, "/api/xz/cmd"))
  522. return
  523. }
  524. // GET:消费式读取,取走即清除
  525. xzCmdMu.Lock()
  526. cmd := xzCmdLast
  527. xzCmdLast = ""
  528. xzCmdMu.Unlock()
  529. writeText(w, http.StatusOK, "%s", cmd)
  530. }
  531. // handleXZCmdPath 路径参数下发:GET /api/xz/cmd/<命令>(URL 编码)
  532. func handleXZCmdPath(w http.ResponseWriter, r *http.Request) {
  533. if forwardToUI(w, r) {
  534. return
  535. }
  536. xzPost(w, r, strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/xz/cmd/"), "/"))
  537. }
  538. // xzPost 校验并保存一条指令
  539. func xzPost(w http.ResponseWriter, r *http.Request, pathCmd string) {
  540. var req struct {
  541. Cmd string `json:"cmd"`
  542. }
  543. if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.Cmd) == "" {
  544. req.Cmd = r.URL.Query().Get("cmd") // 非 JSON 请求时回退到查询参数
  545. }
  546. if pathCmd != "" {
  547. req.Cmd = pathCmd // 路径参数优先
  548. }
  549. cmd := strings.TrimSpace(req.Cmd)
  550. if cmd == "" {
  551. writeJSON(w, http.StatusBadRequest, map[string]any{"error": "cmd 不能为空"})
  552. return
  553. }
  554. if utf8.RuneCountInString(cmd) > xzCmdMaxLen {
  555. writeJSON(w, http.StatusBadRequest, map[string]any{"error": fmt.Sprintf("cmd 长度不能超过 %d 个字符", xzCmdMaxLen)})
  556. return
  557. }
  558. xzCmdMu.Lock()
  559. xzCmdLast = cmd
  560. xzCmdSeq++
  561. seq := xzCmdSeq
  562. xzCmdMu.Unlock()
  563. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "cmd": cmd, "seq": seq})
  564. }
  565. // forwardToUI 界面已登记在线时把请求转发给界面并返回 true
  566. func forwardToUI(w http.ResponseWriter, r *http.Request) bool {
  567. if !uiPeerOnline() {
  568. return false
  569. }
  570. proxyToUI(w, r)
  571. return true
  572. }
  573. // ----------------------------------------------------------------------------
  574. // 端口容错:监听地址被占用时自动切换到备用端口
  575. // (与根目录 apiserver_shared.go 的版本内容一致;独立二进制无法引用,故复制)
  576. // ----------------------------------------------------------------------------
  577. // listenFirst 依次尝试监听 addrs,返回第一个成功绑定的监听器及其逻辑地址。
  578. func listenFirst(addrs ...string) (net.Listener, string, error) {
  579. var lastErr error
  580. for _, addr := range addrs {
  581. ln, err := net.Listen("tcp", addr)
  582. if err == nil {
  583. return ln, addr, nil
  584. }
  585. lastErr = err
  586. }
  587. return nil, "", lastErr
  588. }
  589. // nextPortAddr 同 host 端口 +1 的备用地址;解析失败或端口越界时返回原地址。
  590. func nextPortAddr(addr string) string {
  591. host, portStr, err := net.SplitHostPort(addr)
  592. if err != nil {
  593. return addr
  594. }
  595. port, err := strconv.Atoi(portStr)
  596. if err != nil || port <= 0 || port >= 65535 {
  597. return addr
  598. }
  599. return net.JoinHostPort(host, strconv.Itoa(port+1))
  600. }