From b8c4094cd512dd48015255052170af337db32fc9 Mon Sep 17 00:00:00 2001
From: Ning Yu <nyu@pivotal.io>
Date: Tue, 23 Jul 2019 14:27:20 +0800
Subject: [PATCH v1 4/4] Fix callers of MakePGDirectory()

MakePGDirectory() is a wrapper of mkdir(), when it returns -1 and sets
errno to EEXIST it means that the path already exists, but that does not
means it is a directory, we need to double check with stat().

Co-authored-by: Paul Guo <pguo@pivotal.io>
Co-authored-by: Ning Yu <nyu@pivotal.io>
---
 src/backend/storage/file/fd.c | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)

diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index 315c74c745..5059802c7f 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -1399,11 +1399,10 @@ PathNameOpenFilePerm(const char *fileName, int fileFlags, mode_t fileMode)
 void
 PathNameCreateTemporaryDir(const char *basedir, const char *directory)
 {
+	struct stat statbuf;
+
 	if (MakePGDirectory(directory) < 0)
 	{
-		if (errno == EEXIST)
-			return;
-
 		/*
 		 * Failed.  Try to create basedir first in case it's missing. Tolerate
 		 * EEXIST to close a race against another process following the same
@@ -1422,6 +1421,17 @@ PathNameCreateTemporaryDir(const char *basedir, const char *directory)
 					 errmsg("cannot create temporary subdirectory \"%s\": %m",
 							directory)));
 	}
+
+	if (stat(directory, &statbuf) < 0)
+		ereport(ERROR,
+				(errcode_for_file_access(),
+				 errmsg("cannot stat temporary subdirectory \"%s\": %m",
+						directory)));
+	else if (!S_ISDIR(statbuf.st_mode))
+		ereport(ERROR,
+				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
+				 errmsg("\"%s\" is not a directory",
+						directory)));
 }
 
 /*
-- 
2.20.1

