server-info.c: remove temporary info files on exit

The update_info_file() function within server-info.c is responsible for moving the info/refs and info/packs files around when updating server info. These updates are staged into a temporary file and then moved into place atomically to avoid race conditions when reading those files. However, the temporary file used to stage these changes is managed outside of the tempfile.h API, and thus survives process death. Manage these files instead with the tempfile.h API so that they are automatically cleaned up upon abnormal process death. Unfortunately, and unlike in the previous step, there isn't a straightforward way to inject a failure into the update-server-info step that causes us to die() rather than take the cleanup path in label 'out', hence the lack of a test here. Signed-off-by: Taylor Blau <me@ttaylorr.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Taylor Blau committed Jun 6, 2024 at 18:19 UTC 8981dca8bc717d7656f28fc375b513b91b365360
1 file changed +10 -16
server-info.c
+10 -16
@@ -13,6 +13,7 @@
13 #include "object-store-ll.h"
14 #include "server-info.h"
15 #include "strbuf.h"
16 +#include "tempfile.h"
17
18 struct update_info_ctx {
19 FILE *cur_fp;
@@ -75,9 +76,8 @@ static int update_info_file(char *path,
76 int force)
77 {
78 char *tmp = mkpathdup("%s_XXXXXX", path);
79 + struct tempfile *f = NULL;
80 int ret = -1;
79 - int fd = -1;
80 - FILE *to_close;
81 struct update_info_ctx uic = {
82 .cur_fp = NULL,
83 .old_fp = NULL,
@@ -86,13 +86,12 @@ static int update_info_file(char *path,
86 };
87
88 safe_create_leading_directories(path);
89 - fd = git_mkstemp_mode(tmp, 0666);
90 - if (fd < 0)
89 + f = mks_tempfile_m(tmp, 0666);
90 + if (!f)
91 goto out;
92 - to_close = uic.cur_fp = fdopen(fd, "w");
92 + uic.cur_fp = fdopen_tempfile(f, "w");
93 if (!uic.cur_fp)
94 goto out;
95 - fd = -1;
95
96 /* no problem on ENOENT and old_fp == NULL, it's stale, now */
97 if (!force)
@@ -121,27 +120,22 @@ static int update_info_file(char *path,
120 }
121
122 uic.cur_fp = NULL;
124 - if (fclose(to_close))
125 - goto out;
123
124 if (uic_is_stale(&uic)) {
128 - if (adjust_shared_perm(tmp) < 0)
125 + if (adjust_shared_perm(get_tempfile_path(f)) < 0)
126 goto out;
130 - if (rename(tmp, path) < 0)
127 + if (rename_tempfile(&f, path) < 0)
128 goto out;
129 } else {
133 - unlink(tmp);
130 + delete_tempfile(&f);
131 }
132 ret = 0;
133
134 out:
135 if (ret) {
136 error_errno("unable to update %s", path);
140 - if (uic.cur_fp)
141 - fclose(uic.cur_fp);
142 - else if (fd >= 0)
143 - close(fd);
144 - unlink(tmp);
137 + if (f)
138 + delete_tempfile(&f);
139 }
140 free(tmp);
141 if (uic.old_fp)