web_handler.go 12 KB

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