web_handler.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. "strings"
  12. "time"
  13. "hnyfkj.com.cn/rtu/linux/baseapp"
  14. "hnyfkj.com.cn/rtu/linux/utils/jsonrpc2"
  15. )
  16. const noValue = "--"
  17. type LoginReq struct {
  18. Username string `json:"username"`
  19. Password string `json:"password"`
  20. }
  21. type LoginResp struct {
  22. Success bool `json:"success"`
  23. }
  24. func loginHandler(w http.ResponseWriter, r *http.Request) {
  25. if r.Method != http.MethodPost {
  26. w.WriteHeader(http.StatusMethodNotAllowed)
  27. return
  28. }
  29. var req LoginReq
  30. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  31. w.WriteHeader(http.StatusBadRequest)
  32. return
  33. }
  34. ok := req.Username == "admin" && req.Password == "admin123456"
  35. if ok {
  36. sessionID := createSession()
  37. addSession(sessionID)
  38. http.SetCookie(w, &http.Cookie{
  39. Name: "session_id",
  40. Value: sessionID,
  41. Path: "/",
  42. HttpOnly: true,
  43. SameSite: http.SameSiteStrictMode,
  44. })
  45. }
  46. w.Header().Set("Content-Type", "application/json")
  47. json.NewEncoder(w).Encode(LoginResp{Success: ok})
  48. }
  49. func logoutHandler(w http.ResponseWriter, r *http.Request) {
  50. if cookie, err := r.Cookie("session_id"); err == nil {
  51. sessionMu.Lock()
  52. delete(sessions, cookie.Value)
  53. sessionMu.Unlock()
  54. }
  55. http.SetCookie(w, &http.Cookie{
  56. Name: "session_id",
  57. Value: "",
  58. Path: "/",
  59. MaxAge: -1,
  60. })
  61. http.Redirect(w, r, "/", http.StatusFound)
  62. }
  63. func getIMEIHandler(w http.ResponseWriter, r *http.Request) {
  64. data, err := os.ReadFile("/var/device_imei.txt")
  65. if err != nil {
  66. w.Write([]byte(noValue))
  67. } else {
  68. w.Write(append([]byte("🆔"), data...))
  69. }
  70. }
  71. func systemRebootHandler(w http.ResponseWriter, r *http.Request) {
  72. json.NewEncoder(w).Encode(map[string]bool{
  73. "ok": true,
  74. })
  75. go func() {
  76. time.Sleep(2 * time.Second)
  77. exec.Command("systemctl", "reboot").Run()
  78. }()
  79. }
  80. func (ui *WebUI) rootHandler(w http.ResponseWriter, r *http.Request) {
  81. path := r.URL.Path
  82. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  83. w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
  84. w.Header().Set("Pragma", "no-cache")
  85. w.Header().Set("Expires", "0")
  86. // 1, 未登录时, 只能看登录页
  87. if !checkSession(r) {
  88. data, err := fs.ReadFile(ui.fs, "login.html")
  89. if err != nil {
  90. http.NotFound(w, r)
  91. } else {
  92. w.Write(data)
  93. }
  94. return
  95. }
  96. // 2, 登录成功, 展示应用首页
  97. if path == "/" {
  98. data, err := fs.ReadFile(ui.fs, "app.html")
  99. if err != nil {
  100. http.NotFound(w, r)
  101. } else {
  102. w.Write(data)
  103. }
  104. return
  105. }
  106. // 3, 在网站内跳转其它功能页
  107. if strings.HasPrefix(path, "/pages/") { // path 形如 "/pages/page1.html"
  108. data, err := fs.ReadFile(ui.fs, path[1:])
  109. if err != nil {
  110. http.NotFound(w, r)
  111. } else {
  112. w.Write(data)
  113. }
  114. return
  115. }
  116. // 4, 访问其它不认识的页面时
  117. http.NotFound(w, r)
  118. }
  119. var logFiles = map[string]string{
  120. "yfkj-camera-capture.service": "/opt/yfkj/camera-capture.service/log/camera-capture.log",
  121. }
  122. func serviceLogHandler(w http.ResponseWriter, r *http.Request) {
  123. unit := r.URL.Query().Get("unit")
  124. if unit == "" {
  125. http.Error(w, "missing unit",
  126. http.StatusBadRequest)
  127. return
  128. }
  129. w.Header().Set("Content-Type", "text/event-stream")
  130. w.Header().Set("Cache-Control", "no-cache")
  131. w.Header().Set("Connection", "keep-alive")
  132. w.Header().Set("X-Accel-Buffering", "no")
  133. flusher, ok := w.(http.Flusher)
  134. if !ok {
  135. http.Error(w, "not supported",
  136. http.StatusInternalServerError)
  137. return
  138. }
  139. var cmd *exec.Cmd
  140. if file, ok := logFiles[unit]; ok {
  141. cmd = exec.Command(
  142. "tail",
  143. "-F",
  144. "-n",
  145. "10",
  146. "--",
  147. file,
  148. )
  149. } else {
  150. cmd = exec.Command(
  151. "journalctl",
  152. "-f",
  153. "-u",
  154. unit,
  155. "-n",
  156. "10",
  157. "--no-pager",
  158. "-q",
  159. "-o",
  160. "short-iso",
  161. )
  162. }
  163. stdout, err := cmd.StdoutPipe()
  164. if err != nil {
  165. http.Error(w, err.Error(), http.StatusInternalServerError)
  166. return
  167. }
  168. if err := cmd.Start(); err != nil {
  169. http.Error(w, err.Error(), http.StatusInternalServerError)
  170. return
  171. }
  172. if true {
  173. baseapp.Logger.Debugf("[服务日志流启动] unit=%s", unit)
  174. }
  175. defer func() {
  176. if cmd.Process != nil {
  177. cmd.Process.Kill()
  178. }
  179. cmd.Wait()
  180. baseapp.Logger.Debugf("[服务日志流关闭] unit=%s", unit)
  181. }()
  182. scanner := bufio.NewScanner(stdout)
  183. for scanner.Scan() {
  184. select {
  185. case <-r.Context().Done():
  186. return
  187. default:
  188. }
  189. if _, err := fmt.Fprintf(w, "data: %s\n\n", scanner.Text()); err != nil {
  190. return
  191. }
  192. flusher.Flush()
  193. }
  194. }
  195. func runShellAndWrite(w http.ResponseWriter, cmd string) {
  196. baseapp.Logger.Debugf("[执行命令] %s", cmd)
  197. out, err := exec.Command("sh", "-c", cmd).CombinedOutput()
  198. if err != nil {
  199. baseapp.Logger.Errorf("[命令失败] %s err=%v", cmd, err)
  200. http.Error(w, err.Error()+"\n"+string(out),
  201. http.StatusInternalServerError)
  202. return
  203. }
  204. w.Write(out)
  205. }
  206. func netInterfaces(w http.ResponseWriter, r *http.Request) {
  207. runShellAndWrite(w, "ifconfig")
  208. }
  209. func netRoutes(w http.ResponseWriter, r *http.Request) {
  210. runShellAndWrite(w, "route -n")
  211. }
  212. func netDNS(w http.ResponseWriter, r *http.Request) {
  213. runShellAndWrite(w, "cat /etc/resolv.conf")
  214. }
  215. func callRPCResult(ctx context.Context, port int, method string, params any, result any) error {
  216. url := fmt.Sprintf("http://127.0.0.1:%d/rpc", port)
  217. req, _ := json.Marshal(params)
  218. baseapp.Logger.Debugf("[接收RPC请求] %s %s params=%s\n", url, method, string(req))
  219. client, err := jsonrpc2.NewRPCClient(url)
  220. if err != nil {
  221. baseapp.Logger.Errorf("[执行RPC错误] %s err=%v\n", method, err)
  222. return err
  223. }
  224. resp, err := client.Call(ctx, method, params)
  225. if err != nil {
  226. return err
  227. }
  228. baseapp.Logger.Debugf("[发送RPC应答] %s result=%s\n", method, string(resp.Result))
  229. return json.Unmarshal(resp.Result, result)
  230. }
  231. func callRPCResponse(w http.ResponseWriter, r *http.Request, port int, method string, params any) {
  232. url := fmt.Sprintf("http://127.0.0.1:%d/rpc", port)
  233. req, _ := json.Marshal(params)
  234. baseapp.Logger.Debugf("[接收RPC请求] %s %s params=%s\n", url, method, string(req))
  235. client, err := jsonrpc2.NewRPCClient(url)
  236. if err != nil {
  237. http.Error(w, err.Error(), http.StatusInternalServerError)
  238. return
  239. }
  240. resp, err := client.Call(r.Context(), method, params)
  241. if err != nil {
  242. baseapp.Logger.Errorf("[执行RPC错误] %s err=%v\n", method, err)
  243. http.Error(w, err.Error(), http.StatusInternalServerError)
  244. return
  245. }
  246. baseapp.Logger.Debugf("[发送RPC应答] %s result=%s\n", method, string(resp.Result))
  247. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  248. json.NewEncoder(w).Encode(resp.Result)
  249. }
  250. func serviceLogLevel(w http.ResponseWriter, r *http.Request, port int) {
  251. switch r.Method {
  252. case http.MethodGet:
  253. callRPCResponse(w, r, port, "basic.getLogLevel", nil)
  254. case http.MethodPost:
  255. var req struct {
  256. Level string `json:"level"`
  257. }
  258. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  259. http.Error(w, err.Error(), http.StatusBadRequest)
  260. return
  261. }
  262. callRPCResponse(w, r, port, "basic.setLogLevel", map[string]string{"log_level": req.Level})
  263. default:
  264. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  265. }
  266. }
  267. func serviceLogLevelHandler(port int) http.HandlerFunc {
  268. return func(w http.ResponseWriter, r *http.Request) {
  269. serviceLogLevel(w, r, port)
  270. }
  271. }
  272. type SystemdServiceStatus struct {
  273. Loaded bool
  274. Active bool
  275. Running bool
  276. Raw string
  277. }
  278. func serviceStatus(name string) (SystemdServiceStatus, error) {
  279. var st SystemdServiceStatus
  280. out, err := exec.Command("systemctl", "show", name,
  281. "-p", "LoadState",
  282. "-p", "ActiveState",
  283. "-p", "SubState",
  284. ).Output()
  285. if err != nil {
  286. return st, err
  287. }
  288. s := string(out)
  289. st.Raw = s
  290. st.Loaded = strings.Contains(s, "LoadState=loaded")
  291. st.Active = strings.Contains(s, "ActiveState=active")
  292. st.Running = st.Active && strings.Contains(s, "SubState=running")
  293. return st, nil
  294. }