mirror of
https://github.com/troglobit/finit.git
synced 2026-10-22 11:36:07 +00:00
util: one whole-file reader for all tools
Three private ones had grown: fnread() in util.c, flen() behind pid_cmdline()/pid_cgroup() in cgutil.c, and conf_read_template() in conf.c. Two of them were also wrong in ways the others were not. fnread() formatted the path into a char[256] and stat()ed it before opening, so a longer path was silently truncated and then read from whichever file the truncation happened to name, and the size could change between the look and the read. flen() existed because neither of those approaches works on procfs at all, where stat() reports zero and the only way to learn the size is to read to EOF. Add fslurp() to util.[ch], which every tool already links. It opens first and sizes the fd it holds, treats st_size as a hint, and reads until EOF, so procfs and regular files take the same path. Paths are formatted by libite's vfopenf(), which allocates to fit. Callers that need the byte count, /proc/PID/cmdline embeds NUL, ask for it. fnread() keeps its signature and becomes a bounded copy out of the result, so its one caller is unaffected. Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
This commit is contained in:
4 files changed
+115
-92
No files matched your search
+4
-21
@@ -1660,30 +1660,13 @@ static int is_new_format(char *file, char *buf)
|
||||
*/
|
||||
static char *conf_read_template(char *file, char *name)
|
||||
{
|
||||
struct stat st;
|
||||
char *buf = NULL;
|
||||
size_t len;
|
||||
FILE *fp;
|
||||
char *buf;
|
||||
|
||||
fp = fopen(file, "r");
|
||||
if (!fp)
|
||||
buf = fslurp(NULL, "%s", file);
|
||||
if (!buf)
|
||||
return NULL;
|
||||
|
||||
/* fstat() the open fd, no window for the file to change under us */
|
||||
if (fstat(fileno(fp), &st) || st.st_size < 0)
|
||||
goto out;
|
||||
|
||||
buf = malloc((size_t)st.st_size + 1);
|
||||
if (!buf)
|
||||
goto out;
|
||||
|
||||
len = fread(buf, 1, (size_t)st.st_size, fp);
|
||||
buf[len] = 0;
|
||||
buf = conf_instantiate(buf, name);
|
||||
out:
|
||||
fclose(fp);
|
||||
|
||||
return buf;
|
||||
return conf_instantiate(buf, name);
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
Reference in new issue
Block a user