Skip to content

Commit

Permalink
main: fix some leaks on error paths
Browse files Browse the repository at this point in the history
Signed-off-by: Giuseppe Scrivano <[email protected]>
  • Loading branch information
giuseppe committed Feb 6, 2024
1 parent a6c3eb7 commit f5287ef
Showing 1 changed file with 28 additions and 11 deletions.
39 changes: 28 additions & 11 deletions main.c
Original file line number Diff line number Diff line change
Expand Up @@ -42,41 +42,58 @@ static int nsenter(pid_t target_pid, char *netns, char *userns,
bool only_userns)
{
int usernsfd = -1, netnsfd = -1;
char *netns_allocated = NULL;
char *userns_allocated = NULL;

if (!only_userns && !netns) {
if (asprintf(&netns, "/proc/%d/ns/net", target_pid) < 0) {
if (asprintf(&netns_allocated, "/proc/%d/ns/net", target_pid) < 0) {
perror("cannot get netns path");
return -1;
goto fail;
}
netns = netns_allocated;
}
if (!userns && target_pid) {
if (asprintf(&userns, "/proc/%d/ns/user", target_pid) < 0) {
if (asprintf(&userns_allocated, "/proc/%d/ns/user", target_pid) < 0) {
perror("cannot get userns path");
return -1;
goto fail;
}
userns = userns_allocated;
}
if (!only_userns && (netnsfd = open(netns, O_RDONLY)) < 0) {
perror(netns);
return netnsfd;
goto fail;
}
if (userns && (usernsfd = open(userns, O_RDONLY)) < 0) {
perror(userns);
return usernsfd;
goto fail;
}

if (usernsfd != -1) {
int r = setns(usernsfd, CLONE_NEWUSER);
if (only_userns && r < 0) {
perror("setns(CLONE_NEWUSER)");
return -1;
goto fail;
}
close(usernsfd);
usernsfd = -1;
}
if (netnsfd != -1 && setns(netnsfd, CLONE_NEWNET) < 0) {
perror("setns(CLONE_NEWNET)");
return -1;
if (netnsfd != -1) {
if (setns(netnsfd, CLONE_NEWNET) < 0) {
perror("setns(CLONE_NEWNET)");
goto fail;
}
close(netnsfd);
}
close(netnsfd);
return 0;
fail:
free(netns_allocated);
free(userns_allocated);

if (usernsfd != -1)
close(usernsfd);
if (netnsfd != -1)
close(netnsfd);
return -1;
}

static int open_tap(const char *tapname)
Expand Down

0 comments on commit f5287ef

Please sign in to comment.