Skip to content

Commit 27f5ff4

Browse files
committed
fix(file-update): harden cross-platform staged writes
- win32: parse \\?\UNC\server\share roots so parent dirs are created for new files on network shares instead of failing with EACCES - win32: name temp files .chsrc-XXXXXX like the POSIX backend so the leftover-files test also covers Windows - posix: link+unlink on new targets to match MoveFileExW's no-clobber semantics, falling back to rename on filesystems without hard links - cleanup staged files at exit so an aborting backup leaves no temp files - xy: fall back to EIO when read/fclose fails without setting errno - tests: drop the unknown escape in the home assertion, free display copies, and run the file-update suite on Windows too
1 parent 683ce9c commit 27f5ff4

6 files changed

Lines changed: 112 additions & 22 deletions

File tree

‎Makefile‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -220,11 +220,7 @@ debug: build-in-debug-mode
220220

221221

222222

223-
test: test-make-var test-xy test-fw
224-
225-
ifneq ($(On-Windows), 1)
226-
test: test-file-update
227-
endif
223+
test: test-make-var test-xy test-fw test-file-update
228224

229225
test-make-var:
230226
@echo "On-Linux: $(On-Linux)"

‎lib/xy.h‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1158,10 +1158,11 @@ xy_file_read_bytes (const char *path, char **out_buf, size_t *out_len)
11581158
}
11591159
size_t n = fread (buf + len, 1, cap - len - 1, fp);
11601160
len += n;
1161-
if (ferror (fp)) { ok = false; err = errno; break; }
1161+
/* 读失败时 errno 可能未被设置,补一个兜底以免上层报告 "Success"。 */
1162+
if (ferror (fp)) { ok = false; err = errno; if (0 == err) err = EIO; break; }
11621163
if (feof (fp)) break;
11631164
}
1164-
if (0 != fclose (fp)) { ok = false; err = errno; }
1165+
if (0 != fclose (fp)) { ok = false; err = errno; if (0 == err) err = EIO; }
11651166
if (!ok)
11661167
{
11671168
free (buf);

‎src/framework/file-update-posix.c‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,8 @@ file_update_stage (const FileUpdate_t *op, StagedFileUpdate_t *stage)
231231
if (!stage->target) goto done;
232232
if (0 != stat (stage->target, &st)) goto done;
233233
if (!S_ISREG (st.st_mode)) { errno = EINVAL; goto done; }
234+
/* access() 按真实 UID 判断,root 或 ACL 场景可能偏乐观;这里只作为
235+
* 尽早失败的前置检查,最终权限由临时文件写入与替换决定。 */
234236
if (0 != access (stage->target, W_OK)) goto done;
235237

236238
char *current = NULL;
@@ -294,9 +296,32 @@ file_update_stage (const FileUpdate_t *op, StagedFileUpdate_t *stage)
294296
static bool
295297
file_update_commit (StagedFileUpdate_t *stage, const FileUpdate_t *op)
296298
{
297-
(void) op; /* 保持与 Win32 后端一致的函数签名。 */
298-
299-
if (0 != rename (stage->replacement, stage->target)) return false;
299+
if (op->existed)
300+
{
301+
if (0 != rename (stage->replacement, stage->target)) return false;
302+
}
303+
else
304+
{
305+
/* 目标可能在计划生成后被其他程序创建。Win32 后端的 MoveFileExW 不带
306+
* REPLACE_EXISTING,会拒绝覆盖;这里用 link 取得同样的不覆盖语义。 */
307+
if (0 != link (stage->replacement, stage->target))
308+
{
309+
int err = errno;
310+
/* 不支持硬链接的文件系统退回 rename,行为与旧实现一致。 */
311+
if (ENOTSUP != err && EOPNOTSUPP != err && EPERM != err && EXDEV != err)
312+
{
313+
errno = err;
314+
return false;
315+
}
316+
if (0 != rename (stage->replacement, stage->target)) return false;
317+
}
318+
else if (0 != unlink (stage->replacement))
319+
{
320+
/* 目标已建立、提交已经生效;临时名留给 discard 再清理一次。 */
321+
file_update_sync_parent_dir (stage->target);
322+
return true;
323+
}
324+
}
300325

301326
/* 提交成功后清空指针,避免 discard 误删已不存在的临时路径。 */
302327
free (stage->replacement);

‎src/framework/file-update-win32.c‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,18 @@ file_update_win32_create_parent_dirs (const wchar_t *path)
132132
}
133133
else if (len >= 2 && L'\\' == dir[0] && L'\\' == dir[1])
134134
{
135-
wchar_t *share = wcschr (dir + 2, L'\\');
135+
/* 扩展长度 UNC 路径形如 \\?\UNC\server\share\...,server/share 位于
136+
* UNC\ 标记之后,不能像 \\?\C:\ 那样把前两段直接当作根前缀跳过。 */
137+
size_t offset = 2;
138+
if (len >= 8 && (L'?' == dir[2] || L'.' == dir[2]) && L'\\' == dir[3]
139+
&& (L'U' == dir[4] || L'u' == dir[4])
140+
&& (L'N' == dir[5] || L'n' == dir[5])
141+
&& (L'C' == dir[6] || L'c' == dir[6]) && L'\\' == dir[7])
142+
{
143+
offset = 8;
144+
}
145+
146+
wchar_t *share = wcschr (dir + offset, L'\\');
136147
if (share)
137148
{
138149
wchar_t *next = wcschr (share + 1, L'\\');
@@ -168,8 +179,9 @@ file_update_win32_create_parent_dirs (const wchar_t *path)
168179
}
169180

170181

171-
/* 在目标文件同目录生成 chsrc-XXXXXX 临时文件;CREATE_NEW 保证不会覆盖
172-
* 其他进程刚创建的文件,命名冲突时重新生成。 */
182+
/* 在目标文件同目录生成 .chsrc-XXXXXX 临时文件;CREATE_NEW 保证不会覆盖
183+
* 其他进程刚创建的文件,命名冲突时重新生成。前导点与 POSIX 后端一致,
184+
* 便于用户和测试识别残留的临时文件。 */
173185
static bool
174186
file_update_win32_make_temp (const wchar_t *target, HANDLE *out_handle, wchar_t **out_path)
175187
{
@@ -179,7 +191,7 @@ file_update_win32_make_temp (const wchar_t *target, HANDLE *out_handle, wchar_t
179191
wchar_t *slash = wcsrchr (pattern, L'\\');
180192
if (!slash) { free (pattern); errno = EINVAL; return false; }
181193
slash[1] = L'\0';
182-
wcscat (pattern, L"chsrc-XXXXXX");
194+
wcscat (pattern, L".chsrc-XXXXXX");
183195

184196
for (int i = 0; i < 16; i++)
185197
{

‎src/framework/file-update.c‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,9 +94,27 @@ file_update_changed (const FileUpdate_t *op)
9494
#include "file-update-posix.c"
9595
#endif
9696

97+
/* 暂存完成后若进程被 exit() 终止(例如备份命令失败会直接退出),临时文件
98+
* 不应留在用户目录里;这里记录当前批次,退出时复用各后端的 discard 清理。
99+
* 单线程模型:同一时刻只有一个批次处于暂存状态。 */
100+
static StagedFileUpdate_t *FileUpdate_Active_Stages = NULL;
101+
static size_t FileUpdate_Active_Count = 0;
102+
static bool FileUpdate_Exit_Hook_Installed = false;
103+
104+
static void
105+
file_update_cleanup_active_stages (void)
106+
{
107+
for (size_t i = 0; i < FileUpdate_Active_Count; i++)
108+
file_update_discard (&FileUpdate_Active_Stages[i]);
109+
110+
FileUpdate_Active_Stages = NULL;
111+
FileUpdate_Active_Count = 0;
112+
}
113+
97114
/* 全部内容由调用方预先生成。本层比较字节并复核旧快照,再暂存、备份、替换。
98115
* 无变化时不写入、不备份;Dry Run 只显示将要修改的文件。
99116
* 每个文件原子替换,后续失败回滚已替换文件;不保证崩溃时的多文件原子性。
117+
* 目标若为硬链接,只会重建其中一条目录项,其余链接仍指向旧内容。
100118
* 平台后端负责保留符号链接及权限/ACL;复核快照不能消除外部写入竞态。 */
101119
static FileUpdateResult_t
102120
chsrc_update_files (const FileUpdate_t *ops, size_t count, char **out_err)
@@ -131,6 +149,15 @@ chsrc_update_files (const FileUpdate_t *ops, size_t count, char **out_err)
131149
}
132150

133151
StagedFileUpdate_t *stages = xy_malloc0 (count * sizeof (StagedFileUpdate_t));
152+
if (!FileUpdate_Exit_Hook_Installed)
153+
{
154+
/* 批次结束时指针会复位,正常退出时钩子不会访问已释放的内存。 */
155+
atexit (file_update_cleanup_active_stages);
156+
FileUpdate_Exit_Hook_Installed = true;
157+
}
158+
FileUpdate_Active_Stages = stages;
159+
FileUpdate_Active_Count = count;
160+
134161
size_t failed = 0;
135162
bool ok = true;
136163
bool rollback_ok = true;
@@ -192,9 +219,11 @@ chsrc_update_files (const FileUpdate_t *ops, size_t count, char **out_err)
192219
{
193220
rollback_ok = false;
194221
stages[i].keep_rollback = true;
195-
chsrc_error2 (xy_2strcat (
222+
char *recover = xy_2strcat (
196223
ENGLISH ? "Rollback failed; recover using backup: " : "回滚失败,请使用备份恢复: ",
197-
stages[i].rollback ? stages[i].rollback : stages[i].target));
224+
stages[i].rollback ? stages[i].rollback : stages[i].target);
225+
chsrc_error2 (recover);
226+
free (recover);
198227
}
199228
}
200229
if (out_err)
@@ -227,6 +256,8 @@ chsrc_update_files (const FileUpdate_t *ops, size_t count, char **out_err)
227256
log_for_file_write (ops[i].display_path, true);
228257
}
229258

259+
FileUpdate_Active_Stages = NULL;
260+
FileUpdate_Active_Count = 0;
230261
for (size_t i = 0; i < count; i++)
231262
file_update_discard (&stages[i]);
232263
free (stages);

‎test/xy.c‎

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -195,10 +195,18 @@ main (int argc, char const *argv[])
195195

196196
char *home_path = xy_normalize_path ("~");
197197
#ifdef XY_Build_On_Windows
198-
assert_str (home_path, xy_2strcat ("\\\\\?\\", xy_os_home));
199-
home_path = xy_path_display_text (home_path);
198+
{
199+
char *home_expected = xy_2strcat ("\\\\?\\", xy_os_home);
200+
assert_str (home_path, home_expected);
201+
free (home_expected);
202+
203+
char *home_display = xy_path_display_text (home_path);
204+
assert (NULL != home_display);
205+
free (home_path);
206+
home_path = home_display;
207+
}
200208
#endif
201-
assert_str (home_path , xy_os_home);
209+
assert_str (home_path, xy_os_home);
202210
free (home_path);
203211

204212
#ifdef XY_Build_On_Windows
@@ -219,16 +227,33 @@ main (int argc, char const *argv[])
219227
say (xy_normalize_path ("~"));
220228
say (xy_normalize_path ("~/"));
221229
// xy_parent_dir() 得到的结果一定是不包含尾斜杠的目录名
222-
assert_str (xy_path_display (xy_parent_dir (xy_normalize_path ("~"))), "C:\\Users");
223-
assert_str (xy_path_display (xy_parent_dir (xy_normalize_path ("~/"))), "C:\\Users");
230+
char *home_norm = xy_normalize_path ("~");
231+
char *home_parent = xy_parent_dir (home_norm);
232+
char *home_parent_display = xy_path_display (home_parent);
233+
assert_str (home_parent_display, "C:\\Users");
234+
free (home_parent_display);
235+
free (home_parent);
236+
free (home_norm);
237+
238+
char *home_slash_norm = xy_normalize_path ("~/");
239+
char *home_slash_parent = xy_parent_dir (home_slash_norm);
240+
char *home_slash_display = xy_path_display (home_slash_parent);
241+
assert_str (home_slash_display, "C:\\Users");
242+
free (home_slash_display);
243+
free (home_slash_parent);
244+
free (home_slash_norm);
224245
assert (xy_dir_exist ("C:\\Users"));
225246

226247
say (xy_win_powershell_profile);
227248
say (xy_win_powershellv5_profile);
228249
assert (xy_file_exist (xy_win_powershell_profile));
229250
assert (true == xy_file_exist (xy_win_powershellv5_profile));
230251

231-
assert_str (xy_path_display (xy_normalize_path ("C:\\a bc\\def\\")), "C:\\a bc\\def\\");
252+
char *spaced = xy_normalize_path ("C:\\a bc\\def\\");
253+
char *spaced_display = xy_path_display (spaced);
254+
assert_str (spaced_display, "C:\\a bc\\def\\");
255+
free (spaced_display);
256+
free (spaced);
232257
assert_str (xy_normalize_path ("a/b c/d"), "a\\b c\\d");
233258
assert_str (xy_normalize_path ("a/b c/d/"), "a\\b c\\d\\");
234259
assert_str (xy_parent_dir ("a/b c/d"), "a\\b c");

0 commit comments

Comments
 (0)