mkhtemp: PROPER fd leak/overwrite fix

now this code should be stable. no leaks.

yes. hardened mkhtemp. oh yeah mate.

now all i need is a main() and a getopt
loop, and pledge, unveil, and blackjack,
and something dubious of a titilating
nature.

Signed-off-by: Leah Rowe <leah@libreboot.org>
This commit is contained in:
Leah Rowe
2026-03-23 09:14:41 +00:00
parent 8261553818
commit ba80191b78
2 changed files with 17 additions and 43 deletions

View File

@@ -1997,25 +1997,22 @@ int
fs_resolve_at(int dirfd, const char *path, int flags)
{
int nextfd = -1;
int curfd;
const char *p;
char name[256]; /* TODO: make configurable */
char name[256];
int saved_errno = errno;
int saved_close_errno;
int r;
int is_last;
if (dirfd < 0 ||
path == NULL ||
*path == '\0') {
if (dirfd < 0 || path == NULL || *path == '\0') {
errno = EINVAL;
return -1;
}
p = path;
curfd = dirfd; /* start here */
for (;;) {
r = fs_next_component(&p, name, sizeof(name));
if (r < 0)
goto err;
@@ -2024,55 +2021,32 @@ fs_resolve_at(int dirfd, const char *path, int flags)
is_last = (*p == '\0');
nextfd = fs_open_component(dirfd,
name, flags, is_last);
nextfd = fs_open_component(curfd, name, flags, is_last);
if (nextfd < 0)
goto err;
/*
don't close fd.
it's used next by a few functions.
this results in a fd leak, but
makes the code work:
in practise, your program
will free all descriptors
on exit
/* close previous fd IF it is not the original input */
if (curfd != dirfd) {
(void) close_on_eintr(curfd);
}
what we need to do is figure out a proper
system of storing descriptors,
and freeing them when it's safe;
see how this function is called
and whatt calls those and you see what i mean
who owns what is currently not consistent.
needs rework.
this will be fixed at a later date.
justt leaving thtis in here for future me.
with this uncommented, i always just get
"Bad file descriptor" error:
saved_close_errno = errno;
(void) close_on_eintr(dirfd);
errno = saved_close_errno;
*/
dirfd = nextfd;
curfd = nextfd;
nextfd = -1;
}
errno = saved_errno;
return dirfd;
return curfd;
err:
saved_errno = errno;
if (dirfd >= 0)
(void) close_on_eintr(dirfd);
if (nextfd >= 0)
(void) close_on_eintr(nextfd);
/* close curfd only if it's not the original */
if (curfd != dirfd && curfd >= 0)
(void) close_on_eintr(curfd);
errno = saved_errno;
return -1;
}

View File

@@ -38,11 +38,11 @@ main(int argc, char *argv[])
int rval;
char *test = NULL;
int fd = -1;
rval = new_tmpfile(&fd, &test);
rval = new_tmpdir(&fd, &test);
if (rval < 0)
err_no_cleanup(errno, "TESTERR: ");
printf("TEST: %s", test);
printf("TEST: %s\n", test);
exit(1);
/* https://man.openbsd.org/pledge.2