Skip to content

fix: Memory leak caused by openFile and osOpen functions #102

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (
//nolint:gochecknoglobals
var (
hasMagic = regexp.MustCompile(`[*?[]`)
osOpen = func(path string) (io.Reader, error) { return os.Open(path) }
osOpen = func(path string) (io.ReadCloser, error) { return os.Open(path) }
ErrPrematureLexEnd = errors.New("premature end of file")
)

Expand Down Expand Up @@ -74,7 +74,7 @@ type ParseOptions struct {
ErrorCallback func(error) interface{}

// If specified, use this alternative to open config files
Open func(path string) (io.Reader, error)
Open func(path string) (io.ReadCloser, error)

// Glob will return a matching list of files if specified
Glob func(path string) ([]string, error)
Expand Down Expand Up @@ -167,6 +167,8 @@ func Parse(filename string, options *ParseOptions) (*Payload, error) {
return nil, err
}

defer file.Close()

tokens := LexWithOptions(file, options.LexOptions)
config := Config{
File: incl.path,
Expand Down Expand Up @@ -198,7 +200,7 @@ func Parse(filename string, options *ParseOptions) (*Payload, error) {
return payload, nil
}

func (p *parser) openFile(path string) (io.Reader, error) {
func (p *parser) openFile(path string) (io.ReadCloser, error) {
open := osOpen
if p.options.Open != nil {
open = p.options.Open
Expand Down Expand Up @@ -383,6 +385,7 @@ func (p *parser) parse(parsing *Config, tokens <-chan NgxToken, ctx blockCtx, co
// if the file pattern was explicit, nginx will check
// that the included file can be opened and read
if f, err := p.openFile(pattern); err != nil {
defer f.Close()
perr := &ParseError{
What: err.Error(),
File: &parsing.File,
Expand All @@ -396,9 +399,6 @@ func (p *parser) parse(parsing *Config, tokens <-chan NgxToken, ctx blockCtx, co
return nil, perr
}
} else {
if c, ok := f.(io.Closer); ok {
_ = c.Close()
}
fnames = []string{pattern}
}
}
Expand Down
Loading