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

76 lines
1.7 KiB
Go
Raw Normal View History

2021-04-26 13:52:50 +02:00
package imagedata
import (
"bytes"
"context"
2021-04-26 13:52:50 +02:00
"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
)
2023-02-23 20:11:44 +02:00
var ErrSourceImageTypeNotSupported = ierrors.New(422, "Source image type not supported", "Invalid source image")
2021-04-26 13:52:50 +02:00
var downloadBufPool *bufpool.Pool
func initRead() {
downloadBufPool = bufpool.New("download", config.Concurrency, config.DownloadBufferSize)
}
2023-02-23 20:11:44 +02:00
func readAndCheckImage(r io.Reader, contentLength int, secopts security.Options) (*ImageData, error) {
if err := security.CheckFileSize(contentLength, secopts); err != nil {
return nil, err
2021-04-26 13:52:50 +02:00
}
2022-08-01 15:48:23 +02:00
buf := downloadBufPool.Get(contentLength, false)
2021-04-26 13:52:50 +02:00
cancel := func() { downloadBufPool.Put(buf) }
2023-02-23 20:11:44 +02:00
r = security.LimitFileSize(r, secopts)
2021-04-26 13:52:50 +02:00
br := bufreader.New(r, buf)
meta, err := imagemeta.DecodeMeta(br)
if err != nil {
2022-08-01 15:48:23 +02:00
buf.Reset()
cancel()
if err == imagemeta.ErrFormat {
return nil, ErrSourceImageTypeNotSupported
}
return nil, checkTimeoutErr(err)
2021-04-26 13:52:50 +02:00
}
2023-02-23 20:11:44 +02:00
if err = security.CheckDimensions(meta.Width(), meta.Height(), 1, secopts); err != nil {
2022-08-01 15:48:23 +02:00
buf.Reset()
cancel()
2021-04-26 13:52:50 +02:00
return nil, err
}
2022-08-01 15:48:23 +02:00
if contentLength > buf.Cap() {
buf.Grow(contentLength - buf.Len())
}
2021-04-26 13:52:50 +02:00
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
}
func BorrowBuffer() (*bytes.Buffer, context.CancelFunc) {
buf := downloadBufPool.Get(0, false)
cancel := func() { downloadBufPool.Put(buf) }
return buf, cancel
}