From 0de587f47ede7e433d426e90b645f89669b8094b Mon Sep 17 00:00:00 2001 From: Nick Mathewson Date: Mon, 25 Jun 2012 12:19:26 -0400 Subject: [PATCH] Simplify and correct evutil_open_closeonexec_ The original code needlessly called open in its two- or three- argument format depending on the O_CREAT flag; this should not be needed. The code also leaked an fd if fcntl() failed. Reported by Dave Hart. --- evutil.c | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/evutil.c b/evutil.c index bc4ee99e..352649f7 100644 --- a/evutil.c +++ b/evutil.c @@ -99,24 +99,20 @@ evutil_open_closeonexec_(const char *pathname, int flags, unsigned mode) int fd; #ifdef O_CLOEXEC - if (flags & O_CREAT) - fd = open(pathname, flags|O_CLOEXEC, (mode_t)mode); - else - fd = open(pathname, flags|O_CLOEXEC); + fd = open(pathname, flags|O_CLOEXEC, (mode_t)mode); if (fd >= 0 || errno == EINVAL) return fd; /* If we got an EINVAL, fall through and try without O_CLOEXEC */ #endif - if (flags & O_CREAT) - fd = open(pathname, flags, (mode_t)mode); - else - fd = open(pathname, flags); + fd = open(pathname, flags, (mode_t)mode); if (fd < 0) return -1; #if defined(FD_CLOEXEC) - if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) + if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) { + close(fd); return -1; + } #endif return fd; -- 2.50.1