web_handler.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. package main
  2. import (
  3. "bufio"
  4. "context"
  5. "crypto/subtle"
  6. "encoding/json"
  7. "fmt"
  8. "io/fs"
  9. "net/http"
  10. "os"
  11. "os/exec"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "hnyfkj.com.cn/rtu/linux/baseapp"
  17. "hnyfkj.com.cn/rtu/linux/utils/jsonrpc2"
  18. )
  19. const noValue = "--"
  20. const authPassword = "yfkj123456"
  21. type LoginReq struct {
  22. Username string `json:"username"`
  23. Password string `json:"password"`
  24. }
  25. type LoginResp struct {
  26. Success bool `json:"success"`
  27. }
  28. func loginHandler(w http.ResponseWriter, r *http.Request) {
  29. if r.Method != http.MethodPost {
  30. w.WriteHeader(http.StatusMethodNotAllowed)
  31. return
  32. }
  33. var req LoginReq
  34. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  35. w.WriteHeader(http.StatusBadRequest)
  36. return
  37. }
  38. ok := req.Username == "admin" && req.Password == "admin123456"
  39. if ok {
  40. sessionID := createSession()
  41. addSession(sessionID)
  42. http.SetCookie(w, &http.Cookie{
  43. Name: "session_id",
  44. Value: sessionID,
  45. Path: "/",
  46. HttpOnly: true,
  47. SameSite: http.SameSiteStrictMode,
  48. })
  49. }
  50. w.Header().Set("Content-Type", "application/json")
  51. json.NewEncoder(w).Encode(LoginResp{Success: ok})
  52. }
  53. func logoutHandler(w http.ResponseWriter, r *http.Request) {
  54. if cookie, err := r.Cookie("session_id"); err == nil {
  55. sessionMu.Lock()
  56. delete(sessions, cookie.Value)
  57. sessionMu.Unlock()
  58. }
  59. http.SetCookie(w, &http.Cookie{
  60. Name: "session_id",
  61. Value: "",
  62. Path: "/",
  63. MaxAge: -1,
  64. })
  65. http.Redirect(w, r, "/", http.StatusFound)
  66. }
  67. func getIMEIHandler(w http.ResponseWriter, r *http.Request) {
  68. data, err := os.ReadFile("/var/device_imei.txt")
  69. if err != nil {
  70. w.Write([]byte(noValue))
  71. } else {
  72. w.Write(data) // 纯数据返回, 展示图标由前端渲染
  73. }
  74. }
  75. func systemRebootHandler(w http.ResponseWriter, r *http.Request) {
  76. json.NewEncoder(w).Encode(map[string]bool{
  77. "ok": true,
  78. })
  79. go func() {
  80. time.Sleep(2 * time.Second)
  81. exec.Command("systemctl", "reboot").Run()
  82. }()
  83. }
  84. func (ui *WebUI) rootHandler(w http.ResponseWriter, r *http.Request) {
  85. path := r.URL.Path
  86. // 0, 浏览器自动请求的站点图标(登录前后都会请求, 放在会话校验之前)
  87. // favicon.ico: 桌面浏览器; apple-touch-icon*: Safari/iOS/部分安卓浏览器自动探测
  88. if path == "/favicon.ico" || path == "/apple-touch-icon.png" ||
  89. path == "/apple-touch-icon-precomposed.png" {
  90. data, err := fs.ReadFile(ui.fs, "favicon.ico")
  91. if err != nil {
  92. http.NotFound(w, r)
  93. return
  94. }
  95. w.Header().Set("Content-Type", "image/x-icon")
  96. w.Header().Set("Cache-Control", "public, max-age=86400")
  97. w.Write(data)
  98. return
  99. }
  100. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  101. w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
  102. w.Header().Set("Pragma", "no-cache")
  103. w.Header().Set("Expires", "0")
  104. // 1, 未登录时, 只能看登录页
  105. if !checkSession(r) {
  106. data, err := fs.ReadFile(ui.fs, "login.html")
  107. if err != nil {
  108. http.NotFound(w, r)
  109. } else {
  110. w.Write([]byte(strings.ReplaceAll(string(data), "{{V}}", Version)))
  111. }
  112. return
  113. }
  114. // 2, 登录成功, 展示应用首页
  115. if path == "/" {
  116. data, err := fs.ReadFile(ui.fs, "app.html")
  117. if err != nil {
  118. http.NotFound(w, r)
  119. } else {
  120. w.Write([]byte(strings.ReplaceAll(string(data), "{{V}}", Version)))
  121. }
  122. return
  123. }
  124. // 3, 在网站内跳转其它功能页
  125. if strings.HasPrefix(path, "/pages/") { // path 形如 "/pages/page1.html"
  126. data, err := fs.ReadFile(ui.fs, path[1:])
  127. if err != nil {
  128. http.NotFound(w, r)
  129. } else {
  130. w.Write(data)
  131. }
  132. return
  133. }
  134. // 4, 访问其它不认识的页面时
  135. http.NotFound(w, r)
  136. }
  137. var logCmds sync.Map /* pid -> *exec.Cmd, 用于管理日志流进程, 以便在前端关闭日志流时, 后端可以
  138. 关闭对应的日志流进程, 解决frpc代理后, sse连接断开时, 日志流进程无法关闭的问题, 占用PID资源 */
  139. var logFiles = map[string]string{
  140. "yfkj-camera-capture.service": "/opt/yfkj/camera-capture.service/log/camera-capture.log",
  141. }
  142. func serviceLogHandler(w http.ResponseWriter, r *http.Request) {
  143. unit := r.URL.Query().Get("unit")
  144. if unit == "" {
  145. http.Error(w, "missing unit", http.StatusBadRequest)
  146. return
  147. }
  148. w.Header().Set("Content-Type", "text/event-stream")
  149. w.Header().Set("Cache-Control", "no-cache")
  150. w.Header().Set("Connection", "keep-alive")
  151. w.Header().Set("X-Accel-Buffering", "no")
  152. flusher, ok := w.(http.Flusher)
  153. if !ok {
  154. http.Error(w, "not supported", http.StatusInternalServerError)
  155. return
  156. }
  157. var cmd *exec.Cmd
  158. if file, ok := logFiles[unit]; ok {
  159. cmd = exec.Command(
  160. "tail",
  161. "-F",
  162. "-n",
  163. "10",
  164. "--",
  165. file,
  166. )
  167. } else {
  168. cmd = exec.Command(
  169. "journalctl",
  170. "-f",
  171. "-u",
  172. unit,
  173. "-n",
  174. "10",
  175. "--no-pager",
  176. "-q",
  177. "-o",
  178. "short-iso",
  179. )
  180. }
  181. stdout, err := cmd.StdoutPipe()
  182. if err != nil {
  183. http.Error(w, err.Error(), http.StatusInternalServerError)
  184. return
  185. }
  186. if err := cmd.Start(); err != nil {
  187. http.Error(w, err.Error(), http.StatusInternalServerError)
  188. return
  189. }
  190. pid := cmd.Process.Pid
  191. logCmds.Store(pid, cmd)
  192. id := time.Now().UnixNano()
  193. if true {
  194. baseapp.Logger.Tracef("[服务日志流启动] id=%d unit=%s", id, unit)
  195. }
  196. fmt.Fprintf(w, "event: pid\ndata: %d\n\n", pid)
  197. flusher.Flush() // 发送PID给前端, 让前端在关闭日志流时, 可以通知后端关闭对应的日志流进程
  198. defer func() {
  199. logCmds.Delete(pid)
  200. if cmd.Process != nil {
  201. err := cmd.Process.Kill()
  202. baseapp.Logger.Tracef("[journalctl kill] pid=%d err=%v", cmd.Process.Pid, err)
  203. }
  204. cmd.Wait()
  205. baseapp.Logger.Tracef("[服务日志流关闭] id=%d unit=%s", id, unit)
  206. }()
  207. lines := make(chan string, 100)
  208. go func() {
  209. defer close(lines)
  210. scanner := bufio.NewScanner(stdout)
  211. scanner.Buffer(make([]byte, 1024), 1024*1024)
  212. for scanner.Scan() {
  213. select {
  214. case lines <- scanner.Text():
  215. case <-r.Context().Done():
  216. return
  217. }
  218. }
  219. _ = scanner.Err()
  220. }()
  221. for {
  222. select {
  223. case <-r.Context().Done():
  224. return
  225. case line, ok := <-lines:
  226. if !ok {
  227. return
  228. }
  229. if _, err := fmt.Fprintf(w, "data: %s\n\n", line); err != nil { // 实时推送日志
  230. return
  231. }
  232. flusher.Flush()
  233. }
  234. }
  235. }
  236. func serviceLogCloseHandler(w http.ResponseWriter, r *http.Request) {
  237. pid, err := strconv.Atoi(r.URL.Query().Get("pid"))
  238. if err != nil || pid <= 0 {
  239. http.Error(w, "invalid pid", http.StatusBadRequest)
  240. return
  241. }
  242. v, ok := logCmds.Load(pid)
  243. if !ok {
  244. http.Error(w, "pid not found", http.StatusNotFound)
  245. return
  246. }
  247. cmd := v.(*exec.Cmd)
  248. if cmd.Process == nil {
  249. logCmds.Delete(pid)
  250. return
  251. }
  252. data, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid))
  253. if err != nil {
  254. http.Error(w, "read cmdline failed", http.StatusInternalServerError)
  255. return
  256. }
  257. cmdline := strings.ReplaceAll(string(data), "\x00", " ")
  258. if !strings.Contains(cmdline, "journalctl") && !strings.Contains(cmdline, "tail") {
  259. http.Error(w, "not log process", http.StatusBadRequest) // 只允许关闭日志流进程, 防止误杀其它进程
  260. return
  261. }
  262. logCmds.Delete(pid)
  263. err = cmd.Process.Kill()
  264. baseapp.Logger.Tracef("[服务日志流关闭] pid=%d cmd=%s err=%v", pid, cmdline, err)
  265. if err != nil {
  266. http.Error(w, err.Error(), http.StatusInternalServerError)
  267. return
  268. }
  269. w.WriteHeader(http.StatusOK)
  270. }
  271. func runShellAndWrite(w http.ResponseWriter, cmd string) {
  272. baseapp.Logger.Tracef("[执行命令] %s", cmd)
  273. out, err := exec.Command("sh", "-c", cmd).CombinedOutput()
  274. if err != nil {
  275. baseapp.Logger.Errorf("[命令失败] %s err=%v", cmd, err)
  276. http.Error(w, err.Error()+"\n"+string(out),
  277. http.StatusInternalServerError)
  278. return
  279. }
  280. w.Write(out)
  281. }
  282. func netInterfaces(w http.ResponseWriter, r *http.Request) {
  283. runShellAndWrite(w, "ifconfig")
  284. }
  285. func netRoutes(w http.ResponseWriter, r *http.Request) {
  286. runShellAndWrite(w, "route -n")
  287. }
  288. func netDNS(w http.ResponseWriter, r *http.Request) {
  289. runShellAndWrite(w, "cat /etc/resolv.conf")
  290. }
  291. func callRPCResult(ctx context.Context, port int, method string, params any, result any) error {
  292. url := fmt.Sprintf("http://127.0.0.1:%d/rpc", port)
  293. req, _ := json.Marshal(params)
  294. baseapp.Logger.Tracef("[接收RPC请求] %s %s params=%s\n", url, method, string(req))
  295. client, err := jsonrpc2.NewRPCClient(url)
  296. if err != nil {
  297. return err
  298. }
  299. resp, err := client.Call(ctx, method, params)
  300. if err != nil {
  301. return err
  302. }
  303. baseapp.Logger.Tracef("[发送RPC应答] %s result=%s err=%v\n", method, string(resp.Result), resp.Error)
  304. if resp.Error != nil {
  305. return fmt.Errorf("%s", resp.Error.Message)
  306. }
  307. if result == nil {
  308. return nil
  309. }
  310. return json.Unmarshal(resp.Result, result)
  311. }
  312. func callRPCResponse(w http.ResponseWriter, r *http.Request, port int, method string, params any) {
  313. url := fmt.Sprintf("http://127.0.0.1:%d/rpc", port)
  314. req, _ := json.Marshal(params)
  315. baseapp.Logger.Tracef("[接收RPC请求] %s %s params=%s\n", url, method, string(req))
  316. client, err := jsonrpc2.NewRPCClient(url)
  317. if err != nil {
  318. http.Error(w, err.Error(), http.StatusInternalServerError)
  319. return
  320. }
  321. resp, err := client.Call(r.Context(), method, params)
  322. if err != nil {
  323. http.Error(w, err.Error(), http.StatusInternalServerError)
  324. return
  325. }
  326. baseapp.Logger.Tracef("[发送RPC应答] %s result=%s err=%v\n", method, string(resp.Result), resp.Error)
  327. if resp.Error != nil {
  328. http.Error(w, resp.Error.Message, http.StatusBadRequest)
  329. return
  330. }
  331. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  332. w.Write(resp.Result)
  333. }
  334. func serviceLogLevel(w http.ResponseWriter, r *http.Request, port int) {
  335. switch r.Method {
  336. case http.MethodGet:
  337. callRPCResponse(w, r, port, "basic.getLogLevel", nil)
  338. case http.MethodPost:
  339. var req struct {
  340. Level string `json:"level"`
  341. }
  342. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  343. http.Error(w, err.Error(), http.StatusBadRequest)
  344. return
  345. }
  346. callRPCResponse(w, r, port, "basic.setLogLevel", map[string]string{"log_level": req.Level})
  347. default:
  348. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  349. }
  350. }
  351. func serviceLogLevelHandler(port int) http.HandlerFunc {
  352. return func(w http.ResponseWriter, r *http.Request) {
  353. serviceLogLevel(w, r, port)
  354. }
  355. }
  356. type SystemdServiceStatus struct {
  357. Loaded bool
  358. Active bool
  359. Running bool
  360. Raw string
  361. }
  362. func serviceStatus(name string) (SystemdServiceStatus, error) {
  363. var st SystemdServiceStatus
  364. out, err := exec.Command("systemctl", "show", name,
  365. "-p", "LoadState",
  366. "-p", "ActiveState",
  367. "-p", "SubState",
  368. ).Output()
  369. if err != nil {
  370. return st, err
  371. }
  372. s := string(out)
  373. st.Raw = s
  374. st.Loaded = strings.Contains(s, "LoadState=loaded")
  375. st.Active = strings.Contains(s, "ActiveState=active")
  376. st.Running = st.Active && strings.Contains(s, "SubState=running")
  377. return st, nil
  378. }
  379. func systemctl(action, name string) error {
  380. var args []string
  381. args = strings.Fields(action)
  382. args = append(args, name)
  383. out, err := exec.Command("systemctl", args...).CombinedOutput()
  384. if err != nil {
  385. return fmt.Errorf("systemctl %v failed: %v %s", args, err, string(out))
  386. }
  387. return nil
  388. }
  389. func serviceControlHandler(w http.ResponseWriter, r *http.Request) {
  390. var req struct {
  391. Name string `json:"name"`
  392. Action string `json:"action"`
  393. Secret string `json:"secret"`
  394. }
  395. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  396. http.Error(w, "参数错误", http.StatusBadRequest)
  397. return
  398. }
  399. if req.Secret != authPassword {
  400. http.Error(w, "密码错误", http.StatusForbidden)
  401. return
  402. }
  403. if req.Action == "stop" && req.Name == "yfkj-frp-client.service" {
  404. go func() {
  405. _ = systemctl(req.Action, req.Name)
  406. }()
  407. json.NewEncoder(w).Encode(map[string]bool{"ok": true})
  408. return
  409. }
  410. if err := systemctl(req.Action, req.Name); err != nil {
  411. http.Error(w, err.Error(), http.StatusInternalServerError)
  412. return
  413. }
  414. json.NewEncoder(w).Encode(map[string]bool{"ok": true})
  415. }
  416. func checkOperationPassword(w http.ResponseWriter, r *http.Request) bool {
  417. password := r.Header.Get("X-Operation-Password")
  418. if subtle.ConstantTimeCompare([]byte(password), []byte(authPassword)) != 1 {
  419. http.Error(w, "操作密码错误", http.StatusUnauthorized)
  420. return false
  421. }
  422. return true
  423. }