Versions Compared

Key

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

...

There is no guarantee that the file opened for reading is the same file that was opened for writing. An attacker could replace the original file (for example, with a symbolic link) between the first fclose() and the second fopen(). This solutions is also non-compliant with FIO16-A. Avoid reopening a file stream.

Compliant Solution (POSIX) (device / i-node)

Reopening a file stream should generally be avoided (see FIO16-A. Avoid reopening a file stream). However, this may sometimes be necessary in long running applications to avoid depleting available file descriptors.
This compliant solution uses a "check, use, check" pattern to ensure that the file opened for reading is the same file that was opened for writing. In this solution, the file is opened using the open() function. If the file is successfully opened, the fstat() function is used to read information about the file into the stat structure. This information is compared with existing information about the file (stored in the dev and ino variables) to improve identification.

...

It may also be necessary to call open() with O_NONBLOCK as per FIO32-C. Do not perform operations on devices that are only appropriate for files to ensure that the program does not hang when trying to open special files.

This example is a valid exception to FIO16-A. Avoid reopening a file streamcompliant solution may not work in some cases. For instance a long-running service might choose to occasionally re-open a log file to add log messages, but leave the file closed, so that the log file may be periodically rotated. In this case, the inode number would change, negating this solution.

Non-Compliant Code Example (owner)

...