web_handler.go 12 KB

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