web_handler.go 6.4 KB

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