From 816027e6856e6243697127a3c35693abf66301bd Mon Sep 17 00:00:00 2001 From: Paul Guo Date: Thu, 20 May 2021 04:28:09 +0800 Subject: [PATCH v1] Fix pg_rewind failure due to read only file open() error. The error message is "Permission denied" since open_target_file()->open() fails with O_WRONLY for read only file. This issue could be simply fixed by adding the write permission before open() and removing the permission after open(). --- src/bin/pg_rewind/file_ops.c | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/bin/pg_rewind/file_ops.c b/src/bin/pg_rewind/file_ops.c index c50f283ede..ef5d1fccca 100644 --- a/src/bin/pg_rewind/file_ops.c +++ b/src/bin/pg_rewind/file_ops.c @@ -64,8 +64,25 @@ open_target_file(const char *path, bool trunc) mode |= O_TRUNC; dstfd = open(dstpath, mode, pg_file_create_mode); if (dstfd < 0) - pg_fatal("could not open target file \"%s\": %m", - dstpath); + { + if (errno == EACCES) + { + struct stat buf; + + /* For read-only file, open() needs the write permission on the file. */ + if (stat(dstpath, &buf) == 0 && + !(buf.st_mode & S_IWUSR) && + chmod(dstpath, buf.st_mode | S_IWUSR) == 0) + { + dstfd = open(dstpath, mode, pg_file_create_mode); + if (chmod(dstpath, buf.st_mode) != 0) + pg_fatal("could not chmod target file \"%s\": %m", dstpath); + } + } + + if (dstfd < 0) + pg_fatal("could not open target file \"%s\": %m", dstpath); + } } /* -- 2.14.3