From 13546aa4058d6f64363a4ff5d8382ed5ee2ddc52 Mon Sep 17 00:00:00 2001 From: DarthSim Date: Wed, 22 Apr 2020 19:02:05 +0600 Subject: [PATCH] Fix unhandled panics during animated images processing --- panic_group.go | 39 +++++++++++++++++++++++++++++++++++++++ process.go | 15 ++++++--------- 2 files changed, 45 insertions(+), 9 deletions(-) create mode 100644 panic_group.go diff --git a/panic_group.go b/panic_group.go new file mode 100644 index 00000000..78a24c41 --- /dev/null +++ b/panic_group.go @@ -0,0 +1,39 @@ +package main + +import "sync" + +type panicGroup struct { + wg sync.WaitGroup + errOnce sync.Once + err error +} + +func (g *panicGroup) Wait() error { + g.wg.Wait() + return g.err +} + +func (g *panicGroup) Go(f func() error) { + g.wg.Add(1) + + go func() { + defer g.wg.Done() + defer func() { + if r := recover(); r != nil { + if err, ok := r.(error); ok { + g.errOnce.Do(func() { + g.err = err + }) + } else { + panic(r) + } + } + }() + + if err := f(); err != nil { + g.errOnce.Do(func() { + g.err = err + }) + } + }() +} diff --git a/process.go b/process.go index 9cf7a13c..a70293ac 100644 --- a/process.go +++ b/process.go @@ -8,7 +8,6 @@ import ( "runtime" "github.com/imgproxy/imgproxy/v2/imagemeta" - "golang.org/x/sync/errgroup" ) const msgSmartCropNotSupported = "Smart crop is not supported by used version of libvips" @@ -546,23 +545,21 @@ func transformAnimated(ctx context.Context, img *vipsImage, data []byte, po *pro po.Watermark.Enabled = false defer func() { po.Watermark.Enabled = watermarkEnabled }() - var errg errgroup.Group + var errg panicGroup for i := 0; i < framesCount; i++ { ind := i errg.Go(func() error { - frame := new(vipsImage) + frames[ind] = new(vipsImage) - if err = img.Extract(frame, 0, ind*frameHeight, imgWidth, frameHeight); err != nil { - return err + if ferr := img.Extract(frames[ind], 0, ind*frameHeight, imgWidth, frameHeight); ferr != nil { + return ferr } - if err = transformImage(ctx, frame, nil, po, imgtype); err != nil { - return err + if ferr := transformImage(ctx, frames[ind], nil, po, imgtype); ferr != nil { + return ferr } - frames[ind] = frame - return nil }) }