Fix O_CLOEXEC flag handling in Windows port.

PostgreSQL's src/port/open.c has always set bInheritHandle = TRUE
when opening files on Windows, making all file descriptors inheritable
by child processes.  This meant the O_CLOEXEC flag, added to many call
sites by commit 1da569ca1f (v16), was silently ignored.

The original commit included a comment suggesting that our open()
replacement doesn't create inheritable handles, but it was a mis-
understanding of the code path.  In practice, the code was creating
inheritable handles in all cases.

This hasn't caused widespread problems because most child processes
(archive_command, COPY PROGRAM, etc.) operate on file paths passed as
arguments rather than inherited file descriptors.  Even if a child
wanted to use an inherited handle, it would need to learn the numeric
handle value, which isn't passed through our IPC mechanisms.

Nonetheless, the current behavior is wrong.  It violates documented
O_CLOEXEC semantics, contradicts our own code comments, and makes
PostgreSQL behave differently on Windows than on Unix.  It also creates
potential issues with future code or security auditing tools.

To fix, define O_CLOEXEC to _O_NOINHERIT in master, previously used by
O_DSYNC.  We use different values in the back branches to preserve
existing values.  In pgwin32_open_handle() we set bInheritHandle
according to whether O_CLOEXEC is specified, for the same atomic
semantics as POSIX in multi-threaded programs that create processes.

Backpatch-through: 16
Author: Bryan Green <[email protected]>
Co-authored-by: Thomas Munro <[email protected]> (minor adjustments)
Discussion: https://postgr.es/m/e2b16375-7430-4053-bda3-5d2194ff1880%40gmail.com

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/c507ba55f5bfae900baa94f1c657e1d99da5c6dc

Modified Files
--------------
src/include/port.h                             |   1 -
src/include/port/win32_port.h                  |  19 +-
src/port/open.c                                |  14 +-
src/test/modules/Makefile                      |   1 +
src/test/modules/meson.build                   |   1 +
src/test/modules/test_cloexec/Makefile         |  30 +++
src/test/modules/test_cloexec/meson.build      |  26 +++
src/test/modules/test_cloexec/t/001_cloexec.pl |  60 ++++++
src/test/modules/test_cloexec/test_cloexec.c   | 262 +++++++++++++++++++++++++
9 files changed, 400 insertions(+), 14 deletions(-)

Reply via email to