From 778124a56c515b90e2ea52951666bc119a9aae08 Mon Sep 17 00:00:00 2001 From: Matt Layher Date: Sat, 27 Oct 2018 03:21:36 -0400 Subject: [PATCH] collector: add bounds check and test for tcpstat collector (#1134) Signed-off-by: Matt Layher --- collector/tcpstat_linux.go | 4 ++++ collector/tcpstat_linux_test.go | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/collector/tcpstat_linux.go b/collector/tcpstat_linux.go index 0a5f59f1..da652f97 100644 --- a/collector/tcpstat_linux.go +++ b/collector/tcpstat_linux.go @@ -118,6 +118,10 @@ func parseTCPStats(r io.Reader) (map[tcpConnectionState]float64, error) { if len(parts) == 0 { continue } + if len(parts) < 4 { + return nil, fmt.Errorf("invalid TCP stats line: %q", scanner.Text()) + } + if strings.HasPrefix(parts[0], "sl") { continue } diff --git a/collector/tcpstat_linux_test.go b/collector/tcpstat_linux_test.go index 806ca223..ca9d9944 100644 --- a/collector/tcpstat_linux_test.go +++ b/collector/tcpstat_linux_test.go @@ -15,9 +15,30 @@ package collector import ( "os" + "strings" "testing" ) +func Test_parseTCPStatsError(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 := parseTCPStats(strings.NewReader(tt.in)); err == nil { + t.Fatal("expected an error, but none occurred") + } + }) + } +} + func TestTCPStat(t *testing.T) { file, err := os.Open("fixtures/proc/net/tcpstat") if err != nil {