page0_handler.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. package main
  2. import (
  3. "archive/tar"
  4. "compress/gzip"
  5. "crypto/subtle"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "path/filepath"
  14. "sort"
  15. "strings"
  16. "sync"
  17. "time"
  18. )
  19. const (
  20. fileMgrRoot = "/home" // 文件管理根目录/////////
  21. fmUnlockExpire = 30 * time.Minute // 解锁状态有效期/////////
  22. fmUploadMaxSize = 1 << 30 // 单次上传请求文件最大1GB
  23. fmUploadMaxAge = time.Hour // 临时文件超过1小时后清理
  24. )
  25. var (
  26. fmUnlockMu sync.Mutex
  27. fmUnlocks = make(map[string]time.Time)
  28. fmRootUnlocks = make(map[string]bool)
  29. fmUploadSem = make(chan struct{}, 1)
  30. fmDownloadSem = make(chan struct{}, 1)
  31. fmUploadMu sync.Mutex
  32. fmUploadFiles = make(map[string]bool)
  33. )
  34. type fmEntry struct {
  35. Name string `json:"name"`
  36. IsDir bool `json:"isDir"`
  37. Size int64 `json:"size"`
  38. ModTime int64 `json:"modTime"`
  39. }
  40. func fmSessionKey(r *http.Request) string {
  41. c, err := r.Cookie("session_id")
  42. if err != nil {
  43. return ""
  44. }
  45. return c.Value
  46. }
  47. func fmIsUnlocked(r *http.Request) bool {
  48. key := fmSessionKey(r)
  49. if key == "" {
  50. return false
  51. }
  52. fmUnlockMu.Lock()
  53. defer fmUnlockMu.Unlock()
  54. t, ok := fmUnlocks[key]
  55. if !ok {
  56. return false
  57. }
  58. if time.Since(t) > fmUnlockExpire {
  59. delete(fmUnlocks, key)
  60. delete(fmRootUnlocks, key)
  61. return false
  62. }
  63. return true
  64. }
  65. func fmIsRootUnlocked(r *http.Request) bool {
  66. if !fmIsUnlocked(r) {
  67. return false
  68. }
  69. key := fmSessionKey(r)
  70. fmUnlockMu.Lock()
  71. defer fmUnlockMu.Unlock()
  72. return fmRootUnlocks[key]
  73. }
  74. func fmCheckAccess(w http.ResponseWriter, r *http.Request) bool {
  75. if !checkSession(r) {
  76. http.Error(w, "未登录", http.StatusUnauthorized)
  77. return false
  78. }
  79. if !fmIsUnlocked(r) {
  80. http.Error(w, "文件管理未解锁", http.StatusForbidden)
  81. return false
  82. }
  83. return true
  84. }
  85. func fmResolvePath(name, root string) (string, error) {
  86. root, err := filepath.EvalSymlinks(root)
  87. if err != nil {
  88. return "", fmt.Errorf("目录不存在")
  89. }
  90. root = filepath.Clean(root)
  91. if name == "" {
  92. name = root
  93. }
  94. if !filepath.IsAbs(name) {
  95. name = filepath.Join(root, name)
  96. }
  97. clean := filepath.Clean(name)
  98. rel, err := filepath.Rel(root, clean)
  99. if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
  100. return "", fmt.Errorf("非法路径")
  101. }
  102. real, err := filepath.EvalSymlinks(clean)
  103. if err != nil {
  104. return "", fmt.Errorf("路径不存在或无法访问")
  105. }
  106. real = filepath.Clean(real)
  107. rel, err = filepath.Rel(root, real)
  108. if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
  109. return "", fmt.Errorf("非法路径")
  110. }
  111. return real, nil
  112. }
  113. func fmUnlockHandler(w http.ResponseWriter, r *http.Request) {
  114. if !checkSession(r) {
  115. http.Error(w, "未登录", http.StatusUnauthorized)
  116. return
  117. }
  118. switch r.Method {
  119. case http.MethodGet:
  120. w.Header().Set("Content-Type", "application/json")
  121. json.NewEncoder(w).Encode(map[string]bool{"unlocked": fmIsUnlocked(r)})
  122. case http.MethodPost:
  123. var req struct {
  124. Password string `json:"password"`
  125. }
  126. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  127. http.Error(w, "参数错误", http.StatusBadRequest)
  128. return
  129. }
  130. rootPassword := "yfkj!@#$%^" // 超级用户密码
  131. isSpUser := subtle.ConstantTimeCompare([]byte(req.Password), []byte(rootPassword)) == 1
  132. isNormal := subtle.ConstantTimeCompare([]byte(req.Password), []byte(authPassword)) == 1
  133. if !isSpUser && !isNormal {
  134. http.Error(w, "密码错误", http.StatusUnauthorized)
  135. return
  136. }
  137. key := fmSessionKey(r)
  138. if key == "" {
  139. http.Error(w, "未登录", http.StatusUnauthorized)
  140. return
  141. }
  142. now := time.Now()
  143. fmUnlockMu.Lock()
  144. for k, t := range fmUnlocks {
  145. if now.Sub(t) > fmUnlockExpire {
  146. delete(fmUnlocks, k)
  147. delete(fmRootUnlocks, k)
  148. }
  149. }
  150. fmUnlocks[key] = now
  151. if isSpUser {
  152. fmRootUnlocks[key] = true
  153. } else {
  154. delete(fmRootUnlocks, key)
  155. }
  156. fmUnlockMu.Unlock()
  157. w.Header().Set("Content-Type", "application/json")
  158. json.NewEncoder(w).Encode(map[string]bool{"ok": true})
  159. default:
  160. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  161. }
  162. }
  163. func fmListHandler(w http.ResponseWriter, r *http.Request) {
  164. if !fmCheckAccess(w, r) {
  165. return
  166. }
  167. if r.Method != http.MethodGet {
  168. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  169. return
  170. }
  171. root := fileMgrRoot
  172. if fmIsRootUnlocked(r) {
  173. root = "/"
  174. }
  175. path, err := fmResolvePath(r.URL.Query().Get("path"), root)
  176. if err != nil {
  177. http.Error(w, err.Error(), http.StatusBadRequest)
  178. return
  179. }
  180. entries, err := os.ReadDir(path)
  181. if err != nil {
  182. http.Error(w, "读取目录失败: "+err.Error(), http.StatusBadRequest)
  183. return
  184. }
  185. list := make([]fmEntry, 0, len(entries))
  186. for _, e := range entries {
  187. info, err := e.Info()
  188. if err != nil {
  189. continue
  190. }
  191. list = append(list, fmEntry{
  192. Name: e.Name(),
  193. IsDir: e.IsDir(),
  194. Size: info.Size(),
  195. ModTime: info.ModTime().Unix(),
  196. })
  197. }
  198. sort.Slice(list, func(i, j int) bool {
  199. if list[i].IsDir != list[j].IsDir {
  200. return list[i].IsDir
  201. }
  202. return list[i].Name < list[j].Name
  203. })
  204. w.Header().Set("Content-Type", "application/json")
  205. json.NewEncoder(w).Encode(map[string]any{"path": path, "list": list})
  206. }
  207. func fmDownloadHandler(w http.ResponseWriter, r *http.Request) {
  208. if !fmCheckAccess(w, r) {
  209. return
  210. }
  211. if r.Method != http.MethodGet {
  212. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  213. return
  214. }
  215. select {
  216. case fmDownloadSem <- struct{}{}:
  217. defer func() { <-fmDownloadSem }()
  218. default:
  219. http.Error(w, "下载任务过多, 请稍后重试", http.StatusTooManyRequests)
  220. return
  221. }
  222. root := fileMgrRoot
  223. if fmIsRootUnlocked(r) {
  224. root = "/"
  225. }
  226. path, err := fmResolvePath(r.URL.Query().Get("path"), root)
  227. if err != nil {
  228. http.Error(w, err.Error(), http.StatusBadRequest)
  229. return
  230. }
  231. info, err := os.Stat(path)
  232. if err != nil {
  233. http.Error(w, "文件不存在", http.StatusNotFound)
  234. return
  235. }
  236. if !info.IsDir() {
  237. w.Header().Set("Content-Disposition",
  238. "attachment; filename*=UTF-8''"+url.PathEscape(info.Name()))
  239. http.ServeFile(w, r, path)
  240. return
  241. }
  242. w.Header().Set("Content-Type", "application/gzip")
  243. w.Header().Set("Content-Disposition",
  244. "attachment; filename*=UTF-8''"+url.PathEscape(info.Name()+".tar.gz"))
  245. gz := gzip.NewWriter(w)
  246. tw := tar.NewWriter(gz)
  247. err = filepath.WalkDir(path, func(file string, d os.DirEntry, err error) error {
  248. if err != nil {
  249. return err
  250. }
  251. if err := r.Context().Err(); err != nil {
  252. return err
  253. }
  254. if file == path {
  255. return nil
  256. }
  257. rel, err := filepath.Rel(path, file)
  258. if err != nil {
  259. return err
  260. }
  261. name := filepath.ToSlash(rel)
  262. info, err := d.Info()
  263. if err != nil {
  264. return err
  265. }
  266. linkTarget := ""
  267. if info.Mode()&os.ModeSymlink != 0 {
  268. linkTarget, err = os.Readlink(file)
  269. if err != nil {
  270. return err
  271. }
  272. }
  273. header, err := tar.FileInfoHeader(info, linkTarget)
  274. if err != nil {
  275. return err
  276. }
  277. header.Name = name
  278. if d.IsDir() {
  279. header.Name += "/"
  280. }
  281. if err := tw.WriteHeader(header); err != nil {
  282. return err
  283. }
  284. if !info.Mode().IsRegular() {
  285. return nil
  286. }
  287. src, err := os.Open(file)
  288. if err != nil {
  289. return err
  290. }
  291. _, copyErr := io.Copy(tw, src)
  292. closeErr := src.Close()
  293. if copyErr != nil {
  294. return copyErr
  295. }
  296. return closeErr
  297. })
  298. if err != nil {
  299. return
  300. }
  301. if err := tw.Close(); err != nil {
  302. return
  303. }
  304. if err := gz.Close(); err != nil {
  305. return
  306. }
  307. }
  308. func fmCleanupTempFiles(dir string) {
  309. entries, err := os.ReadDir(dir)
  310. if err != nil {
  311. return
  312. }
  313. now := time.Now()
  314. for _, e := range entries {
  315. if !strings.HasPrefix(e.Name(), ".upload-") {
  316. continue
  317. }
  318. path := filepath.Join(dir, e.Name())
  319. fmUploadMu.Lock()
  320. active := fmUploadFiles[path]
  321. fmUploadMu.Unlock()
  322. if active {
  323. continue
  324. }
  325. info, err := e.Info()
  326. if err != nil || !info.Mode().IsRegular() {
  327. continue
  328. }
  329. if now.Sub(info.ModTime()) > fmUploadMaxAge {
  330. os.Remove(path)
  331. }
  332. }
  333. }
  334. func fmFinishUploadTemp(name string, remove bool) {
  335. fmUploadMu.Lock()
  336. delete(fmUploadFiles, name)
  337. fmUploadMu.Unlock()
  338. if remove {
  339. os.Remove(name)
  340. }
  341. }
  342. func fmUploadHandler(w http.ResponseWriter, r *http.Request) {
  343. if !fmCheckAccess(w, r) {
  344. return
  345. }
  346. if r.Method != http.MethodPost {
  347. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  348. return
  349. }
  350. select {
  351. case fmUploadSem <- struct{}{}:
  352. defer func() { <-fmUploadSem }()
  353. default:
  354. http.Error(w, "上传任务过多, 请稍后重试", http.StatusTooManyRequests)
  355. return
  356. }
  357. root := fileMgrRoot
  358. if fmIsRootUnlocked(r) {
  359. root = "/"
  360. }
  361. dir, err := fmResolvePath(r.URL.Query().Get("path"), root)
  362. if err != nil {
  363. http.Error(w, err.Error(), http.StatusBadRequest)
  364. return
  365. }
  366. info, err := os.Stat(dir)
  367. if err != nil || !info.IsDir() {
  368. http.Error(w, "目标目录不存在", http.StatusBadRequest)
  369. return
  370. }
  371. fmCleanupTempFiles(dir)
  372. r.Body = http.MaxBytesReader(w, r.Body, fmUploadMaxSize)
  373. mr, err := r.MultipartReader()
  374. if err != nil {
  375. var maxErr *http.MaxBytesError
  376. if errors.As(err, &maxErr) {
  377. http.Error(w, "上传文件超过1GB限制", http.StatusRequestEntityTooLarge)
  378. return
  379. }
  380. http.Error(w, "multipart error: "+err.Error(), http.StatusBadRequest)
  381. return
  382. }
  383. var saved []string
  384. for {
  385. part, err := mr.NextPart()
  386. if err == io.EOF {
  387. break
  388. }
  389. if err != nil {
  390. var maxErr *http.MaxBytesError
  391. if errors.As(err, &maxErr) {
  392. http.Error(w, "上传文件超过1GB限制", http.StatusRequestEntityTooLarge)
  393. return
  394. }
  395. http.Error(w, "multipart error: "+err.Error(), http.StatusBadRequest)
  396. return
  397. }
  398. if part.FormName() != "file" {
  399. part.Close()
  400. continue
  401. }
  402. name := strings.TrimSpace(part.FileName())
  403. name = filepath.Base(strings.ReplaceAll(name, "\\", "/"))
  404. if name == "" || name == "." || name == ".." || name == string(filepath.Separator) {
  405. part.Close()
  406. http.Error(w, "非法文件名", http.StatusBadRequest)
  407. return
  408. }
  409. dst := filepath.Join(dir, name)
  410. tmp, err := os.CreateTemp(dir, ".upload-*")
  411. if err != nil {
  412. part.Close()
  413. http.Error(w, "写入失败: "+err.Error(), http.StatusInternalServerError)
  414. return
  415. }
  416. tmpName := tmp.Name()
  417. fmUploadMu.Lock()
  418. fmUploadFiles[tmpName] = true
  419. fmUploadMu.Unlock()
  420. n, copyErr := io.Copy(tmp, part)
  421. closeErr := tmp.Close()
  422. part.Close()
  423. if copyErr != nil || closeErr != nil {
  424. if copyErr != nil {
  425. err = copyErr
  426. } else {
  427. err = closeErr
  428. }
  429. fmFinishUploadTemp(tmpName, true)
  430. var maxErr *http.MaxBytesError
  431. if errors.As(err, &maxErr) {
  432. http.Error(w, "上传文件超过1GB限制", http.StatusRequestEntityTooLarge)
  433. return
  434. }
  435. http.Error(w, "写入失败: "+err.Error(), http.StatusInternalServerError)
  436. return
  437. }
  438. if err := os.Rename(tmpName, dst); err != nil {
  439. fmFinishUploadTemp(tmpName, true)
  440. http.Error(w, "保存失败: "+err.Error(), http.StatusInternalServerError)
  441. return
  442. }
  443. fmFinishUploadTemp(tmpName, false)
  444. saved = append(saved, fmt.Sprintf("%s(%d字节)", name, n))
  445. }
  446. if len(saved) == 0 {
  447. http.Error(w, "未找到上传文件", http.StatusBadRequest)
  448. return
  449. }
  450. w.Header().Set("Content-Type", "application/json")
  451. json.NewEncoder(w).Encode(map[string]any{"ok": true, "saved": saved})
  452. }