129 lines
3.7 KiB
Go
129 lines
3.7 KiB
Go
package attachment
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"image"
|
|
_ "image/jpeg"
|
|
_ "image/png"
|
|
"io"
|
|
"mime"
|
|
"os"
|
|
"strings"
|
|
"unicode"
|
|
"unicode/utf8"
|
|
|
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
|
)
|
|
|
|
const MaxBytes int64 = 10 * 1024 * 1024
|
|
const MaxPixels int64 = 40_000_000
|
|
|
|
func appError(code domain.ErrorCode, message string) error {
|
|
return domain.NewApplicationError(code, message)
|
|
}
|
|
func unavailable() error {
|
|
return appError(domain.ErrorUnavailable, "Хранилище вложений недоступно")
|
|
}
|
|
func ValidateFilename(name string) error {
|
|
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 255 {
|
|
return appError(domain.ErrorInvalid, "Некорректный filename")
|
|
}
|
|
for _, r := range name {
|
|
if r == '/' || r == '\\' || unicode.IsControl(r) {
|
|
return appError(domain.ErrorInvalid, "Недопустимые символы filename")
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type Original struct {
|
|
File *os.File
|
|
Size int64
|
|
SHA256, ContentType string
|
|
Width, Height int
|
|
}
|
|
|
|
func (o *Original) Close() { name := o.File.Name(); o.File.Close(); os.Remove(name) }
|
|
|
|
// Spool bounds compressed bytes on disk before any decode. DecodeConfig checks the
|
|
// pixel budget before a full decode verifies CRCs/truncated scan data.
|
|
func Spool(ctx context.Context, body io.Reader, declared string) (*Original, error) {
|
|
media, _, err := mime.ParseMediaType(declared)
|
|
if err != nil || (media != "image/png" && media != "image/jpeg") {
|
|
return nil, appError("unsupported_media_type", "Допустимы PNG и JPEG")
|
|
}
|
|
f, err := os.CreateTemp("", "messenger-upload-*")
|
|
if err != nil {
|
|
return nil, unavailable()
|
|
}
|
|
o := &Original{File: f}
|
|
good := false
|
|
defer func() {
|
|
if !good {
|
|
o.Close()
|
|
}
|
|
}()
|
|
hash := sha256.New()
|
|
n, err := io.Copy(io.MultiWriter(f, hash), io.LimitReader(&contextReader{ctx: ctx, r: body}, MaxBytes+1))
|
|
if n > MaxBytes {
|
|
return nil, appError("payload_too_large", "Файл превышает 10 MiB")
|
|
}
|
|
if err != nil {
|
|
return nil, appError(domain.ErrorInvalid, "Загрузка прервана")
|
|
}
|
|
o.Size = n
|
|
o.SHA256 = hex.EncodeToString(hash.Sum(nil))
|
|
if _, err = f.Seek(0, 0); err != nil {
|
|
return nil, unavailable()
|
|
}
|
|
cfg, format, err := image.DecodeConfig(f)
|
|
if err != nil {
|
|
return nil, appError("unsupported_media_type", "Повреждённое изображение")
|
|
}
|
|
actual := "image/" + format
|
|
if actual != media {
|
|
return nil, appError("unsupported_media_type", "MIME не соответствует содержимому")
|
|
}
|
|
if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width) > MaxPixels/int64(cfg.Height) {
|
|
return nil, appError("payload_too_large", "Изображение превышает 40 миллионов пикселей")
|
|
}
|
|
if _, err = f.Seek(0, 0); err != nil {
|
|
return nil, unavailable()
|
|
}
|
|
decoded, format, err := image.Decode(f)
|
|
if err != nil || decoded == nil || "image/"+format != actual {
|
|
return nil, appError("unsupported_media_type", "Повреждённое изображение")
|
|
}
|
|
if decoded.Bounds().Dx() != cfg.Width || decoded.Bounds().Dy() != cfg.Height {
|
|
return nil, appError("unsupported_media_type", "Некорректные размеры изображения")
|
|
}
|
|
decoded = nil
|
|
if _, err = f.Seek(0, 0); err != nil {
|
|
return nil, unavailable()
|
|
}
|
|
o.ContentType = actual
|
|
o.Width = cfg.Width
|
|
o.Height = cfg.Height
|
|
good = true
|
|
return o, nil
|
|
}
|
|
|
|
type contextReader struct {
|
|
ctx context.Context
|
|
r io.Reader
|
|
}
|
|
|
|
func (r *contextReader) Read(p []byte) (int, error) {
|
|
if err := r.ctx.Err(); err != nil {
|
|
return 0, err
|
|
}
|
|
n, err := r.r.Read(p)
|
|
if errors.Is(err, context.Canceled) {
|
|
return n, err
|
|
}
|
|
return n, err
|
|
}
|