Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Compliant Solution (POSIX)

Wiki Markup
POSIX defines the {{O_NONBLOCK}} flag to {{open()}} which ensures that delayed operations on a file does not hang the program \[[Open Group 04|AA. C References#Open Group 04]\].

When opening a FIFO with O_RDONLY or O_WRONLY set:

  • If O_NONBLOCK is set
:
  An
  • , an open() for reading only will return without delay. An open() for writing only will return an error if no process currently has the file open for reading.
  • If O_NONBLOCK is clear
:
  An
  • , an open() for reading only will block the calling thread until a thread opens the file for writing. An open() for writing only will block the calling thread until a thread opens the file for reading.

When opening a block special or character special file that supports non-blocking opens:

  • If O_NONBLOCK is set
:
  The
  • , the open() function will return without blocking for the device to be ready or available. Subsequent behaviour of the device is device-specific.
  • If O_NONBLOCK is clear
:
  The
  • , the open() function will block the calling thread until the device is ready or available before returning.

Otherwise, the behaviour of O_NONBLOCK is unspecified.

Once the file is open, programmers can use the POSIX lstat()/ and fstat() functions to obtain information about a named file, and the S_ISREG() macro to determine if the file is a regular file . (see FIO05-A. Identify files using multiple file attributes).

Since Because the behavior of O_NONBLOCK on subsequent calls to read() or write() is unspecified, it is advisable to disable the flag once we are sure after it has been determined that the file in question is not a special device.

...

The above code does contain an unfixable intractable TOCTOU race condition; where an attacker could substitute a rogue file (or symlink) for our good file. After we open the file, we will discover the switch, but if opening the file itself causes unwanted behavior, we cannot prevent the attacker from that behavior. There are essentially four cases that could result from an attacker switching out the file for one of the following:

...

Wiki Markup
\[[Garfinkel 96|AA. C References#Garfinkel 96]\] Section 5.6, "Device Files"
\[[Howard 02|AA. C References#Howard 02]\] Chapter 11, "Canonical Representation Issues"
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section
\[[Open Group 04|AA. C References#Open Group 04]\] [{{open()}}|http://www.opengroup.org/onlinepubs/009695399/functions/open.html]

...

FIO31-C. Do not simultaneously open the same file multiple times      09. Input Output (FIO)       FIO33-C. Detect and handle input output errors resulting in undefined behavior