web_handler.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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", http.StatusBadRequest)
  126. return
  127. }
  128. w.Header().Set("Content-Type", "text/event-stream")
  129. w.Header().Set("Cache-Control", "no-cache")
  130. w.Header().Set("Connection", "keep-alive")
  131. w.Header().Set("X-Accel-Buffering", "no")
  132. flusher, ok := w.(http.Flusher)
  133. if !ok {
  134. http.Error(w, "not supported", http.StatusInternalServerError)
  135. return
  136. }
  137. var cmd *exec.Cmd
  138. if file, ok := logFiles[unit]; ok {
  139. cmd = exec.Command(
  140. "tail",
  141. "-F",
  142. "-n",
  143. "10",
  144. "--",
  145. file,
  146. )
  147. } else {
  148. cmd = exec.Command(
  149. "journalctl",
  150. "-f",
  151. "-u",
  152. unit,
  153. "-n",
  154. "10",
  155. "--no-pager",
  156. "-q",
  157. "-o",
  158. "short-iso",
  159. )
  160. }
  161. stdout, err := cmd.StdoutPipe()
  162. if err != nil {
  163. http.Error(w, err.Error(), http.StatusInternalServerError)
  164. return
  165. }
  166. if err := cmd.Start(); err != nil {
  167. http.Error(w, err.Error(), http.StatusInternalServerError)
  168. return
  169. }
  170. id := time.Now().UnixNano()
  171. if true {
  172. baseapp.Logger.Debugf("[服务日志流启动] id=%d unit=%s", id, unit)
  173. }
  174. defer func() {
  175. if cmd.Process != nil {
  176. cmd.Process.Kill()
  177. }
  178. cmd.Wait()
  179. baseapp.Logger.Debugf("[服务日志流关闭] id=%d unit=%s", id, unit)
  180. }()
  181. lines := make(chan string, 100)
  182. go func() {
  183. scanner := bufio.NewScanner(stdout)
  184. scanner.Buffer(make([]byte, 1024), 1024*1024)
  185. for scanner.Scan() {
  186. lines <- scanner.Text()
  187. }
  188. close(lines)
  189. }()
  190. for {
  191. select {
  192. case <-r.Context().Done():
  193. return
  194. case line, ok := <-lines:
  195. if !ok {
  196. return
  197. }
  198. if _, err := fmt.Fprintf(w, "data: %s\n\n", line); err != nil {
  199. return
  200. }
  201. flusher.Flush()
  202. }
  203. }
  204. }
  205. func runShellAndWrite(w http.ResponseWriter, cmd string) {
  206. baseapp.Logger.Debugf("[执行命令] %s", cmd)
  207. out, err := exec.Command("sh", "-c", cmd).CombinedOutput()
  208. if err != nil {
  209. baseapp.Logger.Errorf("[命令失败] %s err=%v", cmd, err)
  210. http.Error(w, err.Error()+"\n"+string(out),
  211. http.StatusInternalServerError)
  212. return
  213. }
  214. w.Write(out)
  215. }
  216. func netInterfaces(w http.ResponseWriter, r *http.Request) {
  217. runShellAndWrite(w, "ifconfig")
  218. }
  219. func netRoutes(w http.ResponseWriter, r *http.Request) {
  220. runShellAndWrite(w, "route -n")
  221. }
  222. func netDNS(w http.ResponseWriter, r *http.Request) {
  223. runShellAndWrite(w, "cat /etc/resolv.conf")
  224. }
  225. func callRPCResult(ctx context.Context, port int, method string, params any, result any) error {
  226. url := fmt.Sprintf("http://127.0.0.1:%d/rpc", port)
  227. req, _ := json.Marshal(params)
  228. baseapp.Logger.Debugf("[接收RPC请求] %s %s params=%s\n", url, method, string(req))
  229. client, err := jsonrpc2.NewRPCClient(url)
  230. if err != nil {
  231. return err
  232. }
  233. resp, err := client.Call(ctx, method, params)
  234. if err != nil {
  235. return err
  236. }
  237. baseapp.Logger.Debugf("[发送RPC应答] %s result=%s err=%v\n", method, string(resp.Result), resp.Error)
  238. return json.Unmarshal(resp.Result, result)
  239. }
  240. func callRPCResponse(w http.ResponseWriter, r *http.Request, port int, method string, params any) {
  241. url := fmt.Sprintf("http://127.0.0.1:%d/rpc", port)
  242. req, _ := json.Marshal(params)
  243. baseapp.Logger.Debugf("[接收RPC请求] %s %s params=%s\n", url, method, string(req))
  244. client, err := jsonrpc2.NewRPCClient(url)
  245. if err != nil {
  246. http.Error(w, err.Error(), http.StatusInternalServerError)
  247. return
  248. }
  249. resp, err := client.Call(r.Context(), method, params)
  250. if err != nil {
  251. http.Error(w, err.Error(), http.StatusInternalServerError)
  252. return
  253. }
  254. baseapp.Logger.Debugf("[发送RPC应答] %s result=%s err=%v\n", method, string(resp.Result), resp.Error)
  255. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  256. json.NewEncoder(w).Encode(resp.Result)
  257. }
  258. func serviceLogLevel(w http.ResponseWriter, r *http.Request, port int) {
  259. switch r.Method {
  260. case http.MethodGet:
  261. callRPCResponse(w, r, port, "basic.getLogLevel", nil)
  262. case http.MethodPost:
  263. var req struct {
  264. Level string `json:"level"`
  265. }
  266. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  267. http.Error(w, err.Error(), http.StatusBadRequest)
  268. return
  269. }
  270. callRPCResponse(w, r, port, "basic.setLogLevel", map[string]string{"log_level": req.Level})
  271. default:
  272. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  273. }
  274. }
  275. func serviceLogLevelHandler(port int) http.HandlerFunc {
  276. return func(w http.ResponseWriter, r *http.Request) {
  277. serviceLogLevel(w, r, port)
  278. }
  279. }
  280. type SystemdServiceStatus struct {
  281. Loaded bool
  282. Active bool
  283. Running bool
  284. Raw string
  285. }
  286. func serviceStatus(name string) (SystemdServiceStatus, error) {
  287. var st SystemdServiceStatus
  288. out, err := exec.Command("systemctl", "show", name,
  289. "-p", "LoadState",
  290. "-p", "ActiveState",
  291. "-p", "SubState",
  292. ).Output()
  293. if err != nil {
  294. return st, err
  295. }
  296. s := string(out)
  297. st.Raw = s
  298. st.Loaded = strings.Contains(s, "LoadState=loaded")
  299. st.Active = strings.Contains(s, "ActiveState=active")
  300. st.Running = st.Active && strings.Contains(s, "SubState=running")
  301. return st, nil
  302. }