make setproctitle()'s /proc/pid/stat parsing safe

it turns out that our parsing of /proc/pid/stat was not safe in general
(though probably safe for lxc, since our executable names do not contain
spaces).

Let's fix this by looking backwards through the file for ), and then
continuing on from there.

This was reported to me by Solar Designer, who pointed me to this thread:
https://twitter.com/solardiz/status/1634204168545001473

Indeed, this is a lot of tap dancing to work around the kernel's 16
character executable limit. Perhaps I'll send a kernel patch to raise that
limit next.

Signed-off-by: Tycho Andersen <tycho@tycho.pizza>
This commit is contained in:
Tycho Andersen 2023-04-10 17:12:24 -06:00
parent 52326514c6
commit f7f15b20a3

View File

@ -242,10 +242,17 @@ int setproctitle(char *title)
buf[bytes_read] = '\0';
/* Skip the first 25 fields, column 26-28 are start_code, end_code,
/*
* executable names may contain spaces, so we search backwards for the
* ), which is the kernel's marker for "end of executable name". this
* skips the first two fields.
*/
buf_ptr = strrchr(buf, ')')+2;
/* Skip the next 23 fields, column 26-28 are start_code, end_code,
* and start_stack */
buf_ptr = strchr(buf, ' ');
for (i = 0; i < 24; i++) {
buf_ptr = strchr(buf_ptr, ' ');
for (i = 0; i < 22; i++) {
if (!buf_ptr)
return -1;
buf_ptr = strchr(buf_ptr + 1, ' ');