Skip to content

eBPF-based security platform

sysinfo: read /proc/meminfo without sscanf()

Daniel Borkmann4b0b4719d456
diff --git a/testing/unit/sysinfo.c b/testing/unit/sysinfo.c
index 3598dd50..95d22654 100644
--- a/testing/unit/sysinfo.c
+++ b/testing/unit/sysinfo.c
@@ -293,6 +293,16 @@ static void command_line_that_does_not_fit_is_absent(void)
EXPECT_STREQ(img.root, "");
}
+static void memory_of_this_host_is_read(void)
+{
+ struct sysinfo si;
+
+ sysinfo_gather(&si);
+ EXPECT_GT(si.mem_total_kb, 0);
+ EXPECT_TRUE(si.mem_avail_kb >= 0 &&
+ si.mem_avail_kb <= si.mem_total_kb);
+}
+
static const struct unit_case cases[] = {
UNIT_CASE(unquoted_values_are_copied),
UNIT_CASE(one_pair_of_matching_quotes_is_stripped),
@@ -311,6 +321,7 @@ static const struct unit_case cases[] = {
UNIT_CASE(malformed_roothash_does_not_fall_back_to_usrhash),
UNIT_CASE(no_hash_is_absent),
UNIT_CASE(command_line_that_does_not_fit_is_absent),
+ UNIT_CASE(memory_of_this_host_is_read),
{}
};
diff --git a/util/sysinfo.c b/util/sysinfo.c
index 44a07da5..7922ba63 100644
--- a/util/sysinfo.c
+++ b/util/sysinfo.c
@@ -145,6 +145,21 @@ static long read_uptime_sec(void)
return (long)sec;
}
+/* The number of a "<name> <n> kB" line of /proc/meminfo, or -1. */
+static long meminfo_kb(const char *line, const char *name)
+{
+ const char *p = str_after_prefix(line, name);
+ __u64 kb;
+
+ if (!p)
+ return -1;
+ while (*p == ' ' || *p == '\t')
+ p++;
+ if (parse_u64(p, digits(p, strlen(p)), LONG_MAX, &kb))
+ return -1;
+ return (long)kb;
+}
+
static void read_mem(long *total_kb, long *avail_kb)
{
char line[256];
@@ -156,14 +171,10 @@ static void read_mem(long *total_kb, long *avail_kb)
if (!f)
return;
while (fgets(line, sizeof(line), f)) {
- long kb;
-
- if (*total_kb < 0 &&
- sscanf(line, "MemTotal: %ld kB", &kb) == 1)
- *total_kb = kb;
- else if (*avail_kb < 0 &&
- sscanf(line, "MemAvailable: %ld kB", &kb) == 1)
- *avail_kb = kb;
+ if (*total_kb < 0)
+ *total_kb = meminfo_kb(line, "MemTotal:");
+ if (*avail_kb < 0)
+ *avail_kb = meminfo_kb(line, "MemAvailable:");
if (*total_kb >= 0 && *avail_kb >= 0)
break;
}