Skip to content

Commit

Permalink
Read into a buffer of 1MB to limit reading huge files
Browse files Browse the repository at this point in the history
  • Loading branch information
francislavoie committed Mar 27, 2023
1 parent 72f3171 commit 52459de
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions replacer.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package caddy

import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
Expand Down Expand Up @@ -303,14 +304,11 @@ func globalDefaultReplacements(key string) (any, bool) {
}

// check files
// TODO: We may want to cache the file contents in case
// this is used in a hot path in a config. But for now,
// we'll just read the file every time, the kernel will
// tend to cache the file contents for us.
const filePrefix = "file."
if strings.HasPrefix(key, filePrefix) {
filename := key[len(filePrefix):]
body, err := os.ReadFile(filename)
maxSize := 1024 * 1024
body, err := readFileIntoBuffer(filename, maxSize)
if err != nil {
wd, _ := os.Getwd()
Log().Error("placeholder: failed to read file",
Expand Down Expand Up @@ -354,6 +352,24 @@ func globalDefaultReplacements(key string) (any, bool) {
return nil, false
}

// readFileIntoBuffer reads the file at filePath into a size limited buffer.
func readFileIntoBuffer(filename string, size int) ([]byte, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()

buffer := make([]byte, size)
n, err := file.Read(buffer)
if err != nil && err != io.EOF {
return nil, err
}

// slice the buffer to the actual size
return buffer[:n], nil
}

// ReplacementFunc is a function that is called when a
// replacement is being performed. It receives the
// variable (i.e. placeholder name) and the value that
Expand Down

0 comments on commit 52459de

Please sign in to comment.