1
0
mirror of https://github.com/imgproxy/imgproxy.git synced 2025-01-08 10:45:04 +02:00
imgproxy/imagedata/read.go

79 lines
1.8 KiB
Go
Raw Normal View History

2021-04-26 13:52:50 +02:00
package imagedata
import (
"io"
2021-09-30 16:23:30 +02:00
"github.com/imgproxy/imgproxy/v3/bufpool"
"github.com/imgproxy/imgproxy/v3/bufreader"
"github.com/imgproxy/imgproxy/v3/config"
"github.com/imgproxy/imgproxy/v3/ierrors"
"github.com/imgproxy/imgproxy/v3/imagemeta"
"github.com/imgproxy/imgproxy/v3/security"
2021-04-26 13:52:50 +02:00
)
var (
ErrSourceFileTooBig = ierrors.New(422, "Source image file is too big", "Invalid source image")
ErrSourceImageTypeNotSupported = ierrors.New(422, "Source image type not supported", "Invalid source image")
)
var downloadBufPool *bufpool.Pool
func initRead() {
downloadBufPool = bufpool.New("download", config.Concurrency, config.DownloadBufferSize)
}
type hardLimitReader struct {
r io.Reader
left int
}
func (lr *hardLimitReader) Read(p []byte) (n int, err error) {
if lr.left <= 0 {
return 0, ErrSourceFileTooBig
}
if len(p) > lr.left {
p = p[0:lr.left]
}
n, err = lr.r.Read(p)
lr.left -= n
return
}
func readAndCheckImage(r io.Reader, contentLength int) (*ImageData, error) {
if config.MaxSrcFileSize > 0 && contentLength > config.MaxSrcFileSize {
return nil, ErrSourceFileTooBig
}
buf := downloadBufPool.Get(contentLength)
cancel := func() { downloadBufPool.Put(buf) }
if config.MaxSrcFileSize > 0 {
r = &hardLimitReader{r: r, left: config.MaxSrcFileSize}
}
br := bufreader.New(r, buf)
meta, err := imagemeta.DecodeMeta(br)
if err == imagemeta.ErrFormat {
return nil, ErrSourceImageTypeNotSupported
}
if err != nil {
return nil, checkTimeoutErr(err)
2021-04-26 13:52:50 +02:00
}
if err = security.CheckDimensions(meta.Width(), meta.Height()); err != nil {
return nil, err
}
if err = br.Flush(); err != nil {
cancel()
return nil, checkTimeoutErr(err)
2021-04-26 13:52:50 +02:00
}
return &ImageData{
Data: buf.Bytes(),
2021-05-13 15:58:44 +02:00
Type: meta.Format(),
2021-04-26 13:52:50 +02:00
cancel: cancel,
}, nil
}