1 parent
734d389a7c
commit
ff23b27713
11 files changed
+822
-15
No files matched your search
@@ -0,0 +1,205 @@
|
||||
// Package zipfile 提供独占临时目录中的 ZIP 解压,不负责下载、上传或文件业务分类。
|
||||
package zipfile
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
zipPath "path"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"git.zhangdeman.cn/zhangdeman/ginframework/diagnostic"
|
||||
failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultMaxEntries 是未指定时允许的归档条目总数,包含目录。
|
||||
DefaultMaxEntries = 10000
|
||||
// DefaultMaxBytes 是未指定时允许的解压内容总字节数。
|
||||
DefaultMaxBytes int64 = 1 << 30
|
||||
codeOptions = 901201
|
||||
codeOpen = 901202
|
||||
codeTemp = 901203
|
||||
codePath = 901204
|
||||
codeEntry = 901205
|
||||
codeLimit = 901206
|
||||
codeDirectory = 901207
|
||||
codeRead = 901208
|
||||
codeWrite = 901209
|
||||
codeClose = 901210
|
||||
codeCleanup = 901211
|
||||
codeCanceled = 901212
|
||||
)
|
||||
|
||||
// Options 控制解压位置和资源额度,零值使用有界缺省值,负额度拒绝。
|
||||
type Options struct {
|
||||
TempDir string `json:"temp_dir" dc:"独占随机目录的父目录,空使用系统临时目录"`
|
||||
MaxEntries int `json:"max_entries" dc:"包含目录的条目上限,零使用一万条"`
|
||||
MaxBytes int64 `json:"max_bytes" dc:"解压总字节上限,零使用一 GiB"`
|
||||
}
|
||||
|
||||
// Extraction 拥有成功解压的独占临时目录;上传等读取结束后由调用方 Close。
|
||||
type Extraction struct {
|
||||
root string `dc:"不可由调用方改写的独占目录"`
|
||||
files []string `dc:"排序后的普通文件绝对路径"`
|
||||
ctx context.Context `dc:"只用于清理失败诊断的调用上下文"`
|
||||
}
|
||||
|
||||
// Dir 返回当前拥有的目录;Close 成功后返回空字符串。
|
||||
func (e *Extraction) Dir() string { return e.root }
|
||||
|
||||
// Files 返回排序后的路径副本,不含目录条目;不转移临时文件所有权。
|
||||
func (e *Extraction) Files() []string { return append([]string(nil), e.files...) }
|
||||
|
||||
// Close 清理本对象拥有的目录,成功后可重复调用;不得与读取文件或其他 Close 并发。
|
||||
// 返回:删除失败的内部场景错误,保留原因链并允许稍后再次清理。
|
||||
func (e *Extraction) Close() error {
|
||||
if e.root == "" {
|
||||
return nil
|
||||
}
|
||||
if err := os.RemoveAll(e.root); err != nil {
|
||||
return failure.WrapContext(e.ctx, codeCleanup, "remove ZIP extraction failed", err)
|
||||
}
|
||||
e.root = ""
|
||||
return nil
|
||||
}
|
||||
|
||||
// ExtractBytes 解压内存 ZIP;入参为允许 nil 的标准上下文、归档字节和额度选项。
|
||||
// 返回:成功结果归调用方 Close;失败不会交付部分结果,不修改输入字节。
|
||||
func ExtractBytes(ctx context.Context, data []byte, options Options) (*Extraction, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
return nil, failure.WrapContext(ctx, codeOpen, "open ZIP archive failed", err)
|
||||
}
|
||||
return Extract(ctx, reader, options)
|
||||
}
|
||||
|
||||
// Extract 将归档写入独占随机目录,不借用调用方目录中的既有文件。
|
||||
// 入参:ctx 允许 nil;reader 为非 nil 标准 ZIP Reader;options 为正额度或零值默认。
|
||||
// 返回:排序后的普通文件及目录所有权;拒绝越界、反斜线、特殊文件和重复文件路径。
|
||||
// 声明大小与实际复制均受总额度约束,复制中检查取消;失败自动清理并保留清理错误链。
|
||||
func Extract(ctx context.Context, reader *zip.Reader, options Options) (result *Extraction, resultError error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if reader == nil || options.MaxEntries < 0 || options.MaxBytes < 0 || options.MaxBytes == 1<<63-1 {
|
||||
return nil, failure.WrapContext(ctx, codeOptions, "validate ZIP extraction options failed", errors.New("reader and supported non-negative extraction limits are required"))
|
||||
}
|
||||
if options.MaxEntries == 0 {
|
||||
options.MaxEntries = DefaultMaxEntries
|
||||
}
|
||||
if options.MaxBytes == 0 {
|
||||
options.MaxBytes = DefaultMaxBytes
|
||||
}
|
||||
if len(reader.File) > options.MaxEntries {
|
||||
return nil, failure.WrapContext(ctx, codeLimit, "limit ZIP extraction failed", errors.New("ZIP entry count exceeds limit"))
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, failure.WrapContext(ctx, codeCanceled, "cancel ZIP extraction failed", err)
|
||||
}
|
||||
root, err := os.MkdirTemp(options.TempDir, "zip-extract-*")
|
||||
if err != nil {
|
||||
return nil, failure.WrapContext(ctx, codeTemp, "create ZIP extraction directory failed", err)
|
||||
}
|
||||
extracted := &Extraction{root: root, ctx: diagnostic.With(context.Background(), diagnostic.From(ctx))}
|
||||
defer func() {
|
||||
if resultError != nil {
|
||||
resultError = errors.Join(resultError, extracted.Close())
|
||||
}
|
||||
}()
|
||||
remaining := options.MaxBytes
|
||||
for _, entry := range reader.File {
|
||||
if err = ctx.Err(); err != nil {
|
||||
return nil, failure.WrapContext(ctx, codeCanceled, "cancel ZIP extraction failed", err)
|
||||
}
|
||||
name := strings.TrimSuffix(entry.Name, "/")
|
||||
if strings.Contains(name, "\\") || strings.HasPrefix(name, "/") {
|
||||
return nil, failure.WrapContext(ctx, codePath, "validate ZIP entry path failed", errors.New("ZIP entry must use a local path"))
|
||||
}
|
||||
name = zipPath.Clean(name)
|
||||
if name == "." && entry.Mode().IsDir() {
|
||||
continue
|
||||
}
|
||||
if !fs.ValidPath(name) || !filepath.IsLocal(filepath.FromSlash(name)) {
|
||||
return nil, failure.WrapContext(ctx, codePath, "validate ZIP entry path failed", errors.New("ZIP entry must use a local path"))
|
||||
}
|
||||
if !entry.Mode().IsRegular() && !entry.Mode().IsDir() {
|
||||
return nil, failure.WrapContext(ctx, codeEntry, "validate ZIP entry type failed", errors.New("ZIP entry must be a regular file or directory"))
|
||||
}
|
||||
target := filepath.Join(root, filepath.FromSlash(name))
|
||||
if entry.Mode().IsDir() {
|
||||
if err = os.MkdirAll(target, 0700); err != nil {
|
||||
return nil, failure.WrapContext(ctx, codeDirectory, "create ZIP entry directory failed", err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if entry.UncompressedSize64 > uint64(remaining) {
|
||||
return nil, failure.WrapContext(ctx, codeLimit, "limit ZIP extraction failed", errors.New("ZIP uncompressed bytes exceed limit"))
|
||||
}
|
||||
if err = os.MkdirAll(filepath.Dir(target), 0700); err != nil {
|
||||
return nil, failure.WrapContext(ctx, codeDirectory, "create ZIP entry directory failed", err)
|
||||
}
|
||||
n, writeErr := writeEntry(ctx, entry, target, remaining)
|
||||
if writeErr != nil {
|
||||
return nil, writeErr
|
||||
}
|
||||
remaining -= n
|
||||
extracted.files = append(extracted.files, target)
|
||||
}
|
||||
sort.Strings(extracted.files)
|
||||
return extracted, nil
|
||||
}
|
||||
|
||||
// cancelWriter 在每次复制写入前检查取消,不持有归档或创建后台任务。
|
||||
type cancelWriter struct {
|
||||
ctx context.Context `dc:"复制取消上下文"`
|
||||
output io.Writer `dc:"当前文件写入器"`
|
||||
}
|
||||
|
||||
// Write 将 p 写入文件,返回写入量或原始取消/写入错误,由复制边界统一分类。
|
||||
func (w cancelWriter) Write(p []byte) (int, error) {
|
||||
if err := w.ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return w.output.Write(p)
|
||||
}
|
||||
|
||||
// writeEntry 打开并复制一个普通条目;入参为上下文、条目、目标和剩余总额度。
|
||||
// 返回:实际解压字节或已分类错误;同时关闭读写资源,保留复制及关闭原因链。
|
||||
func writeEntry(ctx context.Context, entry *zip.File, target string, remaining int64) (n int64, resultError error) {
|
||||
input, err := entry.Open()
|
||||
if err != nil {
|
||||
return 0, failure.WrapContext(ctx, codeRead, "open ZIP entry failed", err)
|
||||
}
|
||||
defer func() {
|
||||
if err := input.Close(); err != nil {
|
||||
resultError = errors.Join(resultError, failure.WrapContext(ctx, codeClose, "close ZIP entry failed", err))
|
||||
}
|
||||
}()
|
||||
output, err := os.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
return 0, failure.WrapContext(ctx, codeWrite, "create ZIP entry failed", err)
|
||||
}
|
||||
defer func() {
|
||||
if err := output.Close(); err != nil {
|
||||
resultError = errors.Join(resultError, failure.WrapContext(ctx, codeClose, "close ZIP entry failed", err))
|
||||
}
|
||||
}()
|
||||
n, err = io.Copy(cancelWriter{ctx: ctx, output: output}, io.LimitReader(input, remaining+1))
|
||||
if err != nil {
|
||||
return n, failure.WrapContext(ctx, codeWrite, "copy ZIP entry failed", err)
|
||||
}
|
||||
if n > remaining {
|
||||
return n, failure.WrapContext(ctx, codeLimit, "limit ZIP extraction failed", errors.New("ZIP actual bytes exceed limit"))
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||