SVN File descriptor corruption

I was looking at the source code of SVN and found this comment in the source code.

/* The following makes sure that file descriptors 0 (stdin), 1
   (stdout) and 2 (stderr) will not be "reused", because if
   e.g. file descriptor 2 would be reused when opening a file, a
   write to stderr would write to that file and most likely
   corrupt it. */

followed by this code:

if ((fstat(0, &st) == -1 && open("/dev/null", O_RDONLY) == -1) ||
    (fstat(1, &st) == -1 && open("/dev/null", O_WRONLY) == -1) ||
    (fstat(2, &st) == -1 && open("/dev/null", O_WRONLY) == -1))
  {
    if (error_stream)
      fprintf(error_stream, "%s: error: cannot open '/dev/null'\n",
              progname);
    return EXIT_FAILURE;
  }

I don’t understand how "reusing" a file descriptor can corrupt a file. And how can you open a file with file descriptor 2 (stderr) ? And how opening a file can effect write to stderr ?

>Solution :

I’m afraid that I don’t know about SVN-specific problems this code is designed to solve (it was committed more than 18 years ago). But I think that the below summary describes the potential problem at high level. So I assume that the part of code in question prevents this from happening:

Longstanding Unix practice dictates that applications are started with
the standard input, output, and error I/O streams on file descriptors
0, 1, and 2, respectively. The assumption that these file descriptors
will be properly set up is so strong that most developers never think
to check them. So interesting things can happen if an application is
run with one or more of the standard file descriptors closed.

Consider, for example, running a program with file descriptor 2
closed. The next file the program opens will be assigned that
descriptor. If something then causes the program to write to (what it
thinks is) the standard error stream, that output will, instead, go to
the other file which had been opened, probably corrupting that file. A
malicious user can easily make messes this way; when setuid programs
are involved, the potential consequences are worse.

Taken from https://lwn.net/Articles/347815/

PS Check svn blame for this part of code. It has a log message that describes the purpose of these checks.

Leave a Reply