rpc_handler.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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-userapp"
  49. userAppService = "/etc/systemd/system/yfkj-userapp.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 := os.Rename(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("[PkgImport] 导入用户应用安装包成功: %s", savePkgFile)
  115. return jsonrpc2.BuildResponse(req, "success", nil)
  116. }
  117. // 删除用户安装包
  118. func pkgRemove(ctx context.Context, req *jsonrpc2.Request) *jsonrpc2.Response {
  119. appMutex.Lock()
  120. defer appMutex.Unlock()
  121. appInsFile := filepath.Join(userAppPkgDir, "appins.json")
  122. data, err := os.ReadFile(appInsFile)
  123. if err == nil {
  124. var appIns AppIns
  125. if err := json.Unmarshal(data, &appIns); err == nil {
  126. if appIns.Ins.Installed { // 用户应用已安装
  127. return jsonrpc2.BuildError(req, ErrConflict, "application is installed, please uninstall it first")
  128. }
  129. }
  130. } else if !os.IsNotExist(err) {
  131. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  132. }
  133. if err := os.RemoveAll(userAppPkgDir); err != nil {
  134. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  135. }
  136. if err := os.MkdirAll(userAppPkgDir, 0755); err != nil {
  137. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  138. }
  139. baseapp.Logger.Infof("[PkgRemove] 删除用户应用安装包成功")
  140. return jsonrpc2.BuildResponse(req, "success", nil)
  141. }
  142. // 安装包应用安装
  143. func appInstall(ctx context.Context, req *jsonrpc2.Request) *jsonrpc2.Response {
  144. appMutex.Lock()
  145. defer appMutex.Unlock()
  146. appInsFile := filepath.Join(userAppPkgDir, "appins.json")
  147. data, err := os.ReadFile(appInsFile)
  148. if err != nil {
  149. return jsonrpc2.BuildError(req, jsonrpc2.ErrInvalidParams, "application package not found")
  150. }
  151. var appIns AppIns
  152. if err := json.Unmarshal(data, &appIns); err != nil {
  153. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  154. }
  155. if appIns.Ins.Installed {
  156. return jsonrpc2.BuildError(req, ErrConflict, "application already installed")
  157. }
  158. success := false
  159. defer func() {
  160. if !success {
  161. baseapp.Logger.Warnf("[AppInstall] rollback: %s", userAppInsDir)
  162. systemctlIgnoreError("stop", "yfkj-userapp.service")
  163. systemctlIgnoreError("disable", "yfkj-userapp.service")
  164. os.RemoveAll(userAppInsDir)
  165. os.Remove(userAppService)
  166. systemctlIgnoreError("daemon-reload")
  167. }
  168. }()
  169. systemctlIgnoreError("stop", "yfkj-userapp.service")
  170. if err := os.MkdirAll(userAppInsDir, 0755); err != nil {
  171. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  172. }
  173. appPkgFile := filepath.Join(userAppPkgDir, appIns.Pkg.FileName)
  174. if err := extractTarGz(appPkgFile, userAppInsDir); err != nil {
  175. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  176. }
  177. execFile := filepath.Join(userAppInsDir, appIns.App.Executable)
  178. info, err := os.Stat(execFile)
  179. if err != nil {
  180. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, "executable not found")
  181. }
  182. if !info.Mode().IsRegular() {
  183. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, "invalid executable")
  184. }
  185. if err := os.Chmod(execFile, 0755); err != nil {
  186. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  187. }
  188. if err := createUserAppService(appIns.App, userAppInsDir); err != nil {
  189. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  190. }
  191. if err := systemctl("daemon-reload"); err != nil {
  192. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  193. }
  194. if err := systemctl("enable", "yfkj-userapp.service"); err != nil {
  195. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  196. }
  197. if err := systemctl("start", "yfkj-userapp.service"); err != nil {
  198. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  199. }
  200. appIns.Ins.Installed = true
  201. appIns.Ins.InstallTime = time.Now().Format("2006-01-02 15:04:05")
  202. data, err = json.MarshalIndent(appIns, "", " ")
  203. if err != nil {
  204. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  205. }
  206. if err := writeFileAtomic(appInsFile, data, 0644); err != nil {
  207. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  208. }
  209. success = true
  210. baseapp.Logger.Infof("[AppInstall] 安装用户应用成功: %s", appIns.App.Name)
  211. return jsonrpc2.BuildResponse(req, "success", nil)
  212. }
  213. // 卸载已安装应用
  214. func appUninstall(ctx context.Context, req *jsonrpc2.Request) *jsonrpc2.Response {
  215. appMutex.Lock()
  216. defer appMutex.Unlock()
  217. appInsFile := filepath.Join(userAppPkgDir, "appins.json")
  218. data, err := os.ReadFile(appInsFile)
  219. if err != nil {
  220. return jsonrpc2.BuildError(req, jsonrpc2.ErrInvalidParams, "application package not found")
  221. }
  222. var appIns AppIns
  223. if err := json.Unmarshal(data, &appIns); err != nil {
  224. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  225. }
  226. if !appIns.Ins.Installed {
  227. return jsonrpc2.BuildError(req, ErrConflict, "application not installed")
  228. }
  229. systemctlIgnoreError("stop", "yfkj-userapp.service")
  230. systemctlIgnoreError("disable", "yfkj-userapp.service")
  231. if err := os.Remove(userAppService); err != nil && !os.IsNotExist(err) {
  232. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  233. }
  234. if err := systemctl("daemon-reload"); err != nil {
  235. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  236. }
  237. if err := os.RemoveAll(userAppInsDir); err != nil {
  238. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  239. }
  240. appIns.Ins.Installed = false
  241. appIns.Ins.InstallTime = ""
  242. data, err = json.MarshalIndent(appIns, "", " ")
  243. if err != nil {
  244. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  245. }
  246. if err := writeFileAtomic(appInsFile, data, 0644); err != nil {
  247. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  248. }
  249. baseapp.Logger.Infof("[AppUninstall] 卸载用户应用成功: %s", appIns.App.Name)
  250. return jsonrpc2.BuildResponse(req, "success", nil)
  251. }
  252. // 安装包应用信息
  253. func getInstallInfo(ctx context.Context, req *jsonrpc2.Request) *jsonrpc2.Response {
  254. appInsFile := filepath.Join(userAppPkgDir, "appins.json")
  255. data, err := os.ReadFile(appInsFile)
  256. if err != nil {
  257. if os.IsNotExist(err) {
  258. return jsonrpc2.BuildResponse(req, nil, nil)
  259. }
  260. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  261. }
  262. var appIns AppIns
  263. if err := json.Unmarshal(data, &appIns); err != nil {
  264. return jsonrpc2.BuildError(req, jsonrpc2.ErrInternal, err.Error())
  265. }
  266. return jsonrpc2.BuildResponse(req, appIns, nil)
  267. }
  268. func readAppJSON(file string) (AppInfo, error) {
  269. var app AppInfo
  270. f, err := os.Open(file)
  271. if err != nil {
  272. return app, err
  273. }
  274. defer f.Close()
  275. gz, err := gzip.NewReader(f)
  276. if err != nil {
  277. return app, err
  278. }
  279. defer gz.Close()
  280. tr := tar.NewReader(gz)
  281. for {
  282. header, err := tr.Next()
  283. if err == io.EOF {
  284. break
  285. }
  286. if err != nil {
  287. return app, err
  288. }
  289. if header.Typeflag != tar.TypeReg {
  290. continue
  291. }
  292. if path.Base(header.Name) != "app.json" {
  293. continue
  294. }
  295. if header.Size > 2<<20 { // 2MB 上限
  296. return app, fmt.Errorf("app.json 文件过大")
  297. }
  298. data, err := io.ReadAll(io.LimitReader(tr, header.Size))
  299. if err != nil {
  300. return app, err
  301. }
  302. err = json.Unmarshal(data, &app)
  303. if err != nil {
  304. return app, err
  305. }
  306. if app.Name == "" || app.Version == "" || app.Executable == "" {
  307. return app, fmt.Errorf("app.json参数不完整")
  308. }
  309. if !validRelativePath(app.Executable) {
  310. return app, fmt.Errorf("invalid executable path")
  311. }
  312. for _, p := range app.LibPaths {
  313. if validRelativePath(p) {
  314. continue
  315. }
  316. return app, fmt.Errorf("invalid library path: %s", p)
  317. }
  318. return app, nil
  319. }
  320. return app, fmt.Errorf("安装包中未找到 app.json")
  321. }
  322. func fileMD5(file string) (string, error) {
  323. f, err := os.Open(file)
  324. if err != nil {
  325. return "", err
  326. }
  327. defer f.Close()
  328. h := md5.New()
  329. if _, err := io.Copy(h, f); err != nil {
  330. return "", err
  331. }
  332. return hex.EncodeToString(h.Sum(nil)), nil
  333. }
  334. func validRelativePath(p string) bool {
  335. if p == "" {
  336. return false
  337. }
  338. if filepath.IsAbs(p) {
  339. return false
  340. }
  341. clean := filepath.Clean(p)
  342. if clean != p {
  343. return false
  344. }
  345. if clean == ".." ||
  346. strings.HasPrefix(clean, ".."+string(os.PathSeparator)) {
  347. return false
  348. }
  349. return true
  350. }
  351. func isRegularFile(name string) bool {
  352. info, err := os.Stat(name)
  353. if err != nil {
  354. return false
  355. }
  356. return info.Mode().IsRegular()
  357. }
  358. func hasImportedPackage(dir string) bool {
  359. if isRegularFile(filepath.Join(dir, "appins.json")) {
  360. return true
  361. }
  362. entries, err := os.ReadDir(dir)
  363. if err != nil {
  364. return false
  365. }
  366. for _, entry := range entries {
  367. if entry.IsDir() {
  368. continue
  369. }
  370. if strings.HasSuffix(strings.ToLower(entry.Name()), ".tar.gz") {
  371. return true
  372. }
  373. }
  374. return false
  375. }
  376. func writeFileAtomic(name string, data []byte, perm os.FileMode) error {
  377. tmp := name + ".tmp"
  378. defer os.Remove(tmp)
  379. f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, perm)
  380. if err != nil {
  381. return err
  382. }
  383. if _, err := f.Write(data); err != nil {
  384. f.Close()
  385. return err
  386. }
  387. if err := f.Sync(); err != nil {
  388. f.Close()
  389. return err
  390. }
  391. if err := f.Close(); err != nil {
  392. return err
  393. }
  394. return os.Rename(tmp, name)
  395. }
  396. func extractTarGz(src string, dst string) error {
  397. f, err := os.Open(src)
  398. if err != nil {
  399. return err
  400. }
  401. defer f.Close()
  402. gz, err := gzip.NewReader(f)
  403. if err != nil {
  404. return err
  405. }
  406. defer gz.Close()
  407. tr := tar.NewReader(gz)
  408. root := filepath.Clean(dst) + string(os.PathSeparator)
  409. for {
  410. header, err := tr.Next()
  411. if err == io.EOF {
  412. break
  413. }
  414. if err != nil {
  415. return err
  416. }
  417. name := filepath.Join(dst, header.Name)
  418. name = filepath.Clean(name)
  419. if !strings.HasPrefix(name+string(os.PathSeparator), root) {
  420. return fmt.Errorf("invalid path: %s", header.Name)
  421. }
  422. switch header.Typeflag {
  423. case tar.TypeDir:
  424. if err := os.MkdirAll(name, 0755); err != nil {
  425. return err
  426. }
  427. case tar.TypeReg:
  428. if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil {
  429. return err
  430. }
  431. out, err := os.OpenFile(
  432. name,
  433. os.O_CREATE|os.O_WRONLY|os.O_TRUNC,
  434. os.FileMode(header.Mode),
  435. )
  436. if err != nil {
  437. return err
  438. }
  439. _, err = io.Copy(out, tr)
  440. out.Close()
  441. if err != nil {
  442. return err
  443. }
  444. default:
  445. return fmt.Errorf("unsupported tar entry: %s", header.Name)
  446. }
  447. }
  448. return nil
  449. }
  450. func createUserAppService(app AppInfo, installDir string) error {
  451. execFile := filepath.Join(installDir, app.Executable)
  452. libPaths := ""
  453. if len(app.LibPaths) > 0 {
  454. paths := make([]string, 0, len(app.LibPaths))
  455. for _, p := range app.LibPaths {
  456. paths = append(paths, filepath.Join(installDir, p))
  457. }
  458. libPaths = strings.Join(paths, ":")
  459. }
  460. content := fmt.Sprintf(`[Unit]
  461. Description=%s Service
  462. After=yfkj-networkd.service
  463. Wants=yfkj-networkd.service
  464. [Service]
  465. Environment="PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin"
  466. Environment="LD_LIBRARY_PATH=%s"
  467. WorkingDirectory=%s
  468. ExecStart=%s
  469. Restart=always
  470. RestartSec=5
  471. StandardOutput=journal
  472. StandardError=journal
  473. [Install]
  474. WantedBy=multi-user.target
  475. `,
  476. app.Name,
  477. libPaths,
  478. installDir,
  479. execFile,
  480. )
  481. return os.WriteFile(userAppService, []byte(content), 0644)
  482. }
  483. func systemctl(args ...string) error {
  484. out, err := exec.Command("systemctl", args...).CombinedOutput()
  485. if err != nil {
  486. return fmt.Errorf("systemctl %v failed: %v %s", args, err, string(out))
  487. }
  488. return nil
  489. }
  490. func systemctlIgnoreError(args ...string) {
  491. _ = exec.Command("systemctl", args...).Run()
  492. }