Files
vHost/backend/internal/httpapi/files.go
T

423 lines
13 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package httpapi
import (
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
pathpkg "path"
"path/filepath"
"strconv"
"strings"
"time"
fileguard "sea-vhost/internal/files"
"sea-vhost/internal/nodefiles"
"sea-vhost/internal/scope"
"sea-vhost/internal/service"
"sea-vhost/internal/store"
)
type fileEntry struct {
Name string `json:"name"`
Path string `json:"path"`
Directory bool `json:"directory"`
Size int64 `json:"size"`
Modified time.Time `json:"modified"`
}
func (s *Server) files(w http.ResponseWriter, r *http.Request) {
id, err := projectID(r)
if err != nil {
writeError(w, http.StatusBadRequest, "项目编号无效")
return
}
user := currentUser(r)
if user.ProjectID != nil && *user.ProjectID != id {
writeError(w, http.StatusNotFound, "项目不存在")
return
}
project, err := s.store.Project(r.Context(), *user.TenantID, id)
if err != nil {
writeError(w, http.StatusNotFound, "项目不存在")
return
}
if r.Method != http.MethodGet {
tracked := &fileAuditResponse{ResponseWriter: w}
w = tracked
defer func() {
if tracked.status >= 400 {
s.logFile(r, project.TenantID, "file_operation", fmt.Sprintf("文件操作失败(HTTP %d)", tracked.status))
}
}()
}
switch r.Method {
case http.MethodGet:
s.listFiles(w, r, project.Path)
case http.MethodPost:
s.uploadFile(w, r, project.TenantID, project.Path)
case http.MethodPut:
s.writeTextFile(w, r, project.TenantID, project.Path)
case http.MethodDelete:
s.trashFile(w, r, user, project.ID, project.TenantID, project.Path)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
type fileAuditResponse struct {
http.ResponseWriter
status int
}
func (w *fileAuditResponse) WriteHeader(status int) {
if w.status == 0 {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
}
func (w *fileAuditResponse) Write(body []byte) (int, error) {
if w.status == 0 {
w.WriteHeader(http.StatusOK)
}
return w.ResponseWriter.Write(body)
}
func (s *Server) logFile(r *http.Request, tenantID uint64, action, detail string) {
user := currentUser(r)
s.store.Log(r.Context(), &tenantID, user.ID, action, "file", strconv.FormatUint(scope.Project(r.Context()), 10), requestClientIP(r), action != "file_operation", detail)
}
func safeProjectPath(root, requested string) (string, error) {
path, err := fileguard.Resolve(root, requested)
if err != nil {
return "", err
}
if err = fileguard.RejectSymlinks(root, path); err != nil {
return "", err
}
return path, nil
}
func safeProjectName(root, requested string) (string, error) {
absolute, err := fileguard.Resolve(root, requested)
if err != nil {
return "", err
}
relative, err := filepath.Rel(root, absolute)
if err != nil {
return "", err
}
if relative == "." {
return ".", nil
}
virtualPath := filepath.ToSlash(relative)
if nodefiles.IsProtectedPath(virtualPath) {
return "", fileguard.ErrOutsideRoot
}
return relative, nil
}
func displayProjectName(name string) string {
if name == "." {
return ""
}
return filepath.ToSlash(name)
}
func (s *Server) listFiles(w http.ResponseWriter, r *http.Request, root string) {
requested := r.URL.Query().Get("path")
name, err := safeProjectName(root, requested)
if err != nil {
writeError(w, http.StatusBadRequest, "路径无效")
return
}
projectRoot, err := s.projects.OpenFiles(r.Context(), root)
if err != nil {
writeError(w, http.StatusNotFound, "项目目录不存在")
return
}
defer projectRoot.Close()
if r.URL.Query().Get("download") == "1" {
s.downloadFile(w, r, projectRoot, name)
return
}
directory, err := projectRoot.Open(name)
if err != nil {
writeError(w, http.StatusNotFound, "目录不存在")
return
}
defer directory.Close()
entries, err := directory.ReadDir(-1)
if err != nil {
writeError(w, http.StatusNotFound, "目录不存在")
return
}
result := make([]fileEntry, 0, len(entries))
for _, entry := range entries {
if nodefiles.IsProtectedPath(entry.Name()) {
continue
}
info, err := entry.Info()
if err != nil {
continue
}
result = append(result, fileEntry{Name: entry.Name(), Path: displayProjectName(filepath.Join(name, entry.Name())), Directory: entry.IsDir(), Size: info.Size(), Modified: info.ModTime()})
}
writeJSON(w, http.StatusOK, map[string]any{"path": displayProjectName(name), "entries": result, "uploadLimit": s.cfg.UploadLimitBytes})
}
func (s *Server) downloadFile(w http.ResponseWriter, r *http.Request, root *nodefiles.Root, name string) {
file, err := root.Open(name)
if err != nil {
writeError(w, http.StatusNotFound, "文件不存在")
return
}
defer file.Close()
info, err := file.Stat()
if err != nil || info.IsDir() {
writeError(w, http.StatusNotFound, "文件不存在")
return
}
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filepath.Base(name)))
http.ServeContent(w, r, filepath.Base(name), info.ModTime(), file)
}
func (s *Server) uploadFile(w http.ResponseWriter, r *http.Request, tenantID uint64, root string) {
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.UploadLimitBytes+1<<20)
if err := r.ParseMultipartForm(s.cfg.UploadLimitBytes); err != nil {
writeError(w, http.StatusRequestEntityTooLarge, uploadLimitMessage(s.cfg.UploadLimitBytes))
return
}
if r.MultipartForm != nil {
defer r.MultipartForm.RemoveAll()
}
source, header, err := r.FormFile("file")
if err != nil {
writeError(w, http.StatusBadRequest, "缺少上传文件")
return
}
defer source.Close()
dir, err := safeProjectName(root, r.FormValue("path"))
if err != nil {
writeError(w, http.StatusBadRequest, "路径无效")
return
}
name := filepath.Base(strings.ReplaceAll(header.Filename, "\\", "/"))
if name == "." || name == ".." || name == "" {
writeError(w, http.StatusBadRequest, "文件名无效")
return
}
target, err := safeProjectName(root, pathpkg.Join(dir, name))
if err != nil {
writeError(w, http.StatusBadRequest, "路径无效")
return
}
flag := os.O_WRONLY | os.O_CREATE | os.O_EXCL
if r.FormValue("overwrite") == "true" {
flag = os.O_WRONLY | os.O_CREATE | os.O_TRUNC
}
projectRoot, err := s.projects.OpenFiles(r.Context(), root)
if err != nil {
writeError(w, http.StatusNotFound, "项目目录不存在")
return
}
defer projectRoot.Close()
if header.Size < 0 || header.Size > s.cfg.UploadLimitBytes {
writeError(w, http.StatusBadRequest, "无法确定上传文件大小")
return
}
additionalBytes := uint64(header.Size)
if r.FormValue("overwrite") == "true" {
if existing, statErr := projectRoot.Lstat(target); statErr == nil && existing.Mode().IsRegular() && existing.Size() > 0 {
oldSize := uint64(existing.Size())
if oldSize >= additionalBytes {
additionalBytes = 0
} else {
additionalBytes -= oldSize
}
}
}
if err = s.projects.CheckStorageWrite(r.Context(), tenantID, additionalBytes); err != nil {
writeFileQuotaError(w, err)
return
}
destination, err := projectRoot.OpenFile(target, flag, 0660)
if err != nil {
writeError(w, http.StatusConflict, "文件已存在或不可写")
return
}
defer destination.Abort()
written, err := io.Copy(destination, io.LimitReader(source, s.cfg.UploadLimitBytes+1))
if err != nil || written > s.cfg.UploadLimitBytes {
writeError(w, http.StatusRequestEntityTooLarge, uploadLimitMessage(s.cfg.UploadLimitBytes))
return
}
if err = destination.Close(); err != nil {
writeFileCommitError(w, err)
return
}
s.logFile(r, tenantID, "upload", "上传文件:"+filepath.ToSlash(target))
writeJSON(w, http.StatusCreated, map[string]any{"name": name, "size": written})
}
func uploadLimitMessage(limit int64) string {
return fmt.Sprintf("单文件不能超过 %d MB", (limit+(1024*1024)-1)/(1024*1024))
}
func (s *Server) writeTextFile(w http.ResponseWriter, r *http.Request, tenantID uint64, root string) {
var input struct {
Path string `json:"path"`
Content string `json:"content"`
Overwrite bool `json:"overwrite"`
}
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&input); err != nil {
writeError(w, http.StatusBadRequest, "请求格式错误或文本文件超过 1 MB")
return
}
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
writeError(w, http.StatusBadRequest, "请求格式错误")
return
}
path, err := safeProjectName(root, input.Path)
if err != nil {
writeError(w, http.StatusBadRequest, "路径无效")
return
}
projectRoot, err := s.projects.OpenFiles(r.Context(), root)
if err != nil {
writeError(w, http.StatusNotFound, "项目目录不存在")
return
}
defer projectRoot.Close()
additionalBytes := uint64(len(input.Content))
if input.Overwrite {
if existing, statErr := projectRoot.Lstat(path); statErr == nil && existing.Mode().IsRegular() && existing.Size() > 0 {
oldSize := uint64(existing.Size())
if oldSize >= additionalBytes {
additionalBytes = 0
} else {
additionalBytes -= oldSize
}
}
}
if err = s.projects.CheckStorageWrite(r.Context(), tenantID, additionalBytes); err != nil {
writeFileQuotaError(w, err)
return
}
flag := os.O_WRONLY | os.O_CREATE | os.O_EXCL
if input.Overwrite {
flag = os.O_WRONLY | os.O_CREATE | os.O_TRUNC
}
destination, err := projectRoot.OpenFile(path, flag, 0660)
if err != nil {
writeError(w, http.StatusConflict, "文件已存在或不可写")
return
}
defer destination.Abort()
if _, err = destination.Write([]byte(input.Content)); err != nil {
writeError(w, http.StatusUnprocessableEntity, "无法保存文件")
return
}
if err = destination.Close(); err != nil {
writeFileCommitError(w, err)
return
}
s.logFile(r, tenantID, "write", "保存文本文件:"+filepath.ToSlash(path))
w.WriteHeader(http.StatusNoContent)
}
func writeFileCommitError(w http.ResponseWriter, err error) {
if errors.Is(err, os.ErrExist) {
writeError(w, http.StatusConflict, "文件已存在,确认后才可覆盖")
return
}
writeError(w, http.StatusUnprocessableEntity, "文件提交失败,请刷新目录核对后再操作")
}
func writeFileQuotaError(w http.ResponseWriter, err error) {
if errors.Is(err, store.ErrManagementLocked) {
writeCodedError(w, 423, "management_locked", err.Error())
return
}
if errors.Is(err, store.ErrHostNotWritable) {
writeCodedError(w, http.StatusLocked, "host_not_writable", err.Error())
return
}
if errors.Is(err, service.ErrQuotaSuspended) {
writeCodedError(w, http.StatusLocked, "quota_suspended", "资源套餐已超额,当前仅允许读取或永久清理数据")
return
}
if errors.Is(err, service.ErrStorageQuotaExceeded) {
writeCodedError(w, http.StatusInsufficientStorage, "storage_quota_exceeded", "存储空间不足,请先永久删除文件或清空回收站")
return
}
slog.Warn("file quota verification unavailable", "error", err)
w.Header().Set("Retry-After", "3")
writeCodedError(w, http.StatusServiceUnavailable, "resource_check_unavailable", "暂时无法核对资源用量,请稍后重试")
}
func (s *Server) trashFile(w http.ResponseWriter, r *http.Request, user store.User, projectID, tenantID uint64, root string) {
if r.URL.Query().Get("emptyTrash") == "1" {
if err := s.projects.PrepareTrash(r.Context(), user, projectID); err != nil {
writeError(w, http.StatusUnprocessableEntity, "无法安全清空回收站")
return
}
projectRoot, err := s.projects.OpenFiles(r.Context(), root)
if err != nil {
writeError(w, http.StatusNotFound, "项目目录不存在")
return
}
defer projectRoot.Close()
if err = projectRoot.RemoveAll(".sea-trash"); err != nil {
writeError(w, http.StatusUnprocessableEntity, "无法清空回收站")
return
}
// Refresh immediately so a tenant that has cleaned enough data does not
// have to wait for the next one-minute monitor cycle.
_ = s.projects.CheckStorageWrite(r.Context(), tenantID, 0)
s.logFile(r, tenantID, "empty_trash", "清空主机回收站")
w.WriteHeader(http.StatusNoContent)
return
}
path, err := safeProjectName(root, r.URL.Query().Get("path"))
if err != nil || path == "." {
writeError(w, http.StatusBadRequest, "路径无效")
return
}
path = filepath.ToSlash(path)
if path == ".sea-trash" || strings.HasPrefix(path, ".sea-trash/") {
writeError(w, http.StatusBadRequest, "路径无效")
return
}
sites, err := s.store.ListSites(r.Context(), tenantID, projectID)
if err != nil {
writeError(w, http.StatusInternalServerError, "无法核对网站运行目录")
return
}
candidate := "/" + strings.TrimPrefix(path, "/")
for _, site := range sites {
runPath := filepath.ToSlash(filepath.Clean(site.RunPath))
if candidate == runPath || strings.HasPrefix(runPath, candidate+"/") {
writeError(w, http.StatusConflict, "该目录仍被网站使用,请先删除或修改网站")
return
}
}
projectRoot, err := s.projects.OpenFiles(r.Context(), root)
if err != nil {
writeError(w, http.StatusNotFound, "项目目录不存在")
return
}
defer projectRoot.Close()
if _, err = projectRoot.Action(nodefiles.Request{Operation: "trash", Path: path}); err != nil {
writeError(w, http.StatusUnprocessableEntity, "无法移动到回收站")
return
}
s.logFile(r, tenantID, "trash", "移入回收站:"+path)
w.WriteHeader(http.StatusNoContent)
}