rpc_handler.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. package main
  2. import (
  3. "archive/tar"
  4. "compress/gzip"
  5. "context"
  6. "crypto/md5"
  7. "encoding/hex"
  8. "encoding/json"
  9. "fmt"
  10. "io"
  11. "os"
  12. "os/exec"
  13. "path"
  14. "path/filepath"
  15. "strings"
  16. "sync"
  17. "time"
  18. "hnyfkj.com.cn/rtu/linux/baseapp"
  19. "hnyfkj.com.cn/rtu/linux/utils/jsonrpc2"
  20. )
  21. type PkgInfo struct {
  22. FileName string `json:"fileName"`
  23. FileSize int64 `json:"fileSize"`
  24. CheckMD5Val string `json:"fileMD5"`
  25. UploadTime string `json:"uploadTime"`
  26. }
  27. type AppInfo struct {
  28. Name string `json:"name"`
  29. Version string `json:"version"`
  30. Executable string `json:"executable"`
  31. LibPaths []string `json:"libraryPaths"`
  32. Description string `json:"description"`
  33. ReadmeFile string `json:"readmeFile"`
  34. }
  35. type InsInfo struct {
  36. Installed bool `json:"installed"`
  37. InstallTime string `json:"installTime"`
  38. }
  39. type AppIns struct {
  40. Pkg PkgInfo `json:"pkg"` // 应用的安装包
  41. App AppInfo `json:"app"` // 应用详细信息
  42. Ins InsInfo `json:"ins"` // 应用是否安装
  43. }
  44. var (
  45. appMutex sync.Mutex
  46. )
  47. const (
  48. userAppInsDir = "/home/root/yfkj-user-app"
  49. userAppService = "/etc/systemd/system/yfkj-user-app.service"
  50. ErrConflict jsonrpc2.ErrCode = -32099 ///////// 资源访问冲突
  51. )
  52. // 导入用户安装包
  53. func pkgImport(ctx context.Context, req *jsonrpc2.Request) *jsonrpc2.Response {
  54. appMutex.Lock()
  55. defer appMutex.Unlock()
  56. var params map[string]string
  57. if err := json.Unmarshal(req.Params, &params); err != nil {
  58. return jsonrpc2.BuildError(req, jsonrpc2.ErrInvalidParams, err.Error())
  59. }
  60. file, ok := params["file"]
  61. if !ok || file == "" {
  62. return jsonrpc2.BuildError(req, jsonrpc2.ErrInvalidParams, "missing or empty 'file' parameter")
  63. }
  64. if !strings.HasSuffix(strings.ToLower(filepath.Base(file)), ".tar.gz") {
  65. return jsonrpc2.BuildError(req, jsonrpc2.ErrInvalidParams, "invalid install package format")
  66. }
  67. info, err := os.Stat(file)
  68. if err != nil {
  69. return jsonrpc2.BuildError(req, jsonrpc2.ErrInvalidParams, err.Error())
  70. }
  71. if !info.Mode().IsRegular() {
  72. return jsonrpc2.BuildError(req, jsonrpc2.ErrInvalidParams, "invalid install package file")
  73. }
  74. if err := os.MkdirAll(userAppPkgDir, 0755); err != nil {
  75. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  76. }
  77. if hasImportedPackage(userAppPkgDir) {
  78. return jsonrpc2.BuildError(req, ErrConflict, "application package already exists")
  79. }
  80. appInfo, err := readAppJSON(file)
  81. if err != nil {
  82. return jsonrpc2.BuildError(req, jsonrpc2.ErrInvalidParams, err.Error())
  83. }
  84. md5Val, err := fileMD5(file)
  85. if err != nil {
  86. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  87. }
  88. savePkgFile := filepath.Join(userAppPkgDir, filepath.Base(file))
  89. if err := moveFile(file, savePkgFile); err != nil {
  90. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  91. }
  92. appIns := AppIns{
  93. Pkg: PkgInfo{
  94. FileName: filepath.Base(file),
  95. FileSize: info.Size(),
  96. CheckMD5Val: md5Val,
  97. UploadTime: time.Now().Format("2006-01-02 15:04:05"),
  98. },
  99. App: appInfo,
  100. Ins: InsInfo{
  101. Installed: false,
  102. },
  103. }
  104. data, err := json.MarshalIndent(appIns, "", " ")
  105. if err != nil {
  106. os.Remove(savePkgFile)
  107. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  108. }
  109. appInsFile := filepath.Join(userAppPkgDir, "appins.json")
  110. if err := writeFileAtomic(appInsFile, data, 0644); err != nil {
  111. os.Remove(savePkgFile)
  112. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  113. }
  114. baseapp.Logger.Infof("导入用户应用安装包成功: %s, 版本: %s, 描述: %s",
  115. appIns.App.Name, appIns.App.Version, appIns.App.Description)
  116. return jsonrpc2.BuildResponse(req, "success", nil)
  117. }
  118. // 删除用户安装包
  119. func pkgRemove(ctx context.Context, req *jsonrpc2.Request) *jsonrpc2.Response {
  120. appMutex.Lock()
  121. defer appMutex.Unlock()
  122. appInsFile := filepath.Join(userAppPkgDir, "appins.json")
  123. var appIns AppIns
  124. data, err := os.ReadFile(appInsFile)
  125. if err == nil {
  126. if err := json.Unmarshal(data, &appIns); err == nil {
  127. if appIns.Ins.Installed { // 用户应用已安装
  128. return jsonrpc2.BuildError(req, ErrConflict, "application is installed, please uninstall it first")
  129. }
  130. }
  131. } else if !os.IsNotExist(err) {
  132. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  133. }
  134. if err := os.RemoveAll(userAppPkgDir); err != nil {
  135. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  136. }
  137. if err := os.MkdirAll(userAppPkgDir, 0755); err != nil {
  138. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  139. }
  140. baseapp.Logger.Infof("删除用户应用安装包成功: %s, 版本: %s, 描述: %s",
  141. appIns.App.Name, appIns.App.Version, appIns.App.Description)
  142. return jsonrpc2.BuildResponse(req, "success", nil)
  143. }
  144. // 安装包应用安装
  145. func appInstall(ctx context.Context, req *jsonrpc2.Request) *jsonrpc2.Response {
  146. appMutex.Lock()
  147. defer appMutex.Unlock()
  148. appInsFile := filepath.Join(userAppPkgDir, "appins.json")
  149. data, err := os.ReadFile(appInsFile)
  150. if err != nil {
  151. return jsonrpc2.BuildError(req, jsonrpc2.ErrInvalidParams, "application package not found")
  152. }
  153. var appIns AppIns
  154. if err := json.Unmarshal(data, &appIns); err != nil {
  155. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  156. }
  157. if appIns.Ins.Installed {
  158. return jsonrpc2.BuildError(req, ErrConflict, "application already installed")
  159. }
  160. success := false
  161. defer func() {
  162. if !success {
  163. baseapp.Logger.Warnf("安装用户应用失败状态回滚: %s", userAppInsDir)
  164. systemctlIgnoreError("stop", "yfkj-user-app.service")
  165. systemctlIgnoreError("disable", "yfkj-user-app.service")
  166. os.RemoveAll(userAppInsDir)
  167. os.Remove(userAppService)
  168. systemctlIgnoreError("daemon-reload")
  169. }
  170. }()
  171. systemctlIgnoreError("stop", "yfkj-user-app.service")
  172. if err := os.MkdirAll(userAppInsDir, 0755); err != nil {
  173. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  174. }
  175. appPkgFile := filepath.Join(userAppPkgDir, appIns.Pkg.FileName)
  176. if err := extractTarGz(appPkgFile, userAppInsDir); err != nil {
  177. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  178. }
  179. execFile := filepath.Join(userAppInsDir, appIns.App.Executable)
  180. info, err := os.Stat(execFile)
  181. if err != nil {
  182. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, "executable not found")
  183. }
  184. if !info.Mode().IsRegular() {
  185. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, "invalid executable")
  186. }
  187. if err := os.Chmod(execFile, 0755); err != nil {
  188. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  189. }
  190. if err := createUserAppService(appIns.App, userAppInsDir); err != nil {
  191. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  192. }
  193. if err := systemctl("daemon-reload"); err != nil {
  194. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  195. }
  196. if err := systemctl("enable", "yfkj-user-app.service"); err != nil {
  197. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  198. }
  199. if err := systemctl("start", "yfkj-user-app.service"); err != nil {
  200. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  201. }
  202. appIns.Ins.Installed = true
  203. appIns.Ins.InstallTime = time.Now().Format("2006-01-02 15:04:05")
  204. data, err = json.MarshalIndent(appIns, "", " ")
  205. if err != nil {
  206. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  207. }
  208. if err := writeFileAtomic(appInsFile, data, 0644); err != nil {
  209. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  210. }
  211. success = true
  212. baseapp.Logger.Infof("安装用户应用成功: %s, 版本: %s, 描述: %s",
  213. appIns.App.Name, appIns.App.Version, appIns.App.Description)
  214. return jsonrpc2.BuildResponse(req, "success", nil)
  215. }
  216. // 卸载已安装应用
  217. func appUninstall(ctx context.Context, req *jsonrpc2.Request) *jsonrpc2.Response {
  218. appMutex.Lock()
  219. defer appMutex.Unlock()
  220. appInsFile := filepath.Join(userAppPkgDir, "appins.json")
  221. data, err := os.ReadFile(appInsFile)
  222. if err != nil {
  223. return jsonrpc2.BuildError(req, jsonrpc2.ErrInvalidParams, "application package not found")
  224. }
  225. var appIns AppIns
  226. if err := json.Unmarshal(data, &appIns); err != nil {
  227. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  228. }
  229. if !appIns.Ins.Installed {
  230. return jsonrpc2.BuildError(req, ErrConflict, "application not installed")
  231. }
  232. systemctlIgnoreError("stop", "yfkj-user-app.service")
  233. systemctlIgnoreError("disable", "yfkj-user-app.service")
  234. if err := os.Remove(userAppService); err != nil && !os.IsNotExist(err) {
  235. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  236. }
  237. if err := systemctl("daemon-reload"); err != nil {
  238. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  239. }
  240. if err := os.RemoveAll(userAppInsDir); err != nil {
  241. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  242. }
  243. appIns.Ins.Installed = false
  244. appIns.Ins.InstallTime = ""
  245. data, err = json.MarshalIndent(appIns, "", " ")
  246. if err != nil {
  247. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  248. }
  249. if err := writeFileAtomic(appInsFile, data, 0644); err != nil {
  250. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  251. }
  252. baseapp.Logger.Infof("卸载用户应用成功: %s, 版本: %s, 描述: %s",
  253. appIns.App.Name, appIns.App.Version, appIns.App.Description)
  254. return jsonrpc2.BuildResponse(req, "success", nil)
  255. }
  256. // 安装包应用信息
  257. func getInstallInfo(ctx context.Context, req *jsonrpc2.Request) *jsonrpc2.Response {
  258. appInsFile := filepath.Join(userAppPkgDir, "appins.json")
  259. data, err := os.ReadFile(appInsFile)
  260. if err != nil {
  261. if os.IsNotExist(err) {
  262. return jsonrpc2.BuildResponse(req, nil, nil)
  263. }
  264. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  265. }
  266. var appIns AppIns
  267. if err := json.Unmarshal(data, &appIns); err != nil {
  268. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  269. }
  270. if appIns.App.ReadmeFile != "" {
  271. readme, err := os.ReadFile(filepath.Join(userAppInsDir, appIns.App.ReadmeFile))
  272. if err != nil {
  273. appIns.App.ReadmeFile = ""
  274. } else {
  275. appIns.App.ReadmeFile = string(readme)
  276. }
  277. }
  278. return jsonrpc2.BuildResponse(req, appIns, nil)
  279. }
  280. func readAppJSON(file string) (AppInfo, error) {
  281. var app AppInfo
  282. f, err := os.Open(file)
  283. if err != nil {
  284. return app, err
  285. }
  286. defer f.Close()
  287. gz, err := gzip.NewReader(f)
  288. if err != nil {
  289. return app, err
  290. }
  291. defer gz.Close()
  292. tr := tar.NewReader(gz)
  293. for {
  294. header, err := tr.Next()
  295. if err == io.EOF {
  296. break
  297. }
  298. if err != nil {
  299. return app, err
  300. }
  301. if header.Typeflag != tar.TypeReg {
  302. continue
  303. }
  304. if path.Base(header.Name) != "app.json" {
  305. continue
  306. }
  307. if header.Size > 2<<20 { // 2MB 上限
  308. return app, fmt.Errorf("app.json 文件过大")
  309. }
  310. data, err := io.ReadAll(io.LimitReader(tr, header.Size))
  311. if err != nil {
  312. return app, err
  313. }
  314. err = json.Unmarshal(data, &app)
  315. if err != nil {
  316. return app, err
  317. }
  318. if app.Name == "" || app.Version == "" || app.Executable == "" {
  319. return app, fmt.Errorf("app.json参数不完整")
  320. }
  321. if !validRelativePath(app.Executable) {
  322. return app, fmt.Errorf("invalid executable path")
  323. }
  324. for _, p := range app.LibPaths {
  325. if validRelativePath(p) {
  326. continue
  327. }
  328. return app, fmt.Errorf("invalid library path: %s", p)
  329. }
  330. return app, nil
  331. }
  332. return app, fmt.Errorf("安装包中未找到 app.json")
  333. }
  334. func fileMD5(file string) (string, error) {
  335. f, err := os.Open(file)
  336. if err != nil {
  337. return "", err
  338. }
  339. defer f.Close()
  340. h := md5.New()
  341. if _, err := io.Copy(h, f); err != nil {
  342. return "", err
  343. }
  344. return hex.EncodeToString(h.Sum(nil)), nil
  345. }
  346. func moveFile(src, dst string) error {
  347. if err := os.Rename(src, dst); err == nil {
  348. return nil
  349. }
  350. in, err := os.Open(src)
  351. if err != nil {
  352. return err
  353. }
  354. defer in.Close()
  355. out, err := os.Create(dst)
  356. if err != nil {
  357. return err
  358. }
  359. _, err = io.Copy(out, in)
  360. if err != nil {
  361. out.Close()
  362. os.Remove(dst)
  363. return err
  364. }
  365. if err := out.Close(); err != nil {
  366. os.Remove(dst)
  367. return err
  368. }
  369. return os.Remove(src)
  370. }
  371. func validRelativePath(p string) bool {
  372. if p == "" {
  373. return false
  374. }
  375. if filepath.IsAbs(p) {
  376. return false
  377. }
  378. clean := filepath.Clean(p)
  379. if clean != p {
  380. return false
  381. }
  382. if clean == ".." ||
  383. strings.HasPrefix(clean, ".."+string(os.PathSeparator)) {
  384. return false
  385. }
  386. return true
  387. }
  388. func isRegularFile(name string) bool {
  389. info, err := os.Stat(name)
  390. if err != nil {
  391. return false
  392. }
  393. return info.Mode().IsRegular()
  394. }
  395. func hasImportedPackage(dir string) bool {
  396. if isRegularFile(filepath.Join(dir, "appins.json")) {
  397. return true
  398. }
  399. entries, err := os.ReadDir(dir)
  400. if err != nil {
  401. return false
  402. }
  403. for _, entry := range entries {
  404. if entry.IsDir() {
  405. continue
  406. }
  407. if strings.HasSuffix(strings.ToLower(entry.Name()), ".tar.gz") {
  408. return true
  409. }
  410. }
  411. return false
  412. }
  413. func writeFileAtomic(name string, data []byte, perm os.FileMode) error {
  414. tmp := name + ".tmp"
  415. defer os.Remove(tmp)
  416. f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, perm)
  417. if err != nil {
  418. return err
  419. }
  420. if _, err := f.Write(data); err != nil {
  421. f.Close()
  422. return err
  423. }
  424. if err := f.Sync(); err != nil {
  425. f.Close()
  426. return err
  427. }
  428. if err := f.Close(); err != nil {
  429. return err
  430. }
  431. return os.Rename(tmp, name)
  432. }
  433. func extractTarGz(src string, dst string) error {
  434. f, err := os.Open(src)
  435. if err != nil {
  436. return err
  437. }
  438. defer f.Close()
  439. gz, err := gzip.NewReader(f)
  440. if err != nil {
  441. return err
  442. }
  443. defer gz.Close()
  444. tr := tar.NewReader(gz)
  445. root := filepath.Clean(dst) + string(os.PathSeparator)
  446. for {
  447. header, err := tr.Next()
  448. if err == io.EOF {
  449. break
  450. }
  451. if err != nil {
  452. return err
  453. }
  454. name := filepath.Join(dst, header.Name)
  455. name = filepath.Clean(name)
  456. if !strings.HasPrefix(name+string(os.PathSeparator), root) {
  457. return fmt.Errorf("invalid path: %s", header.Name)
  458. }
  459. switch header.Typeflag {
  460. case tar.TypeDir:
  461. if err := os.MkdirAll(name, 0755); err != nil {
  462. return err
  463. }
  464. case tar.TypeReg:
  465. if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil {
  466. return err
  467. }
  468. out, err := os.OpenFile(
  469. name,
  470. os.O_CREATE|os.O_WRONLY|os.O_TRUNC,
  471. os.FileMode(header.Mode),
  472. )
  473. if err != nil {
  474. return err
  475. }
  476. _, err = io.Copy(out, tr)
  477. out.Close()
  478. if err != nil {
  479. return err
  480. }
  481. default:
  482. return fmt.Errorf("unsupported tar entry: %s", header.Name)
  483. }
  484. }
  485. return nil
  486. }
  487. func createUserAppService(app AppInfo, installDir string) error {
  488. execFile := filepath.Join(installDir, app.Executable)
  489. libPaths := ""
  490. if len(app.LibPaths) > 0 {
  491. paths := make([]string, 0, len(app.LibPaths))
  492. for _, p := range app.LibPaths {
  493. paths = append(paths, filepath.Join(installDir, p))
  494. }
  495. libPaths = strings.Join(paths, ":")
  496. }
  497. content := fmt.Sprintf(`[Unit]
  498. Description=%s
  499. After=yfkj-networkd.service
  500. Wants=yfkj-networkd.service
  501. [Service]
  502. Environment="PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin"
  503. Environment="LD_LIBRARY_PATH=%s"
  504. WorkingDirectory=%s
  505. ExecStart=%s
  506. Restart=always
  507. RestartSec=5
  508. StandardOutput=journal
  509. StandardError=journal
  510. [Install]
  511. WantedBy=multi-user.target
  512. `,
  513. "Yunfei User Application",
  514. libPaths,
  515. installDir,
  516. execFile,
  517. )
  518. return os.WriteFile(userAppService, []byte(content), 0644)
  519. }
  520. func systemctl(args ...string) error {
  521. out, err := exec.Command("systemctl", args...).CombinedOutput()
  522. if err != nil {
  523. return fmt.Errorf("systemctl %v failed: %v %s", args, err, string(out))
  524. }
  525. return nil
  526. }
  527. func systemctlIgnoreError(args ...string) {
  528. _ = exec.Command("systemctl", args...).Run()
  529. }