2021-04-26 17:52:50 +06:00
|
|
|
package imagedata
|
|
|
|
|
|
|
|
|
|
import (
|
2022-10-15 19:31:04 +06:00
|
|
|
"bytes"
|
|
|
|
|
"context"
|
2021-04-26 17:52:50 +06:00
|
|
|
"io"
|
|
|
|
|
|
2021-09-30 20:23:30 +06:00
|
|
|
"github.com/imgproxy/imgproxy/v3/bufpool"
|
|
|
|
|
"github.com/imgproxy/imgproxy/v3/bufreader"
|
|
|
|
|
"github.com/imgproxy/imgproxy/v3/config"
|
|
|
|
|
"github.com/imgproxy/imgproxy/v3/imagemeta"
|
|
|
|
|
"github.com/imgproxy/imgproxy/v3/security"
|
2021-04-26 17:52:50 +06:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var downloadBufPool *bufpool.Pool
|
|
|
|
|
|
|
|
|
|
func initRead() {
|
2023-08-15 19:54:42 +03:00
|
|
|
downloadBufPool = bufpool.New("download", config.Workers, config.DownloadBufferSize)
|
2021-04-26 17:52:50 +06:00
|
|
|
}
|
|
|
|
|
|
2023-02-23 21:11:44 +03: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 17:52:50 +06:00
|
|
|
}
|
|
|
|
|
|
2022-08-01 19:48:23 +06:00
|
|
|
buf := downloadBufPool.Get(contentLength, false)
|
2021-04-26 17:52:50 +06:00
|
|
|
cancel := func() { downloadBufPool.Put(buf) }
|
|
|
|
|
|
2023-02-23 21:11:44 +03:00
|
|
|
r = security.LimitFileSize(r, secopts)
|
2021-04-26 17:52:50 +06:00
|
|
|
|
|
|
|
|
br := bufreader.New(r, buf)
|
|
|
|
|
|
|
|
|
|
meta, err := imagemeta.DecodeMeta(br)
|
|
|
|
|
if err != nil {
|
2022-08-01 19:48:23 +06:00
|
|
|
buf.Reset()
|
|
|
|
|
cancel()
|
|
|
|
|
|
2023-03-21 20:58:16 +03:00
|
|
|
return nil, wrapError(err)
|
2021-04-26 17:52:50 +06:00
|
|
|
}
|
|
|
|
|
|
2023-02-23 21:11:44 +03:00
|
|
|
if err = security.CheckDimensions(meta.Width(), meta.Height(), 1, secopts); err != nil {
|
2022-08-01 19:48:23 +06:00
|
|
|
buf.Reset()
|
|
|
|
|
cancel()
|
2023-03-21 20:58:16 +03:00
|
|
|
|
|
|
|
|
return nil, wrapError(err)
|
2021-04-26 17:52:50 +06:00
|
|
|
}
|
|
|
|
|
|
2023-06-12 22:00:55 +03:00
|
|
|
downloadBufPool.GrowBuffer(buf, contentLength)
|
2022-08-01 19:48:23 +06:00
|
|
|
|
2021-04-26 17:52:50 +06:00
|
|
|
if err = br.Flush(); err != nil {
|
2023-03-21 20:58:16 +03:00
|
|
|
buf.Reset()
|
2021-04-26 17:52:50 +06:00
|
|
|
cancel()
|
2023-03-21 20:58:16 +03:00
|
|
|
|
|
|
|
|
return nil, wrapError(err)
|
2021-04-26 17:52:50 +06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return &ImageData{
|
|
|
|
|
Data: buf.Bytes(),
|
2021-05-13 19:58:44 +06:00
|
|
|
Type: meta.Format(),
|
2021-04-26 17:52:50 +06:00
|
|
|
cancel: cancel,
|
|
|
|
|
}, nil
|
|
|
|
|
}
|
2022-10-15 19:31:04 +06:00
|
|
|
|
|
|
|
|
func BorrowBuffer() (*bytes.Buffer, context.CancelFunc) {
|
|
|
|
|
buf := downloadBufPool.Get(0, false)
|
|
|
|
|
cancel := func() { downloadBufPool.Put(buf) }
|
|
|
|
|
|
|
|
|
|
return buf, cancel
|
|
|
|
|
}
|