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}) }