Files

184 lines
5.5 KiB
Go
Raw Permalink 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"
"io"
"mime/multipart"
"net/http"
"os"
"path"
"path/filepath"
"sea-vhost/internal/nodefiles"
"strings"
"unicode/utf8"
)
const batchUploadLimit int64 = 30 << 20
type uploadItem struct {
Name string `json:"name"`
Size int64 `json:"size"`
Success bool `json:"success"`
Status int `json:"status"`
Error string `json:"error,omitempty"`
}
// Validate the whole selection before any file is committed.
var errUploadPath = errors.New("文件夹相对路径无效、重复或包含系统保留目录")
func batchUploadNames(headers []*multipart.FileHeader, limit int64) ([]string, error) {
return batchUploadPaths(headers, limit, nil)
}
func batchUploadPaths(headers []*multipart.FileHeader, limit int64, relative []string) ([]string, error) {
if relative != nil && len(relative) != len(headers) {
return nil, errUploadPath
}
if len(headers) == 0 || len(headers) > 100 {
return nil, errors.New("每批请选择 1–100 个文件")
}
names := make([]string, len(headers))
seen := map[string]bool{}
var total int64
for i, h := range headers {
if h.Size < 0 || h.Size > limit {
return nil, errors.New(uploadLimitMessage(limit))
}
if h.Size > batchUploadLimit-total {
return nil, errors.New("单批上传总大小不能超过 30 MB")
}
total += h.Size
name := filepath.Base(strings.ReplaceAll(h.Filename, "\\", "/"))
if relative != nil {
name = relative[i]
if !utf8.ValidString(name) || len(name) > 1024 || strings.ContainsAny(name, "\\:\x00\r\n") || strings.HasPrefix(name, "/") || path.Clean(name) != name || nodefiles.IsProtectedPath(name) || path.Base(name) != filepath.Base(strings.ReplaceAll(h.Filename, "\\", "/")) {
return nil, errUploadPath
}
parts := strings.Split(name, "/")
if len(parts) > 32 {
return nil, errUploadPath
}
for _, part := range parts {
if part == "" || part == "." || part == ".." || len(part) > 255 {
return nil, errUploadPath
}
}
}
if name == "." || name == ".." || name == "" || seen[name] {
return nil, errors.New("文件名无效或本批存在同名文件")
}
names[i] = name
seen[name] = true
}
for _, name := range names {
for parent := path.Dir(name); parent != "."; parent = path.Dir(parent) {
if seen[parent] {
return nil, errUploadPath
}
}
}
return names, nil
}
func (s *Server) uploadBatchFiles(w http.ResponseWriter, r *http.Request, tenantID uint64, root string) {
headers := r.MultipartForm.File["file"]
limit := min(s.cfg.UploadLimitBytes, int64(20<<20))
var relative []string
if raw := r.FormValue("relativePaths"); raw != "" {
if len(raw) > 128<<10 || json.Unmarshal([]byte(raw), &relative) != nil || relative == nil {
writeError(w, 400, "文件夹路径列表无效")
return
}
}
names, err := batchUploadPaths(headers, limit, relative)
if err != nil {
status := 413
if errors.Is(err, errUploadPath) {
status = 400
}
writeError(w, status, err.Error())
return
}
dir, err := safeProjectName(root, r.FormValue("path"))
if err != nil {
writeError(w, 400, "路径无效")
return
}
projectRoot, err := s.projects.OpenFiles(r.Context(), root)
if err != nil {
writeError(w, 404, "项目目录不存在")
return
}
defer projectRoot.Close()
targets := make([]string, len(names))
overwrite := r.FormValue("overwrite") == "true"
var additional uint64
for i, name := range names {
targets[i], err = safeProjectName(root, path.Join(dir, name))
if err != nil {
writeError(w, 400, "路径无效或包含系统保留文件")
return
}
growth := uint64(headers[i].Size)
if old, e := projectRoot.Lstat(targets[i]); e == nil && old.Mode().IsRegular() {
if !overwrite {
growth = 0
} else if uint64(old.Size()) >= growth {
growth = 0
} else {
growth -= uint64(old.Size())
}
}
additional += growth
}
if err = s.projects.CheckStorageWrite(r.Context(), tenantID, additional); err != nil {
writeFileQuotaError(w, err)
return
}
results := make([]uploadItem, 0, len(names))
for i, name := range names {
result := uploadItem{Name: name, Status: 422, Error: "上传失败,请刷新目录核对"}
flag := os.O_WRONLY | os.O_CREATE | os.O_EXCL
if overwrite {
flag = os.O_WRONLY | os.O_CREATE | os.O_TRUNC
}
source, e := headers[i].Open()
if e == nil {
if parent := path.Dir(filepath.ToSlash(targets[i])); parent != "." {
if mkdirErr := projectRoot.MkdirAll(parent, 0770); mkdirErr != nil {
source.Close()
s.logFile(r, tenantID, "file_operation", "文件夹上传创建子目录失败:"+name)
results = append(results, result)
continue
}
}
destination, openErr := projectRoot.OpenFile(targets[i], flag, 0660)
if openErr == nil {
written, copyErr := io.Copy(destination, io.LimitReader(source, limit+1))
if copyErr == nil && written == headers[i].Size && written <= limit {
e = destination.Close()
} else {
e = errors.New("upload truncated")
}
destination.Abort()
if e == nil {
result = uploadItem{Name: name, Size: written, Success: true, Status: 201}
s.logFile(r, tenantID, "upload", "批量上传文件:"+filepath.ToSlash(targets[i]))
}
} else {
e = openErr
}
source.Close()
}
if !result.Success {
if errors.Is(e, os.ErrExist) {
result.Status = 409
result.Error = "同名文件已存在,未覆盖"
}
s.logFile(r, tenantID, "file_operation", "批量上传失败:"+name)
}
results = append(results, result)
}
writeJSON(w, 207, map[string]any{"files": results})
}