lib/fs: Fix single return points for get_cgroup2_*

Functions get_cgroup2_id() and get_cgroup2_path() may call close() with
a negative argument.
Avoid that making the calls conditional on the file descriptors.

get_cgroup2_path() may also return NULL leaking a file descriptor.
Ensure this does not happen using a single return point.

Fixes: d5e6ee0dac ("ss: introduce cgroup2 cache and helper functions")
Fixes: 8f1cd119b3 ("lib: fix checking of returned file handle size for cgroup")
Signed-off-by: Andrea Claudi <aclaudi@redhat.com>
Signed-off-by: Stephen Hemminger <stephen@networkplumber.org>
This commit is contained in:
Andrea Claudi 2021-02-22 19:14:32 +01:00 committed by Stephen Hemminger
parent 1de363b180
commit b2d44b9a95
1 changed files with 9 additions and 6 deletions

View File

@ -157,6 +157,7 @@ __u64 get_cgroup2_id(const char *path)
memcpy(cg_id.bytes, fhp->f_handle, sizeof(__u64)); memcpy(cg_id.bytes, fhp->f_handle, sizeof(__u64));
out: out:
if (mnt_fd >= 0)
close(mnt_fd); close(mnt_fd);
free(mnt); free(mnt);
@ -179,16 +180,16 @@ char *get_cgroup2_path(__u64 id, bool full)
char *path = NULL; char *path = NULL;
char fd_path[64]; char fd_path[64];
int link_len; int link_len;
char *mnt; char *mnt = NULL;
if (!id) { if (!id) {
fprintf(stderr, "Invalid cgroup2 ID\n"); fprintf(stderr, "Invalid cgroup2 ID\n");
return NULL; goto out;
} }
mnt = find_cgroup2_mount(false); mnt = find_cgroup2_mount(false);
if (!mnt) if (!mnt)
return NULL; goto out;
mnt_fd = open(mnt, O_RDONLY); mnt_fd = open(mnt, O_RDONLY);
if (mnt_fd < 0) { if (mnt_fd < 0) {
@ -225,7 +226,9 @@ char *get_cgroup2_path(__u64 id, bool full)
"Failed to allocate memory for cgroup2 path\n"); "Failed to allocate memory for cgroup2 path\n");
out: out:
if (fd >= 0)
close(fd); close(fd);
if (mnt_fd >= 0)
close(mnt_fd); close(mnt_fd);
free(mnt); free(mnt);