meminfo-writer: make meminfo parsing more robust

- ensure we see all the expected fields
- avoid overflowing name buffer on malformed input
- avoid possible overread when the last line is small
This commit is contained in:
Vincent Penquerc'h 2013-12-26 10:34:16 -05:00 committed by Marek Marczykowski-Górecki
parent 2ba46ff17f
commit 7e086970e9

View File

@ -15,37 +15,41 @@ int usr1_received;
const char *parse(const char *buf) const char *parse(const char *buf)
{ {
const char *ptr = buf; const char *ptr = buf;
char name[256];
static char outbuf[4096]; static char outbuf[4096];
int val; int val;
int len; int len;
int ret;
int MemTotal = 0, MemFree = 0, Buffers = 0, Cached = 0, SwapTotal = int MemTotal = 0, MemFree = 0, Buffers = 0, Cached = 0, SwapTotal =
0, SwapFree = 0; 0, SwapFree = 0;
unsigned long long key; unsigned long long key;
long used_mem, used_mem_diff; long used_mem, used_mem_diff;
int nitems = 0; int nitems = 0;
while (nitems != 6) { while (nitems != (1<<6)-1 || !*ptr) {
sscanf(ptr, "%s %d kB\n%n", name, &val, &len); ret = sscanf(ptr, "%*s %d kB\n%n", &val, &len);
if (ret < 1 || len < sizeof (unsigned long long)) {
ptr += len;
continue;
}
key = *(unsigned long long *) ptr; key = *(unsigned long long *) ptr;
if (key == *(unsigned long long *) "MemTotal:") { if (key == *(unsigned long long *) "MemTotal:") {
MemTotal = val; MemTotal = val;
nitems++; nitems |= 1;
} else if (key == *(unsigned long long *) "MemFree:") { } else if (key == *(unsigned long long *) "MemFree:") {
MemFree = val; MemFree = val;
nitems++; nitems |= 2;
} else if (key == *(unsigned long long *) "Buffers:") { } else if (key == *(unsigned long long *) "Buffers:") {
Buffers = val; Buffers = val;
nitems++; nitems |= 4;
} else if (key == *(unsigned long long *) "Cached: ") { } else if (key == *(unsigned long long *) "Cached: ") {
Cached = val; Cached = val;
nitems++; nitems |= 8;
} else if (key == *(unsigned long long *) "SwapTotal:") { } else if (key == *(unsigned long long *) "SwapTotal:") {
SwapTotal = val; SwapTotal = val;
nitems++; nitems |= 16;
} else if (key == *(unsigned long long *) "SwapFree:") { } else if (key == *(unsigned long long *) "SwapFree:") {
SwapFree = val; SwapFree = val;
nitems++; nitems |= 32;
} }
ptr += len; ptr += len;