web_handler.go 11 KB

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