web_handler.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. func serviceLogHandler(w http.ResponseWriter, r *http.Request) {
  120. unit := r.URL.Query().Get("unit")
  121. if unit == "" {
  122. http.Error(w, "missing unit",
  123. http.StatusBadRequest)
  124. return
  125. }
  126. w.Header().Set("Content-Type", "text/event-stream")
  127. w.Header().Set("Cache-Control", "no-cache")
  128. w.Header().Set("Connection", "keep-alive")
  129. w.Header().Set("X-Accel-Buffering", "no")
  130. flusher, ok := w.(http.Flusher)
  131. if !ok {
  132. http.Error(w, "not supported",
  133. http.StatusInternalServerError)
  134. return
  135. }
  136. cmd := exec.Command(
  137. "journalctl",
  138. "-f",
  139. "-u",
  140. unit,
  141. "-n",
  142. "10",
  143. "--no-pager",
  144. "-q",
  145. "-o",
  146. "short-iso",
  147. )
  148. stdout, err := cmd.StdoutPipe()
  149. if err != nil {
  150. http.Error(w, err.Error(), http.StatusInternalServerError)
  151. return
  152. }
  153. if err := cmd.Start(); err != nil {
  154. http.Error(w, err.Error(), http.StatusInternalServerError)
  155. return
  156. }
  157. if true {
  158. baseapp.Logger.Debugf("[服务日志流启动] unit=%s", unit)
  159. }
  160. defer func() {
  161. if cmd.Process != nil {
  162. cmd.Process.Kill()
  163. }
  164. cmd.Wait()
  165. baseapp.Logger.Debugf("[服务日志流关闭] unit=%s", unit)
  166. }()
  167. scanner := bufio.NewScanner(stdout)
  168. for scanner.Scan() {
  169. select {
  170. case <-r.Context().Done():
  171. return
  172. default:
  173. }
  174. if _, err := fmt.Fprintf(w, "data: %s\n\n", scanner.Text()); err != nil {
  175. return
  176. }
  177. flusher.Flush()
  178. }
  179. }
  180. func runShellAndWrite(w http.ResponseWriter, cmd string) {
  181. baseapp.Logger.Debugf("[执行命令] %s", cmd)
  182. out, err := exec.Command("sh", "-c", cmd).CombinedOutput()
  183. if err != nil {
  184. baseapp.Logger.Errorf("[命令失败] %s err=%v", cmd, err)
  185. http.Error(w, err.Error()+"\n"+string(out),
  186. http.StatusInternalServerError)
  187. return
  188. }
  189. w.Write(out)
  190. }
  191. func netInterfaces(w http.ResponseWriter, r *http.Request) {
  192. runShellAndWrite(w, "ifconfig")
  193. }
  194. func netRoutes(w http.ResponseWriter, r *http.Request) {
  195. runShellAndWrite(w, "route -n")
  196. }
  197. func netDNS(w http.ResponseWriter, r *http.Request) {
  198. runShellAndWrite(w, "cat /etc/resolv.conf")
  199. }
  200. func callRPCResult(ctx context.Context, port int, method string, params any, result any) error {
  201. url := fmt.Sprintf("http://127.0.0.1:%d/rpc", port)
  202. req, _ := json.Marshal(params)
  203. baseapp.Logger.Debugf("[接收RPC请求] %s %s params=%s\n", url, method, string(req))
  204. client, err := jsonrpc2.NewRPCClient(url)
  205. if err != nil {
  206. baseapp.Logger.Errorf("[执行RPC错误] %s err=%v\n", method, err)
  207. return err
  208. }
  209. resp, err := client.Call(ctx, method, params)
  210. if err != nil {
  211. return err
  212. }
  213. baseapp.Logger.Debugf("[发送RPC应答] %s result=%s\n", method, string(resp.Result))
  214. return json.Unmarshal(resp.Result, result)
  215. }
  216. func callRPCResponse(w http.ResponseWriter, r *http.Request, port int, method string, params any) {
  217. url := fmt.Sprintf("http://127.0.0.1:%d/rpc", port)
  218. req, _ := json.Marshal(params)
  219. baseapp.Logger.Debugf("[接收RPC请求] %s %s params=%s\n", url, method, string(req))
  220. client, err := jsonrpc2.NewRPCClient(url)
  221. if err != nil {
  222. http.Error(w, err.Error(), http.StatusInternalServerError)
  223. return
  224. }
  225. resp, err := client.Call(r.Context(), method, params)
  226. if err != nil {
  227. baseapp.Logger.Errorf("[执行RPC错误] %s err=%v\n", method, err)
  228. http.Error(w, err.Error(), http.StatusInternalServerError)
  229. return
  230. }
  231. baseapp.Logger.Debugf("[发送RPC应答] %s result=%s\n", method, string(resp.Result))
  232. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  233. json.NewEncoder(w).Encode(resp.Result)
  234. }
  235. func serviceLogLevel(w http.ResponseWriter, r *http.Request, port int) {
  236. switch r.Method {
  237. case http.MethodGet:
  238. callRPCResponse(w, r, port, "basic.getLogLevel", nil)
  239. case http.MethodPost:
  240. var req struct {
  241. Level string `json:"level"`
  242. }
  243. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  244. http.Error(w, err.Error(), http.StatusBadRequest)
  245. return
  246. }
  247. callRPCResponse(w, r, port, "basic.setLogLevel", map[string]string{"log_level": req.Level})
  248. default:
  249. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  250. }
  251. }
  252. func serviceLogLevelHandler(port int) http.HandlerFunc {
  253. return func(w http.ResponseWriter, r *http.Request) {
  254. serviceLogLevel(w, r, port)
  255. }
  256. }