web_handler.go 5.8 KB

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