web_handler.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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/utils/jsonrpc2"
  14. )
  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, _ := os.ReadFile("/var/device_imei.txt")
  63. w.Write(data)
  64. }
  65. func (ui *WebUI) rootHandler(w http.ResponseWriter, r *http.Request) {
  66. path := r.URL.Path
  67. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  68. w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
  69. w.Header().Set("Pragma", "no-cache")
  70. w.Header().Set("Expires", "0")
  71. // 1, 未登录时, 只能看登录页
  72. if !checkSession(r) {
  73. data, err := fs.ReadFile(ui.fs, "login.html")
  74. if err != nil {
  75. http.NotFound(w, r)
  76. } else {
  77. w.Write(data)
  78. }
  79. return
  80. }
  81. // 2, 登录成功, 展示应用首页
  82. if path == "/" {
  83. data, err := fs.ReadFile(ui.fs, "app.html")
  84. if err != nil {
  85. http.NotFound(w, r)
  86. } else {
  87. w.Write(data)
  88. }
  89. return
  90. }
  91. // 3, 在网站内跳转其它功能页
  92. if strings.HasPrefix(path, "/pages/") { // path 形如 "/pages/page1.html"
  93. data, err := fs.ReadFile(ui.fs, path[1:])
  94. if err != nil {
  95. http.NotFound(w, r)
  96. } else {
  97. w.Write(data)
  98. }
  99. return
  100. }
  101. // 4, 访问其它不认识的页面时
  102. http.NotFound(w, r)
  103. }
  104. func serviceLogHandler(w http.ResponseWriter, r *http.Request) {
  105. unit := r.URL.Query().Get("unit")
  106. if unit == "" {
  107. http.Error(w, "missing unit",
  108. http.StatusBadRequest)
  109. return
  110. }
  111. w.Header().Set("Content-Type", "text/event-stream")
  112. w.Header().Set("Cache-Control", "no-cache")
  113. w.Header().Set("Connection", "keep-alive")
  114. w.Header().Set("X-Accel-Buffering", "no")
  115. flusher, ok := w.(http.Flusher)
  116. if !ok {
  117. http.Error(w, "not supported",
  118. http.StatusInternalServerError)
  119. return
  120. }
  121. cmd := exec.Command(
  122. "journalctl",
  123. "-f",
  124. "-u",
  125. unit,
  126. "-n",
  127. "10",
  128. "--no-pager",
  129. "-q",
  130. "-o",
  131. "short-iso",
  132. )
  133. stdout, err := cmd.StdoutPipe()
  134. if err != nil {
  135. http.Error(w, err.Error(), http.StatusInternalServerError)
  136. return
  137. }
  138. if err := cmd.Start(); err != nil {
  139. http.Error(w, err.Error(), http.StatusInternalServerError)
  140. return
  141. }
  142. defer func() {
  143. if cmd.Process != nil {
  144. cmd.Process.Kill()
  145. }
  146. cmd.Wait()
  147. }()
  148. scanner := bufio.NewScanner(stdout)
  149. for scanner.Scan() {
  150. select {
  151. case <-r.Context().Done():
  152. return
  153. default:
  154. }
  155. if _, err := fmt.Fprintf(w, "data: %s\n\n", scanner.Text()); err != nil {
  156. return
  157. }
  158. flusher.Flush()
  159. }
  160. }
  161. func runShellAndWrite(w http.ResponseWriter, cmd string) {
  162. out, err := exec.Command("sh", "-c", cmd).CombinedOutput()
  163. if err != nil {
  164. http.Error(w, err.Error()+"\n"+string(out), http.StatusInternalServerError)
  165. return
  166. }
  167. w.Write(out)
  168. }
  169. func netInterfaces(w http.ResponseWriter, r *http.Request) {
  170. runShellAndWrite(w, "ifconfig")
  171. }
  172. func netRoutes(w http.ResponseWriter, r *http.Request) {
  173. runShellAndWrite(w, "route -n")
  174. }
  175. func netDNS(w http.ResponseWriter, r *http.Request) {
  176. runShellAndWrite(w, "cat /etc/resolv.conf")
  177. }
  178. func callRPCResult(ctx context.Context, port int, method string, params any, result any) error {
  179. client, err := jsonrpc2.NewRPCClient(fmt.Sprintf("http://127.0.0.1:%d/rpc", port))
  180. if err != nil {
  181. return err
  182. }
  183. resp, err := client.Call(ctx, method, params)
  184. if err != nil {
  185. return err
  186. }
  187. return json.Unmarshal(resp.Result, result)
  188. }
  189. func callRPCResponse(w http.ResponseWriter, r *http.Request, port int, method string, params any) {
  190. client, err := jsonrpc2.NewRPCClient(fmt.Sprintf("http://127.0.0.1:%d/rpc", port))
  191. if err != nil {
  192. http.Error(w, err.Error(), http.StatusInternalServerError)
  193. return
  194. }
  195. resp, err := client.Call(r.Context(), method, params)
  196. if err != nil {
  197. http.Error(w, err.Error(), http.StatusInternalServerError)
  198. return
  199. }
  200. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  201. json.NewEncoder(w).Encode(resp.Result)
  202. }
  203. func serviceLogLevel(w http.ResponseWriter, r *http.Request, port int) {
  204. switch r.Method {
  205. case http.MethodGet:
  206. callRPCResponse(w, r, port, "basic.getLogLevel", nil)
  207. case http.MethodPost:
  208. var req struct {
  209. Level string `json:"level"`
  210. }
  211. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  212. http.Error(w, err.Error(), http.StatusBadRequest)
  213. return
  214. }
  215. callRPCResponse(w, r, port, "basic.setLogLevel", map[string]string{"log_level": req.Level})
  216. default:
  217. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  218. }
  219. }
  220. func serviceLogLevelHandler(port int) http.HandlerFunc {
  221. return func(w http.ResponseWriter, r *http.Request) {
  222. serviceLogLevel(w, r, port)
  223. }
  224. }
  225. func DownloadNetworkLog(w http.ResponseWriter, r *http.Request) {
  226. if r.Method != http.MethodGet {
  227. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  228. return
  229. }
  230. filename := fmt.Sprintf("network.log.%s.tar.gz", time.Now().Format("20060102150405"))
  231. tmpFile := fmt.Sprintf("/tmp/%d.tar.gz", time.Now().UnixNano())
  232. defer os.Remove(tmpFile)
  233. cmd := exec.Command(
  234. "tar",
  235. "--warning=no-file-changed",
  236. "-czf",
  237. tmpFile,
  238. "-C",
  239. "/opt/yfkj/networkd.service/log",
  240. ".",
  241. )
  242. out, err := cmd.CombinedOutput()
  243. if err != nil {
  244. if exitErr, ok := err.(*exec.ExitError); !ok || exitErr.ExitCode() != 1 {
  245. http.Error(w, string(out), http.StatusInternalServerError)
  246. return
  247. }
  248. }
  249. w.Header().Set("Content-Type", "application/gzip")
  250. w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
  251. http.ServeFile(w, r, tmpFile)
  252. }
  253. func RestartNetworkService(w http.ResponseWriter, r *http.Request) {
  254. if r.Method != http.MethodPost {
  255. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  256. return
  257. }
  258. cmd := exec.Command("systemctl", "restart", "yfkj-networkd.service")
  259. if out, err := cmd.CombinedOutput(); err != nil {
  260. http.Error(w, string(out)+err.Error(), http.StatusInternalServerError)
  261. return
  262. }
  263. w.Header().Set("Content-Type", "application/json")
  264. w.Write([]byte(`{"status":"ok"}`))
  265. }
  266. func NetworkStatusHandler(w http.ResponseWriter, r *http.Request) {
  267. var modem struct {
  268. ICCID string `json:"iccid"`
  269. RSSI string `json:"rssi"`
  270. }
  271. var net struct {
  272. Status string `json:"net_ok"`
  273. Type string `json:"net_type"`
  274. }
  275. err1 := callRPCResult(r.Context(), 7000, "core.getNetStatus", nil, &net)
  276. err2 := callRPCResult(r.Context(), 7000, "core.getModemInfo", nil, &modem)
  277. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  278. json.NewEncoder(w).Encode(map[string]string{
  279. "var1": map[bool]string{true: "🟢正常", false: "🔴异常"}[err1 == nil || err2 == nil],
  280. "var2": map[bool]string{true: "🟢正常", false: "🔴异常"}[net.Status == "true"],
  281. "var3": net.Type,
  282. "var4": modem.RSSI,
  283. "var5": modem.ICCID,
  284. })
  285. }