Plug a small race in update-ref.c.
Signed-off-by: Junio C Hamano <junkio@cox.net>
Junio C Hamano committed
Sep 25, 2005 at 16:28 UTC
152da3dfcf2c16d7c240a0dbdcb8a3ae1d332d81
1 file changed
+22
-4
update-ref.c
+22
-4
@@ -1,5 +1,6 @@
1
#include "cache.h"
2
#include "refs.h"
3
+#include <ctype.h>
4
5
static const char git_update_ref_usage[] = "git-update-ref <refname> <value> [<oldval>]";
6
@@ -50,6 +51,19 @@ const char *resolve_ref(const char *path, unsigned char *sha1)
51
return path;
52
}
53
54
+static int re_verify(const char *path, unsigned char *oldsha1, unsigned char *currsha1)
55
+{
56
+ char buf[40];
57
+ int fd = open(path, O_RDONLY), nr;
58
+ if (fd < 0)
59
+ return -1;
60
+ nr = read(fd, buf, 40);
61
+ close(fd);
62
+ if (nr != 40 || get_sha1_hex(buf, currsha1) < 0)
63
+ return -1;
64
+ return memcmp(oldsha1, currsha1, 20) ? -1 : 0;
65
+}
66
+
67
int main(int argc, char **argv)
68
{
69
char *hex;
@@ -97,12 +111,16 @@ int main(int argc, char **argv)
111
}
112
113
/*
100
- * FIXME!
101
- *
102
- * We should re-read the old ref here, and re-verify that it
103
- * matches "oldsha1". Otherwise there's a small race.
114
+ * Re-read the ref after getting the lock to verify
115
*/
116
+ if (oldval && re_verify(path, oldsha1, currsha1) < 0) {
117
+ unlink(lockpath);
118
+ die("Ref lock failed");
119
+ }
120
121
+ /*
122
+ * Finally, replace the old ref with the new one
123
+ */
124
if (rename(lockpath, path) < 0) {
125
unlink(lockpath);
126
die("Unable to create %s", path);