forked from mtusi2026/mtusi2026lab4
157 lines
3.5 KiB
Go
157 lines
3.5 KiB
Go
package upload
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"image"
|
|
_ "image/jpeg"
|
|
_ "image/png"
|
|
"io"
|
|
"mime"
|
|
"os"
|
|
"strings"
|
|
"sync"
|
|
"unicode"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
const (
|
|
MaxBytes int64 = 10 * 1024 * 1024
|
|
MaxPixels = 40_000_000
|
|
)
|
|
|
|
var (
|
|
ErrFilename = errors.New("invalid attachment filename")
|
|
ErrMediaType = errors.New("unsupported or corrupt image")
|
|
ErrTooLarge = errors.New("attachment limit exceeded")
|
|
ErrInterrupted = errors.New("upload interrupted")
|
|
)
|
|
|
|
type Validator struct {
|
|
tempDir string
|
|
slot chan struct{}
|
|
}
|
|
|
|
func NewValidator(tempDir string) *Validator {
|
|
return &Validator{tempDir: tempDir, slot: make(chan struct{}, 1)}
|
|
}
|
|
|
|
type Prepared struct {
|
|
File *os.File
|
|
SizeBytes int64
|
|
SHA256 string
|
|
ContentType string
|
|
Width int
|
|
Height int
|
|
release func()
|
|
closeOnce sync.Once
|
|
closeErr error
|
|
}
|
|
|
|
func (p *Prepared) Close() error {
|
|
p.closeOnce.Do(func() {
|
|
p.closeErr = errors.Join(p.File.Close(), os.Remove(p.File.Name()))
|
|
p.release()
|
|
})
|
|
return p.closeErr
|
|
}
|
|
|
|
func ValidFilename(name string) bool {
|
|
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 255 {
|
|
return false
|
|
}
|
|
for _, r := range name {
|
|
if r == '/' || r == '\\' || unicode.IsControl(r) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (v *Validator) Prepare(ctx context.Context, source io.Reader, contentType, filename string) (_ *Prepared, err error) {
|
|
if !ValidFilename(filename) {
|
|
return nil, ErrFilename
|
|
}
|
|
mediaType, _, parseErr := mime.ParseMediaType(contentType)
|
|
if parseErr != nil || (mediaType != "image/png" && mediaType != "image/jpeg") {
|
|
return nil, ErrMediaType
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
return nil, ctx.Err()
|
|
case v.slot <- struct{}{}:
|
|
}
|
|
defer func() {
|
|
if err != nil {
|
|
<-v.slot
|
|
}
|
|
}()
|
|
file, err := os.CreateTemp(v.tempDir, "attachment-*")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create upload staging: %w", err)
|
|
}
|
|
defer func() {
|
|
if err != nil {
|
|
file.Close()
|
|
os.Remove(file.Name())
|
|
}
|
|
}()
|
|
hash := sha256.New()
|
|
size, err := io.CopyBuffer(io.MultiWriter(file, hash), io.LimitReader(contextReader{ctx, source}, MaxBytes+1), make([]byte, 32*1024))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("stage upload: %w", err)
|
|
}
|
|
if size > MaxBytes {
|
|
return nil, ErrTooLarge
|
|
}
|
|
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
|
return nil, err
|
|
}
|
|
config, format, err := image.DecodeConfig(file)
|
|
if err != nil || "image/"+format != mediaType {
|
|
return nil, ErrMediaType
|
|
}
|
|
if config.Width <= 0 || config.Height <= 0 || config.Width > MaxPixels/config.Height {
|
|
return nil, ErrTooLarge
|
|
}
|
|
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
|
return nil, err
|
|
}
|
|
if _, _, err := image.Decode(contextReader{ctx, file}); err != nil {
|
|
if ctx.Err() != nil {
|
|
return nil, ctx.Err()
|
|
}
|
|
return nil, ErrMediaType
|
|
}
|
|
if err := ctx.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
|
return nil, err
|
|
}
|
|
return &Prepared{
|
|
File: file, SizeBytes: size, SHA256: hex.EncodeToString(hash.Sum(nil)),
|
|
ContentType: mediaType, Width: config.Width, Height: config.Height,
|
|
release: func() { <-v.slot },
|
|
}, nil
|
|
}
|
|
|
|
type contextReader struct {
|
|
ctx context.Context
|
|
src io.Reader
|
|
}
|
|
|
|
func (r contextReader) Read(p []byte) (int, error) {
|
|
if err := r.ctx.Err(); err != nil {
|
|
return 0, err
|
|
}
|
|
n, err := r.src.Read(p)
|
|
if err != nil && !errors.Is(err, io.EOF) {
|
|
return n, fmt.Errorf("%w: %w", ErrInterrupted, err)
|
|
}
|
|
return n, err
|
|
}
|