| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567 |
- package main
- import (
- "archive/tar"
- "compress/gzip"
- "crypto/subtle"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "net/http"
- "net/url"
- "os"
- "path/filepath"
- "sort"
- "strings"
- "sync"
- "time"
- )
- const (
- fileMgrRoot = "/home" // 文件管理根目录/////////
- fmUnlockExpire = 30 * time.Minute // 解锁状态有效期/////////
- fmUploadMaxSize = 1 << 30 // 单次上传请求文件最大1GB
- fmUploadMaxAge = time.Hour // 临时文件超过1小时后清理
- )
- var (
- fmUnlockMu sync.Mutex
- fmUnlocks = make(map[string]time.Time)
- fmRootUnlocks = make(map[string]bool)
- fmUploadSem = make(chan struct{}, 1)
- fmDownloadSem = make(chan struct{}, 1)
- fmUploadMu sync.Mutex
- fmUploadFiles = make(map[string]bool)
- )
- type fmEntry struct {
- Name string `json:"name"`
- IsDir bool `json:"isDir"`
- Size int64 `json:"size"`
- ModTime int64 `json:"modTime"`
- }
- func fmSessionKey(r *http.Request) string {
- c, err := r.Cookie("session_id")
- if err != nil {
- return ""
- }
- return c.Value
- }
- func fmIsUnlocked(r *http.Request) bool {
- key := fmSessionKey(r)
- if key == "" {
- return false
- }
- fmUnlockMu.Lock()
- defer fmUnlockMu.Unlock()
- t, ok := fmUnlocks[key]
- if !ok {
- return false
- }
- if time.Since(t) > fmUnlockExpire {
- delete(fmUnlocks, key)
- delete(fmRootUnlocks, key)
- return false
- }
- return true
- }
- func fmIsRootUnlocked(r *http.Request) bool {
- if !fmIsUnlocked(r) {
- return false
- }
- key := fmSessionKey(r)
- fmUnlockMu.Lock()
- defer fmUnlockMu.Unlock()
- return fmRootUnlocks[key]
- }
- func fmCheckAccess(w http.ResponseWriter, r *http.Request) bool {
- if !checkSession(r) {
- http.Error(w, "未登录", http.StatusUnauthorized)
- return false
- }
- if !fmIsUnlocked(r) {
- http.Error(w, "文件管理未解锁", http.StatusForbidden)
- return false
- }
- return true
- }
- func fmResolvePath(name, root string) (string, error) {
- root, err := filepath.EvalSymlinks(root)
- if err != nil {
- return "", fmt.Errorf("目录不存在")
- }
- root = filepath.Clean(root)
- if name == "" {
- name = root
- }
- if !filepath.IsAbs(name) {
- name = filepath.Join(root, name)
- }
- clean := filepath.Clean(name)
- rel, err := filepath.Rel(root, clean)
- if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
- return "", fmt.Errorf("非法路径")
- }
- real, err := filepath.EvalSymlinks(clean)
- if err != nil {
- return "", fmt.Errorf("路径不存在或无法访问")
- }
- real = filepath.Clean(real)
- rel, err = filepath.Rel(root, real)
- if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
- return "", fmt.Errorf("非法路径")
- }
- return real, nil
- }
- func fmUnlockHandler(w http.ResponseWriter, r *http.Request) {
- if !checkSession(r) {
- http.Error(w, "未登录", http.StatusUnauthorized)
- return
- }
- switch r.Method {
- case http.MethodGet:
- w.Header().Set("Content-Type", "application/json")
- json.NewEncoder(w).Encode(map[string]bool{"unlocked": fmIsUnlocked(r)})
- case http.MethodPost:
- var req struct {
- Password string `json:"password"`
- }
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- http.Error(w, "参数错误", http.StatusBadRequest)
- return
- }
- rootPassword := "yfkj!@#$%^" // 超级用户密码
- isSpUser := subtle.ConstantTimeCompare([]byte(req.Password), []byte(rootPassword)) == 1
- isNormal := subtle.ConstantTimeCompare([]byte(req.Password), []byte(authPassword)) == 1
- if !isSpUser && !isNormal {
- http.Error(w, "密码错误", http.StatusUnauthorized)
- return
- }
- key := fmSessionKey(r)
- if key == "" {
- http.Error(w, "未登录", http.StatusUnauthorized)
- return
- }
- now := time.Now()
- fmUnlockMu.Lock()
- for k, t := range fmUnlocks {
- if now.Sub(t) > fmUnlockExpire {
- delete(fmUnlocks, k)
- delete(fmRootUnlocks, k)
- }
- }
- fmUnlocks[key] = now
- if isSpUser {
- fmRootUnlocks[key] = true
- } else {
- delete(fmRootUnlocks, key)
- }
- fmUnlockMu.Unlock()
- w.Header().Set("Content-Type", "application/json")
- json.NewEncoder(w).Encode(map[string]bool{"ok": true})
- default:
- http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
- }
- }
- func fmListHandler(w http.ResponseWriter, r *http.Request) {
- if !fmCheckAccess(w, r) {
- return
- }
- if r.Method != http.MethodGet {
- http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
- return
- }
- root := fileMgrRoot
- if fmIsRootUnlocked(r) {
- root = "/"
- }
- path, err := fmResolvePath(r.URL.Query().Get("path"), root)
- if err != nil {
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
- entries, err := os.ReadDir(path)
- if err != nil {
- http.Error(w, "读取目录失败: "+err.Error(), http.StatusBadRequest)
- return
- }
- list := make([]fmEntry, 0, len(entries))
- for _, e := range entries {
- info, err := e.Info()
- if err != nil {
- continue
- }
- list = append(list, fmEntry{
- Name: e.Name(),
- IsDir: e.IsDir(),
- Size: info.Size(),
- ModTime: info.ModTime().Unix(),
- })
- }
- sort.Slice(list, func(i, j int) bool {
- if list[i].IsDir != list[j].IsDir {
- return list[i].IsDir
- }
- return list[i].Name < list[j].Name
- })
- w.Header().Set("Content-Type", "application/json")
- json.NewEncoder(w).Encode(map[string]any{"path": path, "list": list})
- }
- func fmDownloadHandler(w http.ResponseWriter, r *http.Request) {
- if !fmCheckAccess(w, r) {
- return
- }
- if r.Method != http.MethodGet {
- http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
- return
- }
- select {
- case fmDownloadSem <- struct{}{}:
- defer func() { <-fmDownloadSem }()
- default:
- http.Error(w, "下载任务过多, 请稍后重试", http.StatusTooManyRequests)
- return
- }
- root := fileMgrRoot
- if fmIsRootUnlocked(r) {
- root = "/"
- }
- path, err := fmResolvePath(r.URL.Query().Get("path"), root)
- if err != nil {
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
- info, err := os.Stat(path)
- if err != nil {
- http.Error(w, "文件不存在", http.StatusNotFound)
- return
- }
- if !info.IsDir() {
- w.Header().Set("Content-Disposition",
- "attachment; filename*=UTF-8''"+url.PathEscape(info.Name()))
- http.ServeFile(w, r, path)
- return
- }
- w.Header().Set("Content-Type", "application/gzip")
- w.Header().Set("Content-Disposition",
- "attachment; filename*=UTF-8''"+url.PathEscape(info.Name()+".tar.gz"))
- gz := gzip.NewWriter(w)
- tw := tar.NewWriter(gz)
- err = filepath.WalkDir(path, func(file string, d os.DirEntry, err error) error {
- if err != nil {
- return err
- }
- if err := r.Context().Err(); err != nil {
- return err
- }
- if file == path {
- return nil
- }
- rel, err := filepath.Rel(path, file)
- if err != nil {
- return err
- }
- name := filepath.ToSlash(rel)
- info, err := d.Info()
- if err != nil {
- return err
- }
- linkTarget := ""
- if info.Mode()&os.ModeSymlink != 0 {
- linkTarget, err = os.Readlink(file)
- if err != nil {
- return err
- }
- }
- header, err := tar.FileInfoHeader(info, linkTarget)
- if err != nil {
- return err
- }
- header.Name = name
- if d.IsDir() {
- header.Name += "/"
- }
- if err := tw.WriteHeader(header); err != nil {
- return err
- }
- if !info.Mode().IsRegular() {
- return nil
- }
- src, err := os.Open(file)
- if err != nil {
- return err
- }
- _, copyErr := io.Copy(tw, src)
- closeErr := src.Close()
- if copyErr != nil {
- return copyErr
- }
- return closeErr
- })
- if err != nil {
- return
- }
- if err := tw.Close(); err != nil {
- return
- }
- if err := gz.Close(); err != nil {
- return
- }
- }
- func fmCleanupTempFiles(dir string) {
- entries, err := os.ReadDir(dir)
- if err != nil {
- return
- }
- now := time.Now()
- for _, e := range entries {
- if !strings.HasPrefix(e.Name(), ".upload-") {
- continue
- }
- path := filepath.Join(dir, e.Name())
- fmUploadMu.Lock()
- active := fmUploadFiles[path]
- fmUploadMu.Unlock()
- if active {
- continue
- }
- info, err := e.Info()
- if err != nil || !info.Mode().IsRegular() {
- continue
- }
- if now.Sub(info.ModTime()) > fmUploadMaxAge {
- os.Remove(path)
- }
- }
- }
- func fmFinishUploadTemp(name string, remove bool) {
- fmUploadMu.Lock()
- delete(fmUploadFiles, name)
- fmUploadMu.Unlock()
- if remove {
- os.Remove(name)
- }
- }
- func fmUploadHandler(w http.ResponseWriter, r *http.Request) {
- if !fmCheckAccess(w, r) {
- return
- }
- if r.Method != http.MethodPost {
- http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
- return
- }
- select {
- case fmUploadSem <- struct{}{}:
- defer func() { <-fmUploadSem }()
- default:
- http.Error(w, "上传任务过多, 请稍后重试", http.StatusTooManyRequests)
- return
- }
- root := fileMgrRoot
- if fmIsRootUnlocked(r) {
- root = "/"
- }
- dir, err := fmResolvePath(r.URL.Query().Get("path"), root)
- if err != nil {
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
- info, err := os.Stat(dir)
- if err != nil || !info.IsDir() {
- http.Error(w, "目标目录不存在", http.StatusBadRequest)
- return
- }
- fmCleanupTempFiles(dir)
- r.Body = http.MaxBytesReader(w, r.Body, fmUploadMaxSize)
- mr, err := r.MultipartReader()
- if err != nil {
- var maxErr *http.MaxBytesError
- if errors.As(err, &maxErr) {
- http.Error(w, "上传文件超过1GB限制", http.StatusRequestEntityTooLarge)
- return
- }
- http.Error(w, "multipart error: "+err.Error(), http.StatusBadRequest)
- return
- }
- var saved []string
- for {
- part, err := mr.NextPart()
- if err == io.EOF {
- break
- }
- if err != nil {
- var maxErr *http.MaxBytesError
- if errors.As(err, &maxErr) {
- http.Error(w, "上传文件超过1GB限制", http.StatusRequestEntityTooLarge)
- return
- }
- http.Error(w, "multipart error: "+err.Error(), http.StatusBadRequest)
- return
- }
- if part.FormName() != "file" {
- part.Close()
- continue
- }
- name := strings.TrimSpace(part.FileName())
- name = filepath.Base(strings.ReplaceAll(name, "\\", "/"))
- if name == "" || name == "." || name == ".." || name == string(filepath.Separator) {
- part.Close()
- http.Error(w, "非法文件名", http.StatusBadRequest)
- return
- }
- dst := filepath.Join(dir, name)
- tmp, err := os.CreateTemp(dir, ".upload-*")
- if err != nil {
- part.Close()
- http.Error(w, "写入失败: "+err.Error(), http.StatusInternalServerError)
- return
- }
- tmpName := tmp.Name()
- fmUploadMu.Lock()
- fmUploadFiles[tmpName] = true
- fmUploadMu.Unlock()
- n, copyErr := io.Copy(tmp, part)
- closeErr := tmp.Close()
- part.Close()
- if copyErr != nil || closeErr != nil {
- if copyErr != nil {
- err = copyErr
- } else {
- err = closeErr
- }
- fmFinishUploadTemp(tmpName, true)
- var maxErr *http.MaxBytesError
- if errors.As(err, &maxErr) {
- http.Error(w, "上传文件超过1GB限制", http.StatusRequestEntityTooLarge)
- return
- }
- http.Error(w, "写入失败: "+err.Error(), http.StatusInternalServerError)
- return
- }
- if err := os.Rename(tmpName, dst); err != nil {
- fmFinishUploadTemp(tmpName, true)
- http.Error(w, "保存失败: "+err.Error(), http.StatusInternalServerError)
- return
- }
- fmFinishUploadTemp(tmpName, false)
- saved = append(saved, fmt.Sprintf("%s(%d字节)", name, n))
- }
- if len(saved) == 0 {
- http.Error(w, "未找到上传文件", http.StatusBadRequest)
- return
- }
- w.Header().Set("Content-Type", "application/json")
- json.NewEncoder(w).Encode(map[string]any{"ok": true, "saved": saved})
- }
|