files_read_raw_ref: avoid infinite loop on broken symlinks
authorJeff King <peff@peff.net>
Thu, 6 Oct 2016 19:41:08 +0000 (15:41 -0400)
committerJunio C Hamano <gitster@pobox.com>
Mon, 10 Oct 2016 17:53:16 +0000 (10:53 -0700)
Our ref resolution first runs lstat() on any path we try to
look up, because we want to treat symlinks specially (by
resolving them manually and considering them symrefs). But
if the results of `readlink` do _not_ look like a ref, we
fall through to treating it like a normal file, and just
read the contents of the linked path.

Since fcb7c76 (resolve_ref_unsafe(): close race condition
reading loose refs, 2013-06-19), that "normal file" code
path will stat() the file and if we see ENOENT, will jump
back to the lstat(), thinking we've seen inconsistent
results between the two calls. But for a symbolic ref, this
isn't a race: the lstat() found the symlink, and the stat()
is looking at the path it points to. We end up in an
infinite loop calling lstat() and stat().

We can fix this by avoiding the retry-on-inconsistent jump
when we know that we found a symlink. While we're at it,
let's add a comment explaining why the symlink case gets to
this code in the first place; without that, it is not
obvious that the correct solution isn't to avoid the stat()
code path entirely.

Signed-off-by: Jeff King <peff@peff.net>
Reviewed-by: Michael Haggerty <mhagger@alum.mit.edu>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
refs/files-backend.c
t/t1503-rev-parse-verify.sh
index 12290d249643b5aaab18961ca91637910d0d7261..087a8fa024303604a1608341774449ac8e21b72e 100644 (file)
@@ -1496,6 +1496,11 @@ int read_raw_ref(const char *refname, unsigned char *sha1,
                        ret = 0;
                        goto out;
                }
+               /*
+                * It doesn't look like a refname; fall through to just
+                * treating it like a non-symlink, and reading whatever it
+                * points to.
+                */
        }
 
        /* Is it a directory? */
@@ -1519,7 +1524,7 @@ int read_raw_ref(const char *refname, unsigned char *sha1,
         */
        fd = open(path, O_RDONLY);
        if (fd < 0) {
-               if (errno == ENOENT)
+               if (errno == ENOENT && !S_ISLNK(st.st_mode))
                        /* inconsistent with lstat; retry */
                        goto stat_ref;
                else
index ab27d0db5c5577a23e1053b58eefa63015526d0c..492edffa9cfb626b4747ead04251fc33b0502ac9 100755 (executable)
@@ -139,4 +139,9 @@ test_expect_success 'master@{n} for various n' '
        test_must_fail git rev-parse --verify master@{$Np1}
 '
 
+test_expect_success SYMLINKS 'ref resolution not confused by broken symlinks' '
+       ln -s does-not-exist .git/refs/heads/broken &&
+       test_must_fail git rev-parse --verify broken
+'
+
 test_done