From af08077fb4c60dee516948ce7bf9bed91de62119 Mon Sep 17 00:00:00 2001
From: Panu Matilainen <pmatilai@redhat.com>
Date: Tue, 13 Sep 2022 10:26:05 +0300
Subject: [PATCH] Fix possible descriptor leak in fsmOpenat()

For the very unlikely case when openat() succeeded but fstatat()
doesn't, the directory descriptor may be leaved opened. Rearrange
the code a bit to ensure it'll always get closed when appropriate.

Suggested-by: Pavel Kopylov <pkopylov@cloudlinux.com>
Suggested-by: Dmitry Antipov <dantipov@cloudlinux.com>
---
 lib/fsm.c | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)

diff --git a/lib/fsm.c b/lib/fsm.c
index e4ec07e..c9ab3e1 100644
--- a/lib/fsm.c
+++ b/lib/fsm.c
@@ -427,14 +427,16 @@ static int fsmOpenat(int dirfd, const char *path, int flags)
      */
     if (fd < 0 && errno == ELOOP && flags != sflags) {
 	int ffd = openat(dirfd, path, flags);
-	if (ffd >= 0 && fstatat(dirfd, path, &lsb, AT_SYMLINK_NOFOLLOW) == 0) {
-	    if (fstat(ffd, &sb) == 0) {
-		if (lsb.st_uid == 0 || lsb.st_uid == sb.st_uid) {
-		    fd = ffd;
-		} else {
-		    close(ffd);
+	if (ffd >= 0) {
+	    if (fstatat(dirfd, path, &lsb, AT_SYMLINK_NOFOLLOW) == 0) {
+		if (fstat(ffd, &sb) == 0) {
+		    if (lsb.st_uid == 0 || lsb.st_uid == sb.st_uid) {
+			fd = ffd;
+		    }
 		}
 	    }
+	    if (ffd != fd)
+		close(ffd);
 	}
     }
     return fd;
-- 
2.33.0

