mirror of
https://github.com/aquasecurity/trivy.git
synced 2026-01-31 13:53:14 +08:00
fix: close file descriptors and pipes on error paths (#9536)
Co-authored-by: knqyf263 <knqyf263@users.noreply.github.com>
This commit is contained in:
@@ -35,12 +35,19 @@ type ImageFile struct {
|
||||
reader *io.SectionReader
|
||||
}
|
||||
|
||||
func newFile(filePath string, storage Storage) (*ImageFile, error) {
|
||||
func newFile(filePath string, storage Storage) (imgFile *ImageFile, err error) {
|
||||
f, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("file open error: %w", err)
|
||||
}
|
||||
|
||||
// Close file on error
|
||||
defer func() {
|
||||
if err != nil && f != nil {
|
||||
f.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := lru.New[string, []byte](storageFILECacheSize)
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("failed to create new lru cache: %w", err)
|
||||
|
||||
@@ -579,10 +579,23 @@ func (o *Options) GetUsedFlags() []Flagger {
|
||||
return o.usedFlags
|
||||
}
|
||||
|
||||
func (o *Options) outputPluginWriter(ctx context.Context) (io.Writer, func() error, error) {
|
||||
func (o *Options) outputPluginWriter(ctx context.Context) (writer io.Writer, cleanup func() error, err error) {
|
||||
pluginName := strings.TrimPrefix(o.Output, "plugin=")
|
||||
|
||||
pr, pw := io.Pipe()
|
||||
|
||||
// Close pipes on error
|
||||
defer func() {
|
||||
if err != nil {
|
||||
if pr != nil {
|
||||
pr.Close()
|
||||
}
|
||||
if pw != nil {
|
||||
pw.Close()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
wait, err := plugin.Start(ctx, pluginName, plugin.Options{
|
||||
Args: o.OutputPluginArgs,
|
||||
Stdin: pr,
|
||||
@@ -591,7 +604,7 @@ func (o *Options) outputPluginWriter(ctx context.Context) (io.Writer, func() err
|
||||
return nil, nil, xerrors.Errorf("plugin start: %w", err)
|
||||
}
|
||||
|
||||
cleanup := func() error {
|
||||
cleanup = func() error {
|
||||
if err = pw.Close(); err != nil {
|
||||
return xerrors.Errorf("failed to close pipe: %w", err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user