cfengine/core — pull request #1670 by kacfengine (2014-05-01 08:33:42+00:00)
Title: Redmine #5621: Safe open fixes

The pull request should be reviewed without whitespace changes, since there is a lot of reindentation.

https://cfengine.com/dev/issues/5621

commit 48bbcdcae07dd82bf2fd9e170658ff6ed94da2c2
Author: Kristian Amlie
Date: Thu May 1 09:25:26 2014

Redmine #5621: Fix failing safe_open in create race.

On single core systems with certain kernel versions (CentOS), the
ordering of open calls is deterministic, and if two threads try to
open the same file with O_CREAT, one will fail because the other
thread creates it at the same moment.

This is actually the very thing that safe_open was designed to protect
against, but since it can happen even in daily operation when there is
no foul play, we need to be a bit more tolerant. So if we find that we
have hit a race condition, instead of failing immediately, retry the
operation to see if we hit the race condition again. Only after a few
attempts do we give up.

This changes the expected result of one of the unit tests from
safe_open returning -1, to returning a file descriptor.

commit e8bdd736216b13fa9d8d45d830b1380ea4314a0b
Author: Kristian Amlie
Date: Thu May 1 09:56:31 2014

Add an additional test for opening a dangling symlink, not just creating

commit b50f4aea68caa739b93e9a133f7f90c19bdbb431
Author: Kristian Amlie
Date: Thu May 1 10:23:24 2014

Fix possible file open race condition on platforms without openat().

When opening a relative path, the first path component opened is the
current directory. However, this is opened using normal open(). This
is fine on most platforms, but on those where we emulate openat(), we
do not protect the open() call using the lock inside generic_at.c,
which means we can potentially be in a different directory at the time
of the call.

The fix is to switch to openat() with the AT_FDCWD flag, so that we
run the emulation code with the lock also for the first file open.