web_handler.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. package main
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "fmt"
  6. "io/fs"
  7. "net/http"
  8. "os"
  9. "os/exec"
  10. "strings"
  11. "hnyfkj.com.cn/rtu/linux/utils/jsonrpc2"
  12. )
  13. type LoginReq struct {
  14. Username string `json:"username"`
  15. Password string `json:"password"`
  16. }
  17. type LoginResp struct {
  18. Success bool `json:"success"`
  19. }
  20. func loginHandler(w http.ResponseWriter, r *http.Request) {
  21. if r.Method != http.MethodPost {
  22. w.WriteHeader(http.StatusMethodNotAllowed)
  23. return
  24. }
  25. var req LoginReq
  26. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  27. w.WriteHeader(http.StatusBadRequest)
  28. return
  29. }
  30. ok := req.Username == "admin" && req.Password == "admin123456"
  31. if ok {
  32. sessionID := createSession()
  33. addSession(sessionID)
  34. http.SetCookie(w, &http.Cookie{
  35. Name: "session_id",
  36. Value: sessionID,
  37. Path: "/",
  38. HttpOnly: true,
  39. SameSite: http.SameSiteStrictMode,
  40. })
  41. }
  42. w.Header().Set("Content-Type", "application/json")
  43. json.NewEncoder(w).Encode(LoginResp{Success: ok})
  44. }
  45. func logoutHandler(w http.ResponseWriter, r *http.Request) {
  46. if cookie, err := r.Cookie("session_id"); err == nil {
  47. sessionMu.Lock()
  48. delete(sessions, cookie.Value)
  49. sessionMu.Unlock()
  50. }
  51. http.SetCookie(w, &http.Cookie{
  52. Name: "session_id",
  53. Value: "",
  54. Path: "/",
  55. MaxAge: -1,
  56. })
  57. http.Redirect(w, r, "/", http.StatusFound)
  58. }
  59. func getIMEIHandler(w http.ResponseWriter, r *http.Request) {
  60. data, _ := os.ReadFile("/var/device_imei.txt")
  61. w.Write(data)
  62. }
  63. func (ui *WebUI) rootHandler(w http.ResponseWriter, r *http.Request) {
  64. path := r.URL.Path
  65. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  66. w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
  67. w.Header().Set("Pragma", "no-cache")
  68. w.Header().Set("Expires", "0")
  69. // 1, 未登录时, 只能看登录页
  70. if !checkSession(r) {
  71. data, err := fs.ReadFile(ui.fs, "login.html")
  72. if err != nil {
  73. http.NotFound(w, r)
  74. } else {
  75. w.Write(data)
  76. }
  77. return
  78. }
  79. // 2, 登录成功, 展示应用首页
  80. if path == "/" {
  81. data, err := fs.ReadFile(ui.fs, "app.html")
  82. if err != nil {
  83. http.NotFound(w, r)
  84. } else {
  85. w.Write(data)
  86. }
  87. return
  88. }
  89. // 3, 在网站内跳转其它功能页
  90. if strings.HasPrefix(path, "/pages/") { // path 形如 "/pages/page1.html"
  91. data, err := fs.ReadFile(ui.fs, path[1:])
  92. if err != nil {
  93. http.NotFound(w, r)
  94. } else {
  95. w.Write(data)
  96. }
  97. return
  98. }
  99. // 4, 访问其它不认识的页面时
  100. http.NotFound(w, r)
  101. }
  102. func serviceLogHandler(w http.ResponseWriter, r *http.Request) {
  103. unit := r.URL.Query().Get("unit")
  104. if unit == "" {
  105. http.Error(w, "missing unit",
  106. http.StatusBadRequest)
  107. return
  108. }
  109. w.Header().Set("Content-Type", "text/event-stream")
  110. w.Header().Set("Cache-Control", "no-cache")
  111. w.Header().Set("Connection", "keep-alive")
  112. w.Header().Set("X-Accel-Buffering", "no")
  113. flusher, ok := w.(http.Flusher)
  114. if !ok {
  115. http.Error(w, "not supported",
  116. http.StatusInternalServerError)
  117. return
  118. }
  119. cmd := exec.Command(
  120. "journalctl",
  121. "-f",
  122. "-u",
  123. unit,
  124. "-n",
  125. "10",
  126. "--no-pager",
  127. "-q",
  128. "-o",
  129. "short-iso",
  130. )
  131. stdout, err := cmd.StdoutPipe()
  132. if err != nil {
  133. http.Error(w, err.Error(), http.StatusInternalServerError)
  134. return
  135. }
  136. if err := cmd.Start(); err != nil {
  137. http.Error(w, err.Error(), http.StatusInternalServerError)
  138. return
  139. }
  140. defer func() {
  141. if cmd.Process != nil {
  142. cmd.Process.Kill()
  143. }
  144. cmd.Wait()
  145. }()
  146. scanner := bufio.NewScanner(stdout)
  147. for scanner.Scan() {
  148. select {
  149. case <-r.Context().Done():
  150. return
  151. default:
  152. }
  153. if _, err := fmt.Fprintf(w, "data: %s\n\n", scanner.Text()); err != nil {
  154. return
  155. }
  156. flusher.Flush()
  157. }
  158. }
  159. func runShellAndWrite(w http.ResponseWriter, cmd string) {
  160. out, err := exec.Command("sh", "-c", cmd).CombinedOutput()
  161. if err != nil {
  162. http.Error(w, err.Error()+"\n"+string(out), http.StatusInternalServerError)
  163. return
  164. }
  165. w.Write(out)
  166. }
  167. func netInterfaces(w http.ResponseWriter, r *http.Request) {
  168. runShellAndWrite(w, "ifconfig")
  169. }
  170. func netRoutes(w http.ResponseWriter, r *http.Request) {
  171. runShellAndWrite(w, "route -n")
  172. }
  173. func netDNS(w http.ResponseWriter, r *http.Request) {
  174. runShellAndWrite(w, "cat /etc/resolv.conf")
  175. }
  176. func callLocalRPC(w http.ResponseWriter, r *http.Request, port int, method string, params any) {
  177. client, err := jsonrpc2.NewRPCClient(fmt.Sprintf("http://127.0.0.1:%d/rpc", port))
  178. if err != nil {
  179. http.Error(w, err.Error(), http.StatusInternalServerError)
  180. return
  181. }
  182. resp, err := client.Call(r.Context(), method, params)
  183. if err != nil {
  184. http.Error(w, err.Error(), http.StatusInternalServerError)
  185. return
  186. }
  187. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  188. json.NewEncoder(w).Encode(resp.Result)
  189. }
  190. func serviceLogLevel(w http.ResponseWriter, r *http.Request, port int) {
  191. switch r.Method {
  192. case http.MethodGet:
  193. callLocalRPC(w, r, port, "basic.getLogLevel", nil)
  194. case http.MethodPost:
  195. var req struct {
  196. Level string `json:"level"`
  197. }
  198. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  199. http.Error(w, err.Error(), http.StatusBadRequest)
  200. return
  201. }
  202. callLocalRPC(w, r, port, "basic.setLogLevel", map[string]string{"log_level": req.Level})
  203. default:
  204. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  205. }
  206. }
  207. func serviceLogLevelHandler(port int) http.HandlerFunc {
  208. return func(w http.ResponseWriter, r *http.Request) {
  209. serviceLogLevel(w, r, port)
  210. }
  211. }