web_handler.go 4.0 KB

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