Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix fd leaks in fdopendir #29

Merged
merged 1 commit into from
Sep 4, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions src/fdopendir.c
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ int best_fchdir(int dirfd);

#define PROTECT_ERRNO(what) ({ int __err = (errno); what; errno = __err; })

/*
* Implementation behavior largely follows these man page descriptions:
*
* https://www.freebsd.org/cgi/man.cgi?query=fdopendir&sektion=3
* https://linux.die.net/man/3/fdopendir
*/

michaelld marked this conversation as resolved.
Show resolved Hide resolved
DIR *fdopendir(int dirfd) {
DIR *dir;
struct stat st;
Expand All @@ -43,8 +50,12 @@ DIR *fdopendir(int dirfd) {
return 0;
}

if (dirfd == AT_FDCWD)
return opendir (".");
if (dirfd == AT_FDCWD) {
dir = opendir (".");
/* dirfd can be closed only upon success */
if (dir) PROTECT_ERRNO(close(dirfd));
return dir;
}

oldCWD = open(".", O_RDONLY);
if (oldCWD == -1)
Expand All @@ -58,13 +69,17 @@ DIR *fdopendir(int dirfd) {
dir = opendir (".");

if (best_fchdir(oldCWD) < 0) {
if (dir) PROTECT_ERRNO(closedir(dir));
if (oldCWD != -1) PROTECT_ERRNO(close(oldCWD));
return 0;
}

if (oldCWD != -1)
PROTECT_ERRNO(close(oldCWD));

/* dirfd can be closed only upon success */
if (dir && dirfd != -1) PROTECT_ERRNO(close(dirfd));

return dir;
}

Expand Down