From c0a55e3f80d803e3d596c11ae50fce1ce391d729 Mon Sep 17 00:00:00 2001 From: Matt Layher Date: Tue, 30 Oct 2018 17:12:42 -0400 Subject: [PATCH] collector: add bounds check and test for filesystem collector (#1133) Signed-off-by: Matt Layher --- collector/filesystem_linux.go | 16 ++++++++++++++-- collector/filesystem_linux_test.go | 21 +++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/collector/filesystem_linux.go b/collector/filesystem_linux.go index 65614a97..9cada1e9 100644 --- a/collector/filesystem_linux.go +++ b/collector/filesystem_linux.go @@ -17,6 +17,8 @@ package collector import ( "bufio" + "fmt" + "io" "os" "strings" "sync" @@ -139,11 +141,20 @@ func mountPointDetails() ([]filesystemLabels, error) { } defer file.Close() - filesystems := []filesystemLabels{} - scanner := bufio.NewScanner(file) + return parseFilesystemLabels(file) +} + +func parseFilesystemLabels(r io.Reader) ([]filesystemLabels, error) { + var filesystems []filesystemLabels + + scanner := bufio.NewScanner(r) for scanner.Scan() { parts := strings.Fields(scanner.Text()) + if len(parts) < 4 { + return nil, fmt.Errorf("malformed mount point information: %q", scanner.Text()) + } + // Ensure we handle the translation of \040 and \011 // as per fstab(5). parts[1] = strings.Replace(parts[1], "\\040", " ", -1) @@ -156,5 +167,6 @@ func mountPointDetails() ([]filesystemLabels, error) { options: parts[3], }) } + return filesystems, scanner.Err() } diff --git a/collector/filesystem_linux_test.go b/collector/filesystem_linux_test.go index 2b0a848b..17c2d165 100644 --- a/collector/filesystem_linux_test.go +++ b/collector/filesystem_linux_test.go @@ -16,11 +16,32 @@ package collector import ( + "strings" "testing" kingpin "gopkg.in/alecthomas/kingpin.v2" ) +func Test_parseFilesystemLabelsError(t *testing.T) { + tests := []struct { + name string + in string + }{ + { + name: "too few fields", + in: "hello world", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if _, err := parseFilesystemLabels(strings.NewReader(tt.in)); err == nil { + t.Fatal("expected an error, but none occurred") + } + }) + } +} + func TestMountPointDetails(t *testing.T) { if _, err := kingpin.CommandLine.Parse([]string{"--path.procfs", "./fixtures/proc"}); err != nil { t.Fatal(err)