web_handler.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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 sshdStatusHandler(w http.ResponseWriter, r *http.Request) {
  70. if r.Method != http.MethodGet {
  71. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  72. return
  73. }
  74. status := noValue
  75. cmd := exec.Command("systemctl", "is-active", "yfkj-sshd-mqtt-bridge.service")
  76. if out, err := cmd.Output(); err == nil {
  77. if strings.TrimSpace(string(out)) == "active" {
  78. status = "🟢 YFKJ-SSHD"
  79. }
  80. }
  81. w.Header().Set("Content-Type", "application/json")
  82. json.NewEncoder(w).Encode(map[string]string{"status": status})
  83. }
  84. func (ui *WebUI) rootHandler(w http.ResponseWriter, r *http.Request) {
  85. path := r.URL.Path
  86. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  87. w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
  88. w.Header().Set("Pragma", "no-cache")
  89. w.Header().Set("Expires", "0")
  90. // 1, 未登录时, 只能看登录页
  91. if !checkSession(r) {
  92. data, err := fs.ReadFile(ui.fs, "login.html")
  93. if err != nil {
  94. http.NotFound(w, r)
  95. } else {
  96. w.Write(data)
  97. }
  98. return
  99. }
  100. // 2, 登录成功, 展示应用首页
  101. if path == "/" {
  102. data, err := fs.ReadFile(ui.fs, "app.html")
  103. if err != nil {
  104. http.NotFound(w, r)
  105. } else {
  106. w.Write(data)
  107. }
  108. return
  109. }
  110. // 3, 在网站内跳转其它功能页
  111. if strings.HasPrefix(path, "/pages/") { // path 形如 "/pages/page1.html"
  112. data, err := fs.ReadFile(ui.fs, path[1:])
  113. if err != nil {
  114. http.NotFound(w, r)
  115. } else {
  116. w.Write(data)
  117. }
  118. return
  119. }
  120. // 4, 访问其它不认识的页面时
  121. http.NotFound(w, r)
  122. }
  123. func serviceLogHandler(w http.ResponseWriter, r *http.Request) {
  124. unit := r.URL.Query().Get("unit")
  125. if unit == "" {
  126. http.Error(w, "missing unit",
  127. http.StatusBadRequest)
  128. return
  129. }
  130. w.Header().Set("Content-Type", "text/event-stream")
  131. w.Header().Set("Cache-Control", "no-cache")
  132. w.Header().Set("Connection", "keep-alive")
  133. w.Header().Set("X-Accel-Buffering", "no")
  134. flusher, ok := w.(http.Flusher)
  135. if !ok {
  136. http.Error(w, "not supported",
  137. http.StatusInternalServerError)
  138. return
  139. }
  140. cmd := exec.Command(
  141. "journalctl",
  142. "-f",
  143. "-u",
  144. unit,
  145. "-n",
  146. "10",
  147. "--no-pager",
  148. "-q",
  149. "-o",
  150. "short-iso",
  151. )
  152. stdout, err := cmd.StdoutPipe()
  153. if err != nil {
  154. http.Error(w, err.Error(), http.StatusInternalServerError)
  155. return
  156. }
  157. if err := cmd.Start(); err != nil {
  158. http.Error(w, err.Error(), http.StatusInternalServerError)
  159. return
  160. }
  161. defer func() {
  162. if cmd.Process != nil {
  163. cmd.Process.Kill()
  164. }
  165. cmd.Wait()
  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. out, err := exec.Command("sh", "-c", cmd).CombinedOutput()
  182. if err != nil {
  183. http.Error(w, err.Error()+"\n"+string(out), http.StatusInternalServerError)
  184. return
  185. }
  186. w.Write(out)
  187. }
  188. func netInterfaces(w http.ResponseWriter, r *http.Request) {
  189. runShellAndWrite(w, "ifconfig")
  190. }
  191. func netRoutes(w http.ResponseWriter, r *http.Request) {
  192. runShellAndWrite(w, "route -n")
  193. }
  194. func netDNS(w http.ResponseWriter, r *http.Request) {
  195. runShellAndWrite(w, "cat /etc/resolv.conf")
  196. }
  197. func callRPCResult(ctx context.Context, port int, method string, params any, result any) error {
  198. client, err := jsonrpc2.NewRPCClient(fmt.Sprintf("http://127.0.0.1:%d/rpc", port))
  199. if err != nil {
  200. return err
  201. }
  202. resp, err := client.Call(ctx, method, params)
  203. if err != nil {
  204. return err
  205. }
  206. return json.Unmarshal(resp.Result, result)
  207. }
  208. func callRPCResponse(w http.ResponseWriter, r *http.Request, port int, method string, params any) {
  209. client, err := jsonrpc2.NewRPCClient(fmt.Sprintf("http://127.0.0.1:%d/rpc", port))
  210. if err != nil {
  211. http.Error(w, err.Error(), http.StatusInternalServerError)
  212. return
  213. }
  214. resp, err := client.Call(r.Context(), method, params)
  215. if err != nil {
  216. http.Error(w, err.Error(), http.StatusInternalServerError)
  217. return
  218. }
  219. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  220. json.NewEncoder(w).Encode(resp.Result)
  221. }
  222. func serviceLogLevel(w http.ResponseWriter, r *http.Request, port int) {
  223. switch r.Method {
  224. case http.MethodGet:
  225. callRPCResponse(w, r, port, "basic.getLogLevel", nil)
  226. case http.MethodPost:
  227. var req struct {
  228. Level string `json:"level"`
  229. }
  230. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  231. http.Error(w, err.Error(), http.StatusBadRequest)
  232. return
  233. }
  234. callRPCResponse(w, r, port, "basic.setLogLevel", map[string]string{"log_level": req.Level})
  235. default:
  236. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  237. }
  238. }
  239. func serviceLogLevelHandler(port int) http.HandlerFunc {
  240. return func(w http.ResponseWriter, r *http.Request) {
  241. serviceLogLevel(w, r, port)
  242. }
  243. }