read.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package imagedata
  2. import (
  3. "bytes"
  4. "context"
  5. "io"
  6. "github.com/imgproxy/imgproxy/v3/bufpool"
  7. "github.com/imgproxy/imgproxy/v3/bufreader"
  8. "github.com/imgproxy/imgproxy/v3/config"
  9. "github.com/imgproxy/imgproxy/v3/ierrors"
  10. "github.com/imgproxy/imgproxy/v3/imagemeta"
  11. "github.com/imgproxy/imgproxy/v3/security"
  12. )
  13. var ErrSourceImageTypeNotSupported = ierrors.New(422, "Source image type not supported", "Invalid source image")
  14. var downloadBufPool *bufpool.Pool
  15. func initRead() {
  16. downloadBufPool = bufpool.New("download", config.Workers, config.DownloadBufferSize)
  17. }
  18. func readAndCheckImage(r io.Reader, contentLength int, secopts security.Options) (*ImageData, error) {
  19. if err := security.CheckFileSize(contentLength, secopts); err != nil {
  20. return nil, err
  21. }
  22. buf := downloadBufPool.Get(contentLength, false)
  23. cancel := func() { downloadBufPool.Put(buf) }
  24. r = security.LimitFileSize(r, secopts)
  25. br := bufreader.New(r, buf)
  26. meta, err := imagemeta.DecodeMeta(br)
  27. if err != nil {
  28. buf.Reset()
  29. cancel()
  30. if err == imagemeta.ErrFormat {
  31. return nil, ErrSourceImageTypeNotSupported
  32. }
  33. return nil, wrapError(err)
  34. }
  35. if err = security.CheckDimensions(meta.Width(), meta.Height(), 1, secopts); err != nil {
  36. buf.Reset()
  37. cancel()
  38. return nil, wrapError(err)
  39. }
  40. downloadBufPool.GrowBuffer(buf, contentLength)
  41. if err = br.Flush(); err != nil {
  42. buf.Reset()
  43. cancel()
  44. return nil, wrapError(err)
  45. }
  46. return &ImageData{
  47. Data: buf.Bytes(),
  48. Type: meta.Format(),
  49. cancel: cancel,
  50. }, nil
  51. }
  52. func BorrowBuffer() (*bytes.Buffer, context.CancelFunc) {
  53. buf := downloadBufPool.Get(0, false)
  54. cancel := func() { downloadBufPool.Put(buf) }
  55. return buf, cancel
  56. }