Raw
1 #define USE_THE_REPOSITORY_VARIABLE
2 #define DISABLE_SIGN_COMPARE_WARNINGS
3
4 #include "git-compat-util.h"
5 #include "abspath.h"
6 #include "alloc.h"
7 #include "config.h"
8 #include "dir.h"
9 #include "environment.h"
10 #include "repository.h"
11 #include "gettext.h"
12 #include "run-command.h"
13 #include "strbuf.h"
14 #include "symlinks.h"
15 #include "trace2.h"
16 #include "win32.h"
17 #include "win32/exit-process.h"
18 #include "win32/lazyload.h"
19 #include "wrapper.h"
20 #include <aclapi.h>
21 #include <conio.h>
22 #include <sddl.h>
23 #define SECURITY_WIN32
24 #include <sspi.h>
25 #include <wchar.h>
26 #include <winioctl.h>
27 #include <winternl.h>
28
29 #define STATUS_DELETE_PENDING ((NTSTATUS) 0xC0000056)
30
31 #define HCAST(type, handle) ((type)(intptr_t)handle)
32
33 void open_in_gdb(void)
34 {
35 static struct child_process cp = CHILD_PROCESS_INIT;
36
37 strvec_pushl(&cp.args, "mintty", "gdb", NULL);
38 strvec_pushf(&cp.args, "--pid=%d", getpid());
39 cp.clean_on_exit = 1;
40 if (start_command(&cp) < 0)
41 die_errno("Could not start gdb");
42 sleep(1);
43 }
44
45 int err_win_to_posix(DWORD winerr)
46 {
47 int error = ENOSYS;
48 switch(winerr) {
49 case ERROR_ACCESS_DENIED: error = EACCES; break;
50 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
51 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
52 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
53 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
54 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
55 case ERROR_BAD_COMMAND: error = EIO; break;
56 case ERROR_BAD_DEVICE: error = ENODEV; break;
57 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
58 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
59 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
60 case ERROR_BAD_LENGTH: error = EINVAL; break;
61 case ERROR_BAD_PATHNAME: error = ENOENT; break;
62 case ERROR_BAD_PIPE: error = EPIPE; break;
63 case ERROR_BAD_UNIT: error = ENODEV; break;
64 case ERROR_BAD_USERNAME: error = EINVAL; break;
65 case ERROR_BROKEN_PIPE: error = EPIPE; break;
66 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
67 case ERROR_BUSY: error = EBUSY; break;
68 case ERROR_BUSY_DRIVE: error = EBUSY; break;
69 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
70 case ERROR_CANNOT_MAKE: error = EACCES; break;
71 case ERROR_CANTOPEN: error = EIO; break;
72 case ERROR_CANTREAD: error = EIO; break;
73 case ERROR_CANTWRITE: error = EIO; break;
74 case ERROR_CRC: error = EIO; break;
75 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
76 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
77 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
78 case ERROR_DIRECTORY: error = EINVAL; break;
79 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
80 case ERROR_DISK_CHANGE: error = EIO; break;
81 case ERROR_DISK_FULL: error = ENOSPC; break;
82 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
83 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
84 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
85 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
86 case ERROR_FILE_EXISTS: error = EEXIST; break;
87 case ERROR_FILE_INVALID: error = ENODEV; break;
88 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
89 case ERROR_GEN_FAILURE: error = EIO; break;
90 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
91 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
92 case ERROR_INVALID_ACCESS: error = EACCES; break;
93 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
94 case ERROR_INVALID_BLOCK: error = EFAULT; break;
95 case ERROR_INVALID_DATA: error = EINVAL; break;
96 case ERROR_INVALID_DRIVE: error = ENODEV; break;
97 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
98 case ERROR_INVALID_FLAGS: error = EINVAL; break;
99 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
100 case ERROR_INVALID_HANDLE: error = EBADF; break;
101 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
102 case ERROR_INVALID_NAME: error = EINVAL; break;
103 case ERROR_INVALID_OWNER: error = EINVAL; break;
104 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
105 case ERROR_INVALID_PASSWORD: error = EPERM; break;
106 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
107 case ERROR_INVALID_REPARSE_DATA: error = EINVAL; break;
108 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
109 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
110 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
111 case ERROR_IO_DEVICE: error = EIO; break;
112 case ERROR_IO_INCOMPLETE: error = EINTR; break;
113 case ERROR_LOCKED: error = EBUSY; break;
114 case ERROR_LOCK_VIOLATION: error = EACCES; break;
115 case ERROR_LOGON_FAILURE: error = EACCES; break;
116 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
117 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
118 case ERROR_MORE_DATA: error = EPIPE; break;
119 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
120 case ERROR_NOACCESS: error = EFAULT; break;
121 case ERROR_NONE_MAPPED: error = EINVAL; break;
122 case ERROR_NOT_A_REPARSE_POINT: error = EINVAL; break;
123 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
124 case ERROR_NOT_READY: error = EAGAIN; break;
125 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
126 case ERROR_NO_DATA: error = EPIPE; break;
127 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
128 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
129 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
130 case ERROR_OPEN_FAILED: error = EIO; break;
131 case ERROR_OPEN_FILES: error = EBUSY; break;
132 case ERROR_OPERATION_ABORTED: error = EINTR; break;
133 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
134 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
135 case ERROR_PATH_BUSY: error = EBUSY; break;
136 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
137 case ERROR_PIPE_BUSY: error = EBUSY; break;
138 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
139 case ERROR_PIPE_LISTENING: error = EPIPE; break;
140 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
141 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
142 case ERROR_READ_FAULT: error = EIO; break;
143 case ERROR_REPARSE_ATTRIBUTE_CONFLICT: error = EINVAL; break;
144 case ERROR_REPARSE_TAG_INVALID: error = EINVAL; break;
145 case ERROR_REPARSE_TAG_MISMATCH: error = EINVAL; break;
146 case ERROR_SEEK: error = EIO; break;
147 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
148 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
149 case ERROR_SHARING_VIOLATION: error = EACCES; break;
150 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
151 case ERROR_SUCCESS: BUG("err_win_to_posix() called without an error!");
152 case ERROR_SWAPERROR: error = ENOENT; break;
153 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
154 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
155 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
156 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
157 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
158 case ERROR_WRITE_FAULT: error = EIO; break;
159 case ERROR_WRITE_PROTECT: error = EROFS; break;
160 }
161 return error;
162 }
163
164 static inline int is_file_in_use_error(DWORD errcode)
165 {
166 switch (errcode) {
167 case ERROR_SHARING_VIOLATION:
168 case ERROR_ACCESS_DENIED:
169 return 1;
170 }
171
172 return 0;
173 }
174
175 static int read_yes_no_answer(void)
176 {
177 char answer[1024];
178
179 if (fgets(answer, sizeof(answer), stdin)) {
180 size_t answer_len = strlen(answer);
181 int got_full_line = 0, c;
182
183 /* remove the newline */
184 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
185 answer[answer_len-2] = '\0';
186 got_full_line = 1;
187 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
188 answer[answer_len-1] = '\0';
189 got_full_line = 1;
190 }
191 /* flush the buffer in case we did not get the full line */
192 if (!got_full_line)
193 while ((c = getchar()) != EOF && c != '\n')
194 ;
195 } else
196 /* we could not read, return the
197 * default answer which is no */
198 return 0;
199
200 if (tolower(answer[0]) == 'y' && !answer[1])
201 return 1;
202 if (!strncasecmp(answer, "yes", sizeof(answer)))
203 return 1;
204 if (tolower(answer[0]) == 'n' && !answer[1])
205 return 0;
206 if (!strncasecmp(answer, "no", sizeof(answer)))
207 return 0;
208
209 /* did not find an answer we understand */
210 return -1;
211 }
212
213 static int ask_yes_no_if_possible(const char *format, va_list args)
214 {
215 char question[4096];
216 const char *retry_hook;
217
218 vsnprintf(question, sizeof(question), format, args);
219
220 retry_hook = mingw_getenv("GIT_ASK_YESNO");
221 if (retry_hook) {
222 struct child_process cmd = CHILD_PROCESS_INIT;
223
224 strvec_pushl(&cmd.args, retry_hook, question, NULL);
225 return !run_command(&cmd);
226 }
227
228 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
229 return 0;
230
231 while (1) {
232 int answer;
233 fprintf(stderr, "%s (y/n) ", question);
234
235 if ((answer = read_yes_no_answer()) >= 0)
236 return answer;
237
238 fprintf(stderr, "Sorry, I did not understand your answer. "
239 "Please type 'y' or 'n'\n");
240 }
241 }
242
243 static int retry_ask_yes_no(int *tries, const char *format, ...)
244 {
245 static const int delay[] = { 0, 1, 10, 20, 40 };
246 va_list args;
247 int result, saved_errno = errno;
248
249 if ((*tries) < ARRAY_SIZE(delay)) {
250 /*
251 * We assume that some other process had the file open at the wrong
252 * moment and retry. In order to give the other process a higher
253 * chance to complete its operation, we give up our time slice now.
254 * If we have to retry again, we do sleep a bit.
255 */
256 Sleep(delay[*tries]);
257 (*tries)++;
258 return 1;
259 }
260
261 va_start(args, format);
262 result = ask_yes_no_if_possible(format, args);
263 va_end(args);
264 errno = saved_errno;
265 return result;
266 }
267
268 /* Windows only */
269 enum hide_dotfiles_type {
270 HIDE_DOTFILES_FALSE = 0,
271 HIDE_DOTFILES_TRUE,
272 HIDE_DOTFILES_DOTGITONLY
273 };
274
275 static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
276 static char *unset_environment_variables;
277
278 int mingw_core_config(const char *var, const char *value,
279 const struct config_context *ctx UNUSED,
280 void *cb UNUSED)
281 {
282 if (!strcmp(var, "core.hidedotfiles")) {
283 if (value && !strcasecmp(value, "dotgitonly"))
284 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
285 else
286 hide_dotfiles = git_config_bool(var, value);
287 return 0;
288 }
289
290 if (!strcmp(var, "core.unsetenvvars")) {
291 if (!value)
292 return config_error_nonbool(var);
293 free(unset_environment_variables);
294 unset_environment_variables = xstrdup(value);
295 return 0;
296 }
297
298 return 0;
299 }
300
301 static inline int is_wdir_sep(wchar_t wchar)
302 {
303 return wchar == L'/' || wchar == L'\\';
304 }
305
306 static const wchar_t *make_relative_to(const wchar_t *path,
307 const wchar_t *relative_to, wchar_t *out,
308 size_t size)
309 {
310 size_t i = wcslen(relative_to), len;
311
312 /* Is `path` already absolute? */
313 if (is_wdir_sep(path[0]) ||
314 (iswalpha(path[0]) && path[1] == L':' && is_wdir_sep(path[2])))
315 return path;
316
317 while (i > 0 && !is_wdir_sep(relative_to[i - 1]))
318 i--;
319
320 /* Is `relative_to` in the current directory? */
321 if (!i)
322 return path;
323
324 len = wcslen(path);
325 if (i + len + 1 > size) {
326 error("Could not make '%ls' relative to '%ls' (too large)",
327 path, relative_to);
328 return NULL;
329 }
330
331 memcpy(out, relative_to, i * sizeof(wchar_t));
332 wcscpy(out + i, path);
333 return out;
334 }
335
336 static DWORD symlink_file_flags = 0, symlink_directory_flags = 1;
337
338 enum phantom_symlink_result {
339 PHANTOM_SYMLINK_RETRY,
340 PHANTOM_SYMLINK_DONE,
341 PHANTOM_SYMLINK_DIRECTORY
342 };
343
344 /*
345 * Changes a file symlink to a directory symlink if the target exists and is a
346 * directory.
347 */
348 static enum phantom_symlink_result
349 process_phantom_symlink(const wchar_t *wtarget, const wchar_t *wlink)
350 {
351 HANDLE hnd;
352 BY_HANDLE_FILE_INFORMATION fdata;
353 wchar_t relative[MAX_PATH];
354 const wchar_t *rel;
355
356 /*
357 * Do not follow symlinks to network shares, to avoid NTLM credential
358 * leak from crafted repositories (e.g. \\attacker-server\share).
359 * Since paths come in all kind of enterprising shapes and forms (in
360 * addition to the canonical `\\host\share` form, there's also
361 * `\??\UNC\host\share`, `\GLOBAL??\UNC\host\share` and also
362 * `\Device\Mup\host\share`, just to name a few), we simply avoid
363 * following every symlink target that starts with a slash.
364 *
365 * This also catches drive-less absolute paths, of course. These are
366 * uncommon in practice (and also fragile because they are relative to
367 * the current working directory's drive). The only "harm" this does
368 * is that it now requires users to specify via the Git attributes if
369 * they have such an uncommon symbolic link and need it to be a
370 * directory type link.
371 */
372 if (is_wdir_sep(wtarget[0])) {
373 warning("created file symlink '%ls' pointing to '%ls';\n"
374 "set the `symlink` gitattribute to `dir` if a "
375 "directory symlink is required", wlink, wtarget);
376 return PHANTOM_SYMLINK_DONE;
377 }
378
379 /* check that wlink is still a file symlink */
380 if ((GetFileAttributesW(wlink)
381 & (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
382 != FILE_ATTRIBUTE_REPARSE_POINT)
383 return PHANTOM_SYMLINK_DONE;
384
385 /* make it relative, if necessary */
386 rel = make_relative_to(wtarget, wlink, relative, ARRAY_SIZE(relative));
387 if (!rel)
388 return PHANTOM_SYMLINK_DONE;
389
390 /* let Windows resolve the link by opening it */
391 hnd = CreateFileW(rel, 0,
392 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
393 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
394 if (hnd == INVALID_HANDLE_VALUE) {
395 errno = err_win_to_posix(GetLastError());
396 return PHANTOM_SYMLINK_RETRY;
397 }
398
399 if (!GetFileInformationByHandle(hnd, &fdata)) {
400 errno = err_win_to_posix(GetLastError());
401 CloseHandle(hnd);
402 return PHANTOM_SYMLINK_RETRY;
403 }
404 CloseHandle(hnd);
405
406 /* if target exists and is a file, we're done */
407 if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
408 return PHANTOM_SYMLINK_DONE;
409
410 /* otherwise recreate the symlink with directory flag */
411 if (DeleteFileW(wlink) &&
412 CreateSymbolicLinkW(wlink, wtarget, symlink_directory_flags))
413 return PHANTOM_SYMLINK_DIRECTORY;
414
415 errno = err_win_to_posix(GetLastError());
416 return PHANTOM_SYMLINK_RETRY;
417 }
418
419 /* keep track of newly created symlinks to non-existing targets */
420 struct phantom_symlink_info {
421 struct phantom_symlink_info *next;
422 wchar_t *wlink;
423 wchar_t *wtarget;
424 };
425
426 static struct phantom_symlink_info *phantom_symlinks = NULL;
427 static CRITICAL_SECTION phantom_symlinks_cs;
428
429 static void process_phantom_symlinks(void)
430 {
431 struct phantom_symlink_info *current, **psi;
432 EnterCriticalSection(&phantom_symlinks_cs);
433 /* process phantom symlinks list */
434 psi = &phantom_symlinks;
435 while ((current = *psi)) {
436 enum phantom_symlink_result result = process_phantom_symlink(
437 current->wtarget, current->wlink);
438 if (result == PHANTOM_SYMLINK_RETRY) {
439 psi = &current->next;
440 } else {
441 /* symlink was processed, remove from list */
442 *psi = current->next;
443 free(current);
444 /* if symlink was a directory, start over */
445 if (result == PHANTOM_SYMLINK_DIRECTORY)
446 psi = &phantom_symlinks;
447 }
448 }
449 LeaveCriticalSection(&phantom_symlinks_cs);
450 }
451
452 /* Normalizes NT paths as returned by some low-level APIs. */
453 static wchar_t *normalize_ntpath(wchar_t *wbuf)
454 {
455 int i;
456 /* fix absolute path prefixes */
457 if (wbuf[0] == '\\') {
458 /* strip NT namespace prefixes */
459 if (!wcsncmp(wbuf, L"\\??\\", 4) ||
460 !wcsncmp(wbuf, L"\\\\?\\", 4))
461 wbuf += 4;
462 else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
463 wbuf += 12;
464 /* replace remaining '...UNC\' with '\\' */
465 if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
466 wbuf += 2;
467 *wbuf = '\\';
468 }
469 }
470 /* convert backslashes to slashes */
471 for (i = 0; wbuf[i]; i++)
472 if (wbuf[i] == '\\')
473 wbuf[i] = '/';
474 return wbuf;
475 }
476
477 /*
478 * Use SetFileInformationByHandle(FileDispositionInfo) to force legacy
479 * (non-POSIX) delete semantics. On Windows 11, DeleteFileW() uses POSIX
480 * delete semantics internally, allowing deletion even with active
481 * MapViewOfFile views. This helper simulates Windows 10 behavior where
482 * deletion fails if a file mapping exists.
483 *
484 * Returns nonzero on success (like DeleteFileW), 0 on failure.
485 */
486 static int legacy_delete_file(const wchar_t *wpathname)
487 {
488 FILE_DISPOSITION_INFO fdi = { TRUE };
489 DWORD gle;
490 HANDLE h = CreateFileW(wpathname, DELETE,
491 FILE_SHARE_READ | FILE_SHARE_WRITE |
492 FILE_SHARE_DELETE,
493 NULL, OPEN_EXISTING,
494 FILE_FLAG_OPEN_REPARSE_POINT, NULL);
495 if (h == INVALID_HANDLE_VALUE)
496 return 0;
497
498 if (SetFileInformationByHandle(h, FileDispositionInfo,
499 &fdi, sizeof(fdi))) {
500 CloseHandle(h);
501 return 1;
502 }
503 gle = GetLastError();
504 CloseHandle(h);
505 SetLastError(gle);
506 return 0;
507 }
508
509 static int try_delete_file(const wchar_t *wpathname, int use_legacy)
510 {
511 if (use_legacy)
512 return legacy_delete_file(wpathname);
513 return DeleteFileW(wpathname);
514 }
515
516 int mingw_unlink(const char *pathname, int handle_in_use_error)
517 {
518 static int use_legacy_delete = -1;
519 int tries = 0;
520 wchar_t wpathname[MAX_PATH];
521 if (xutftowcs_path(wpathname, pathname) < 0)
522 return -1;
523
524 if (use_legacy_delete < 0)
525 use_legacy_delete = git_env_bool("GIT_TEST_LEGACY_DELETE", 0);
526
527 if (try_delete_file(wpathname, use_legacy_delete))
528 return 0;
529
530 do {
531 /* read-only files cannot be removed */
532 _wchmod(wpathname, 0666);
533 if (try_delete_file(wpathname, use_legacy_delete))
534 return 0;
535 if (!is_file_in_use_error(GetLastError()))
536 break;
537 /*
538 * _wunlink() / DeleteFileW() for directory symlinks fails with
539 * ERROR_ACCESS_DENIED (EACCES), so try _wrmdir() as well. This is the
540 * same error we get if a file is in use (already checked above).
541 */
542 if (!_wrmdir(wpathname))
543 return 0;
544
545 if (!handle_in_use_error)
546 return -1;
547 } while (retry_ask_yes_no(&tries, "Unlink of file '%s' failed. "
548 "Should I try again?", pathname));
549 return -1;
550 }
551
552 static int is_dir_empty(const wchar_t *wpath)
553 {
554 WIN32_FIND_DATAW findbuf;
555 HANDLE handle;
556 wchar_t wbuf[MAX_PATH + 2];
557 wcscpy(wbuf, wpath);
558 wcscat(wbuf, L"\\*");
559 handle = FindFirstFileW(wbuf, &findbuf);
560 if (handle == INVALID_HANDLE_VALUE)
561 return GetLastError() == ERROR_NO_MORE_FILES;
562
563 while (!wcscmp(findbuf.cFileName, L".") ||
564 !wcscmp(findbuf.cFileName, L".."))
565 if (!FindNextFileW(handle, &findbuf)) {
566 DWORD err = GetLastError();
567 FindClose(handle);
568 return err == ERROR_NO_MORE_FILES;
569 }
570 FindClose(handle);
571 return 0;
572 }
573
574 int mingw_rmdir(const char *pathname)
575 {
576 int tries = 0;
577 wchar_t wpathname[MAX_PATH];
578 struct stat st;
579
580 /*
581 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
582 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
583 * symbolic link (if it points to a directory).
584 *
585 * This behavior breaks the assumption of e.g. `remove_path()` which
586 * upon successful deletion of a file will attempt to remove its parent
587 * directories recursively until failure (which usually happens when
588 * the directory is not empty).
589 *
590 * Therefore, before calling `_wrmdir()`, we first check if the path is
591 * a symbolic link. If it is, we exit and return the same error as
592 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
593 */
594 if (!mingw_lstat(pathname, &st) && S_ISLNK(st.st_mode)) {
595 errno = ENOTDIR;
596 return -1;
597 }
598
599 if (xutftowcs_path(wpathname, pathname) < 0)
600 return -1;
601
602 do {
603 if (!_wrmdir(wpathname)) {
604 invalidate_lstat_cache();
605 return 0;
606 }
607 if (!is_file_in_use_error(GetLastError()))
608 errno = err_win_to_posix(GetLastError());
609 if (errno != EACCES)
610 break;
611 if (!is_dir_empty(wpathname)) {
612 errno = ENOTEMPTY;
613 break;
614 }
615 } while (retry_ask_yes_no(&tries, "Deletion of directory '%s' failed. "
616 "Should I try again?", pathname));
617 return -1;
618 }
619
620 static inline int needs_hiding(const char *path)
621 {
622 const char *basename;
623
624 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
625 return 0;
626
627 /* We cannot use basename(), as it would remove trailing slashes */
628 win32_skip_dos_drive_prefix((char **)&path);
629 if (!*path)
630 return 0;
631
632 for (basename = path; *path; path++)
633 if (is_dir_sep(*path)) {
634 do {
635 path++;
636 } while (is_dir_sep(*path));
637 /* ignore trailing slashes */
638 if (*path)
639 basename = path;
640 else
641 break;
642 }
643
644 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
645 return *basename == '.';
646
647 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
648 return !strncasecmp(".git", basename, 4) &&
649 (!basename[4] || is_dir_sep(basename[4]));
650 }
651
652 static int set_hidden_flag(const wchar_t *path, int set)
653 {
654 DWORD original = GetFileAttributesW(path), modified;
655 if (set)
656 modified = original | FILE_ATTRIBUTE_HIDDEN;
657 else
658 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
659 if (original == modified || SetFileAttributesW(path, modified))
660 return 0;
661 errno = err_win_to_posix(GetLastError());
662 return -1;
663 }
664
665 int mingw_mkdir(const char *path, int mode UNUSED)
666 {
667 int ret;
668 wchar_t wpath[MAX_PATH];
669
670 if (!is_valid_win32_path(path, 0)) {
671 errno = EINVAL;
672 return -1;
673 }
674
675 if (xutftowcs_path(wpath, path) < 0)
676 return -1;
677 ret = _wmkdir(wpath);
678 if (!ret)
679 process_phantom_symlinks();
680 if (!ret && needs_hiding(path))
681 return set_hidden_flag(wpath, 1);
682 return ret;
683 }
684
685 /*
686 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
687 * is documented in [1] as opening a writable file handle in append mode.
688 * (It is believed that) this is atomic since it is maintained by the
689 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
690 *
691 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
692 *
693 * This trick does not appear to work for named pipes. Instead it creates
694 * a named pipe client handle that cannot be written to. Callers should
695 * just use the regular _wopen() for them. (And since client handle gets
696 * bound to a unique server handle, it isn't really an issue.)
697 */
698 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
699 {
700 HANDLE handle;
701 int fd;
702 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
703
704 /* only these flags are supported */
705 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND)) {
706 errno = ENOSYS;
707 return -1;
708 }
709
710 /*
711 * FILE_SHARE_WRITE is required to permit child processes
712 * to append to the file.
713 */
714 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
715 FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
716 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
717 if (handle == INVALID_HANDLE_VALUE) {
718 DWORD err = GetLastError();
719
720 /*
721 * Some network storage solutions (e.g. Isilon) might return
722 * ERROR_INVALID_PARAMETER instead of expected error
723 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
724 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
725 */
726 if (err == ERROR_INVALID_PARAMETER)
727 err = ERROR_PATH_NOT_FOUND;
728
729 errno = err_win_to_posix(err);
730 return -1;
731 }
732
733 /*
734 * No O_APPEND here, because the CRT uses it only to reset the
735 * file pointer to EOF before each write(); but that is not
736 * necessary (and may lead to races) for a file created with
737 * FILE_APPEND_DATA.
738 */
739 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
740 if (fd < 0)
741 CloseHandle(handle);
742 return fd;
743 }
744
745 /*
746 * Ideally, we'd use `_wopen()` to implement this functionality so that we
747 * don't have to reimplement it, but unfortunately we do not have tight control
748 * over the share mode there. And while `_wsopen()` and friends exist that give
749 * us _some_ control over the share mode, this family of functions doesn't give
750 * us the ability to enable FILE_SHARE_DELETE, either. But this is a strict
751 * requirement for us though so that we can unlink or rename over files that
752 * are held open by another process.
753 *
754 * We are thus forced to implement our own emulation of `open()`. To make our
755 * life simpler we only implement basic support for this, namely opening
756 * existing files for reading and/or writing. This means that newly created
757 * files won't have their sharing mode set up correctly, but for now I couldn't
758 * find any case where this matters. We may have to revisit that in the future
759 * though based on our needs.
760 */
761 static int mingw_open_existing(const wchar_t *filename, int oflags, ...)
762 {
763 SECURITY_ATTRIBUTES security_attributes = {
764 .nLength = sizeof(security_attributes),
765 .bInheritHandle = !(oflags & O_NOINHERIT),
766 };
767 HANDLE handle;
768 DWORD access;
769 int fd;
770
771 /* We only support basic flags. */
772 if (oflags & ~(O_ACCMODE | O_NOINHERIT)) {
773 errno = ENOSYS;
774 return -1;
775 }
776
777 switch (oflags & O_ACCMODE) {
778 case O_RDWR:
779 access = GENERIC_READ | GENERIC_WRITE;
780 break;
781 case O_WRONLY:
782 access = GENERIC_WRITE;
783 break;
784 default:
785 access = GENERIC_READ;
786 break;
787 }
788
789 handle = CreateFileW(filename, access,
790 FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
791 &security_attributes, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
792 if (handle == INVALID_HANDLE_VALUE) {
793 DWORD err = GetLastError();
794 if (err == ERROR_ACCESS_DENIED) {
795 DWORD attrs = GetFileAttributesW(filename);
796 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
797 handle = CreateFileW(filename, access,
798 FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
799 &security_attributes, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL| FILE_FLAG_BACKUP_SEMANTICS, NULL);
800 }
801
802 if (handle == INVALID_HANDLE_VALUE) {
803 err = GetLastError();
804
805 /* See `mingw_open_append()` for why we have this conversion. */
806 if (err == ERROR_INVALID_PARAMETER)
807 err = ERROR_PATH_NOT_FOUND;
808
809 errno = err_win_to_posix(err);
810 return -1;
811 }
812 }
813
814 fd = _open_osfhandle((intptr_t)handle, oflags | O_BINARY);
815 if (fd < 0)
816 CloseHandle(handle);
817 return fd;
818 }
819
820 /*
821 * Does the pathname map to the local named pipe filesystem?
822 * That is, does it have a "//./pipe/" prefix?
823 */
824 static int is_local_named_pipe_path(const char *filename)
825 {
826 return (is_dir_sep(filename[0]) &&
827 is_dir_sep(filename[1]) &&
828 filename[2] == '.' &&
829 is_dir_sep(filename[3]) &&
830 !strncasecmp(filename+4, "pipe", 4) &&
831 is_dir_sep(filename[8]) &&
832 filename[9]);
833 }
834
835 int mingw_open (const char *filename, int oflags, ...)
836 {
837 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
838 va_list args;
839 unsigned mode;
840 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
841 wchar_t wfilename[MAX_PATH];
842 open_fn_t open_fn;
843 WIN32_FILE_ATTRIBUTE_DATA fdata;
844
845 DECLARE_PROC_ADDR(ntdll.dll, NTSTATUS, NTAPI, RtlGetLastNtStatus, void);
846
847 va_start(args, oflags);
848 mode = va_arg(args, int);
849 va_end(args);
850
851 if (!is_valid_win32_path(filename, !create)) {
852 errno = create ? EINVAL : ENOENT;
853 return -1;
854 }
855
856 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
857 open_fn = mingw_open_append;
858 else if (!(oflags & ~(O_ACCMODE | O_NOINHERIT)))
859 open_fn = mingw_open_existing;
860 else
861 open_fn = _wopen;
862
863 if (filename && !strcmp(filename, "/dev/null"))
864 wcscpy(wfilename, L"nul");
865 else if (xutftowcs_path(wfilename, filename) < 0)
866 return -1;
867
868 /*
869 * When `symlink` exists and is a symbolic link pointing to a
870 * non-existing file, `_wopen(symlink, O_CREAT | O_EXCL)` would
871 * create that file. Not what we want: Linux would say `EEXIST`
872 * in that instance, which is therefore what Git expects.
873 */
874 if (create &&
875 GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata) &&
876 (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
877 errno = EEXIST;
878 return -1;
879 }
880
881 fd = open_fn(wfilename, oflags, mode);
882
883 /*
884 * Internally, `_wopen()` uses the `CreateFile()` API with CREATE_NEW,
885 * which may error out with ERROR_ACCESS_DENIED and an NtStatus of
886 * STATUS_DELETE_PENDING when the file is scheduled for deletion via
887 * `DeleteFileW()`. The file essentially exists, so we map errno to
888 * EEXIST instead of EACCESS so that callers don't have to special-case
889 * this.
890 *
891 * This fixes issues for example with the lockfile interface when one
892 * process has a lock that it is about to commit or release while
893 * another process wants to acquire it.
894 */
895 if (fd < 0 && create && GetLastError() == ERROR_ACCESS_DENIED &&
896 INIT_PROC_ADDR(RtlGetLastNtStatus) && RtlGetLastNtStatus() == STATUS_DELETE_PENDING)
897 errno = EEXIST;
898 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
899 DWORD attrs = GetFileAttributesW(wfilename);
900 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
901 errno = EISDIR;
902 }
903 if ((oflags & O_CREAT) && needs_hiding(filename)) {
904 /*
905 * Internally, _wopen() uses the CreateFile() API which errors
906 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
907 * specified and an already existing file's attributes do not
908 * match *exactly*. As there is no mode or flag we can set that
909 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
910 * again *without* the O_CREAT flag (that corresponds to the
911 * CREATE_ALWAYS flag of CreateFile()).
912 */
913 if (fd < 0 && errno == EACCES)
914 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
915 if (fd >= 0 && set_hidden_flag(wfilename, 1))
916 warning("could not mark '%s' as hidden.", filename);
917 }
918 return fd;
919 }
920
921 static BOOL WINAPI ctrl_ignore(DWORD type UNUSED)
922 {
923 return TRUE;
924 }
925
926 #undef fgetc
927 int mingw_fgetc(FILE *stream)
928 {
929 int ch;
930 if (!isatty(_fileno(stream)))
931 return fgetc(stream);
932
933 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
934 while (1) {
935 ch = fgetc(stream);
936 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
937 break;
938
939 /* Ctrl+C was pressed, simulate SIGINT and retry */
940 mingw_raise(SIGINT);
941 }
942 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
943 return ch;
944 }
945
946 #undef fopen
947 FILE *mingw_fopen (const char *filename, const char *otype)
948 {
949 int hide = needs_hiding(filename);
950 FILE *file;
951 wchar_t wfilename[MAX_PATH], wotype[4];
952 if (filename && !strcmp(filename, "/dev/null"))
953 wcscpy(wfilename, L"nul");
954 else if (!is_valid_win32_path(filename, 1)) {
955 int create = otype && strchr(otype, 'w');
956 errno = create ? EINVAL : ENOENT;
957 return NULL;
958 } else if (xutftowcs_path(wfilename, filename) < 0)
959 return NULL;
960
961 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
962 return NULL;
963
964 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
965 error("could not unhide %s", filename);
966 return NULL;
967 }
968 file = _wfopen(wfilename, wotype);
969 if (!file && GetLastError() == ERROR_INVALID_NAME)
970 errno = ENOENT;
971 if (file && hide && set_hidden_flag(wfilename, 1))
972 warning("could not mark '%s' as hidden.", filename);
973 return file;
974 }
975
976 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
977 {
978 int hide = needs_hiding(filename);
979 FILE *file;
980 wchar_t wfilename[MAX_PATH], wotype[4];
981 if (filename && !strcmp(filename, "/dev/null"))
982 wcscpy(wfilename, L"nul");
983 else if (!is_valid_win32_path(filename, 1)) {
984 int create = otype && strchr(otype, 'w');
985 errno = create ? EINVAL : ENOENT;
986 return NULL;
987 } else if (xutftowcs_path(wfilename, filename) < 0)
988 return NULL;
989
990 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
991 return NULL;
992
993 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
994 error("could not unhide %s", filename);
995 return NULL;
996 }
997 file = _wfreopen(wfilename, wotype, stream);
998 if (file && hide && set_hidden_flag(wfilename, 1))
999 warning("could not mark '%s' as hidden.", filename);
1000 return file;
1001 }
1002
1003 #undef fflush
1004 int mingw_fflush(FILE *stream)
1005 {
1006 int ret = fflush(stream);
1007
1008 /*
1009 * write() is used behind the scenes of stdio output functions.
1010 * Since git code does not check for errors after each stdio write
1011 * operation, it can happen that write() is called by a later
1012 * stdio function even if an earlier write() call failed. In the
1013 * case of a pipe whose readable end was closed, only the first
1014 * call to write() reports EPIPE on Windows. Subsequent write()
1015 * calls report EINVAL. It is impossible to notice whether this
1016 * fflush invocation triggered such a case, therefore, we have to
1017 * catch all EINVAL errors whole-sale.
1018 */
1019 if (ret && errno == EINVAL)
1020 errno = EPIPE;
1021
1022 return ret;
1023 }
1024
1025 #undef write
1026 ssize_t mingw_write(int fd, const void *buf, size_t len)
1027 {
1028 ssize_t result = write(fd, buf, len);
1029
1030 if (result < 0 && (errno == EINVAL || errno == ENOSPC) && buf) {
1031 int orig = errno;
1032
1033 /* check if fd is a pipe */
1034 HANDLE h = (HANDLE) _get_osfhandle(fd);
1035 if (GetFileType(h) != FILE_TYPE_PIPE)
1036 errno = orig;
1037 else if (orig == EINVAL)
1038 errno = EPIPE;
1039 else {
1040 DWORD buf_size;
1041
1042 if (!GetNamedPipeInfo(h, NULL, NULL, &buf_size, NULL))
1043 buf_size = 4096;
1044 if (len > buf_size)
1045 return write(fd, buf, buf_size);
1046 errno = orig;
1047 }
1048 }
1049
1050 return result;
1051 }
1052
1053 int mingw_access(const char *filename, int mode)
1054 {
1055 wchar_t wfilename[MAX_PATH];
1056 if (!strcmp("nul", filename) || !strcmp("/dev/null", filename))
1057 return 0;
1058 if (xutftowcs_path(wfilename, filename) < 0)
1059 return -1;
1060 /* X_OK is not supported by the MSVCRT version */
1061 return _waccess(wfilename, mode & ~X_OK);
1062 }
1063
1064 int mingw_chdir(const char *dirname)
1065 {
1066 wchar_t wdirname[MAX_PATH];
1067
1068 if (xutftowcs_path(wdirname, dirname) < 0)
1069 return -1;
1070
1071 if (repo_has_symlinks(the_repository)) {
1072 HANDLE hnd = CreateFileW(wdirname, 0,
1073 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1074 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1075 if (hnd == INVALID_HANDLE_VALUE) {
1076 errno = err_win_to_posix(GetLastError());
1077 return -1;
1078 }
1079 if (!GetFinalPathNameByHandleW(hnd, wdirname, ARRAY_SIZE(wdirname), 0)) {
1080 errno = err_win_to_posix(GetLastError());
1081 CloseHandle(hnd);
1082 return -1;
1083 }
1084 CloseHandle(hnd);
1085 }
1086
1087 return _wchdir(normalize_ntpath(wdirname));
1088 }
1089
1090 int mingw_chmod(const char *filename, int mode)
1091 {
1092 wchar_t wfilename[MAX_PATH];
1093 if (xutftowcs_path(wfilename, filename) < 0)
1094 return -1;
1095 return _wchmod(wfilename, mode);
1096 }
1097
1098 /*
1099 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
1100 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
1101 */
1102 static inline long long filetime_to_hnsec(const FILETIME *ft)
1103 {
1104 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
1105 /* Windows to Unix Epoch conversion */
1106 return winTime - 116444736000000000LL;
1107 }
1108
1109 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
1110 {
1111 long long hnsec = filetime_to_hnsec(ft);
1112 ts->tv_sec = (time_t)(hnsec / 10000000);
1113 ts->tv_nsec = (hnsec % 10000000) * 100;
1114 }
1115
1116 /**
1117 * Verifies that safe_create_leading_directories() would succeed.
1118 */
1119 static int has_valid_directory_prefix(wchar_t *wfilename)
1120 {
1121 size_t n = wcslen(wfilename);
1122
1123 while (n > 0) {
1124 wchar_t c = wfilename[--n];
1125 DWORD attributes;
1126
1127 if (!is_dir_sep(c))
1128 continue;
1129
1130 wfilename[n] = L'\0';
1131 attributes = GetFileAttributesW(wfilename);
1132 wfilename[n] = c;
1133 if (attributes &
1134 (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE))
1135 return 1;
1136 if (attributes == INVALID_FILE_ATTRIBUTES)
1137 switch (GetLastError()) {
1138 case ERROR_PATH_NOT_FOUND:
1139 continue;
1140 case ERROR_FILE_NOT_FOUND:
1141 /* This implies parent directory exists. */
1142 return 1;
1143 }
1144 return 0;
1145 }
1146 return 1;
1147 }
1148
1149 #ifndef _WINNT_H
1150 /*
1151 * The REPARSE_DATA_BUFFER structure is defined in the Windows DDK (in
1152 * ntifs.h) and in MSYS1's winnt.h (which defines _WINNT_H). So define
1153 * it ourselves if we are on MSYS2 (whose winnt.h defines _WINNT_).
1154 */
1155 typedef struct _REPARSE_DATA_BUFFER {
1156 DWORD ReparseTag;
1157 WORD ReparseDataLength;
1158 WORD Reserved;
1159 #ifndef _MSC_VER
1160 _ANONYMOUS_UNION
1161 #endif
1162 union {
1163 struct {
1164 WORD SubstituteNameOffset;
1165 WORD SubstituteNameLength;
1166 WORD PrintNameOffset;
1167 WORD PrintNameLength;
1168 ULONG Flags;
1169 WCHAR PathBuffer[1];
1170 } SymbolicLinkReparseBuffer;
1171 struct {
1172 WORD SubstituteNameOffset;
1173 WORD SubstituteNameLength;
1174 WORD PrintNameOffset;
1175 WORD PrintNameLength;
1176 WCHAR PathBuffer[1];
1177 } MountPointReparseBuffer;
1178 struct {
1179 BYTE DataBuffer[1];
1180 } GenericReparseBuffer;
1181 } DUMMYUNIONNAME;
1182 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
1183 #endif
1184
1185 static int read_reparse_point(const WCHAR *wpath, BOOL fail_on_unknown_tag,
1186 char *tmpbuf, int *plen, DWORD *ptag)
1187 {
1188 HANDLE handle;
1189 WCHAR *wbuf;
1190 REPARSE_DATA_BUFFER *b = alloca(MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
1191 DWORD dummy;
1192
1193 /* read reparse point data */
1194 handle = CreateFileW(wpath, 0,
1195 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1196 OPEN_EXISTING,
1197 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
1198 if (handle == INVALID_HANDLE_VALUE) {
1199 errno = err_win_to_posix(GetLastError());
1200 return -1;
1201 }
1202 if (!DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, NULL, 0, b,
1203 MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &dummy, NULL)) {
1204 errno = err_win_to_posix(GetLastError());
1205 CloseHandle(handle);
1206 return -1;
1207 }
1208 CloseHandle(handle);
1209
1210 /* get target path for symlinks or mount points (aka 'junctions') */
1211 switch ((*ptag = b->ReparseTag)) {
1212 case IO_REPARSE_TAG_SYMLINK:
1213 wbuf = (WCHAR*) (((char*) b->SymbolicLinkReparseBuffer.PathBuffer)
1214 + b->SymbolicLinkReparseBuffer.SubstituteNameOffset);
1215 *(WCHAR*) (((char*) wbuf)
1216 + b->SymbolicLinkReparseBuffer.SubstituteNameLength) = 0;
1217 break;
1218 case IO_REPARSE_TAG_MOUNT_POINT:
1219 wbuf = (WCHAR*) (((char*) b->MountPointReparseBuffer.PathBuffer)
1220 + b->MountPointReparseBuffer.SubstituteNameOffset);
1221 *(WCHAR*) (((char*) wbuf)
1222 + b->MountPointReparseBuffer.SubstituteNameLength) = 0;
1223 break;
1224 default:
1225 if (fail_on_unknown_tag) {
1226 errno = EINVAL;
1227 return -1;
1228 } else {
1229 *plen = MAX_PATH;
1230 return 0;
1231 }
1232 }
1233
1234 if ((*plen =
1235 xwcstoutf(tmpbuf, normalize_ntpath(wbuf), MAX_PATH)) < 0)
1236 return -1;
1237 return 0;
1238 }
1239
1240 int mingw_lstat(const char *file_name, struct stat *buf)
1241 {
1242 WIN32_FILE_ATTRIBUTE_DATA fdata;
1243 DWORD reparse_tag = 0;
1244 int link_len = 0;
1245 wchar_t wfilename[MAX_PATH];
1246 int wlen = xutftowcs_path(wfilename, file_name);
1247 if (wlen < 0)
1248 return -1;
1249
1250 /* strip trailing '/', or GetFileAttributes will fail */
1251 while (wlen && is_dir_sep(wfilename[wlen - 1]))
1252 wfilename[--wlen] = 0;
1253 if (!wlen) {
1254 errno = ENOENT;
1255 return -1;
1256 }
1257
1258 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
1259 /* for reparse points, get the link tag and length */
1260 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1261 char tmpbuf[MAX_PATH];
1262
1263 if (read_reparse_point(wfilename, FALSE, tmpbuf,
1264 &link_len, &reparse_tag) < 0)
1265 return -1;
1266 }
1267 buf->st_ino = 0;
1268 buf->st_gid = 0;
1269 buf->st_uid = 0;
1270 buf->st_nlink = 1;
1271 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes,
1272 reparse_tag);
1273 buf->st_size = S_ISLNK(buf->st_mode) ? link_len :
1274 fdata.nFileSizeLow | (((off_t) fdata.nFileSizeHigh) << 32);
1275 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
1276 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
1277 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
1278 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
1279 return 0;
1280 }
1281
1282 switch (GetLastError()) {
1283 case ERROR_ACCESS_DENIED:
1284 case ERROR_SHARING_VIOLATION:
1285 case ERROR_LOCK_VIOLATION:
1286 case ERROR_SHARING_BUFFER_EXCEEDED:
1287 errno = EACCES;
1288 break;
1289 case ERROR_BUFFER_OVERFLOW:
1290 errno = ENAMETOOLONG;
1291 break;
1292 case ERROR_NOT_ENOUGH_MEMORY:
1293 errno = ENOMEM;
1294 break;
1295 case ERROR_PATH_NOT_FOUND:
1296 if (!has_valid_directory_prefix(wfilename)) {
1297 errno = ENOTDIR;
1298 break;
1299 }
1300 /* fallthru */
1301 default:
1302 errno = ENOENT;
1303 break;
1304 }
1305 return -1;
1306 }
1307
1308 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
1309 {
1310 BY_HANDLE_FILE_INFORMATION fdata;
1311
1312 if (!GetFileInformationByHandle(hnd, &fdata)) {
1313 errno = err_win_to_posix(GetLastError());
1314 return -1;
1315 }
1316
1317 buf->st_ino = 0;
1318 buf->st_gid = 0;
1319 buf->st_uid = 0;
1320 buf->st_nlink = 1;
1321 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes, 0);
1322 buf->st_size = fdata.nFileSizeLow |
1323 (((off_t)fdata.nFileSizeHigh)<<32);
1324 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
1325 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
1326 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
1327 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
1328 return 0;
1329 }
1330
1331 int mingw_stat(const char *file_name, struct stat *buf)
1332 {
1333 wchar_t wfile_name[MAX_PATH];
1334 HANDLE hnd;
1335 int result;
1336
1337 /* open the file and let Windows resolve the links */
1338 if (xutftowcs_path(wfile_name, file_name) < 0)
1339 return -1;
1340 hnd = CreateFileW(wfile_name, 0,
1341 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1342 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1343 if (hnd == INVALID_HANDLE_VALUE) {
1344 DWORD err = GetLastError();
1345
1346 if (err == ERROR_ACCESS_DENIED &&
1347 !mingw_lstat(file_name, buf) &&
1348 !S_ISLNK(buf->st_mode))
1349 /*
1350 * POSIX semantics state to still try to fill
1351 * information, even if permission is denied to create
1352 * a file handle.
1353 */
1354 return 0;
1355
1356 errno = err_win_to_posix(err);
1357 return -1;
1358 }
1359 result = get_file_info_by_handle(hnd, buf);
1360 CloseHandle(hnd);
1361 return result;
1362 }
1363
1364 int mingw_fstat(int fd, struct stat *buf)
1365 {
1366 HANDLE fh = (HANDLE)_get_osfhandle(fd);
1367 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
1368
1369 switch (type) {
1370 case FILE_TYPE_DISK:
1371 return get_file_info_by_handle(fh, buf);
1372
1373 case FILE_TYPE_CHAR:
1374 case FILE_TYPE_PIPE:
1375 /* initialize stat fields */
1376 memset(buf, 0, sizeof(*buf));
1377 buf->st_nlink = 1;
1378
1379 if (type == FILE_TYPE_CHAR) {
1380 buf->st_mode = _S_IFCHR;
1381 } else {
1382 buf->st_mode = _S_IFIFO;
1383 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
1384 buf->st_size = avail;
1385 }
1386 return 0;
1387
1388 default:
1389 errno = EBADF;
1390 return -1;
1391 }
1392 }
1393
1394 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
1395 {
1396 long long winTime = t * 10000000LL + 116444736000000000LL;
1397 ft->dwLowDateTime = winTime;
1398 ft->dwHighDateTime = winTime >> 32;
1399 }
1400
1401 int mingw_utime (const char *file_name, const struct utimbuf *times)
1402 {
1403 FILETIME mft, aft;
1404 int rc;
1405 DWORD attrs;
1406 wchar_t wfilename[MAX_PATH];
1407 HANDLE osfilehandle;
1408
1409 if (xutftowcs_path(wfilename, file_name) < 0)
1410 return -1;
1411
1412 /* must have write permission */
1413 attrs = GetFileAttributesW(wfilename);
1414 if (attrs != INVALID_FILE_ATTRIBUTES &&
1415 (attrs & FILE_ATTRIBUTE_READONLY)) {
1416 /* ignore errors here; open() will report them */
1417 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
1418 }
1419
1420 osfilehandle = CreateFileW(wfilename,
1421 FILE_WRITE_ATTRIBUTES,
1422 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1423 NULL,
1424 OPEN_EXISTING,
1425 (attrs != INVALID_FILE_ATTRIBUTES &&
1426 (attrs & FILE_ATTRIBUTE_DIRECTORY)) ?
1427 FILE_FLAG_BACKUP_SEMANTICS : 0,
1428 NULL);
1429 if (osfilehandle == INVALID_HANDLE_VALUE) {
1430 errno = err_win_to_posix(GetLastError());
1431 rc = -1;
1432 goto revert_attrs;
1433 }
1434
1435 if (times) {
1436 time_t_to_filetime(times->modtime, &mft);
1437 time_t_to_filetime(times->actime, &aft);
1438 } else {
1439 GetSystemTimeAsFileTime(&mft);
1440 aft = mft;
1441 }
1442
1443 if (!SetFileTime(osfilehandle, NULL, &aft, &mft)) {
1444 errno = EINVAL;
1445 rc = -1;
1446 } else
1447 rc = 0;
1448
1449 if (osfilehandle != INVALID_HANDLE_VALUE)
1450 CloseHandle(osfilehandle);
1451
1452 revert_attrs:
1453 if (attrs != INVALID_FILE_ATTRIBUTES &&
1454 (attrs & FILE_ATTRIBUTE_READONLY)) {
1455 /* ignore errors again */
1456 SetFileAttributesW(wfilename, attrs);
1457 }
1458 return rc;
1459 }
1460
1461 #undef strftime
1462 size_t mingw_strftime(char *s, size_t max,
1463 const char *format, const struct tm *tm)
1464 {
1465 #ifdef _UCRT
1466 size_t ret = strftime(s, max, format, tm);
1467 #else
1468 /* a pointer to the original strftime in case we can't find the UCRT version */
1469 static size_t (*fallback)(char *, size_t, const char *, const struct tm *) = strftime;
1470 size_t ret;
1471 DECLARE_PROC_ADDR(ucrtbase.dll, size_t, __cdecl, strftime, char *, size_t,
1472 const char *, const struct tm *);
1473
1474 if (INIT_PROC_ADDR(strftime))
1475 ret = strftime(s, max, format, tm);
1476 else
1477 ret = fallback(s, max, format, tm);
1478 #endif
1479
1480 if (!ret && errno == EINVAL)
1481 die("invalid strftime format: '%s'", format);
1482 return ret;
1483 }
1484
1485 unsigned int sleep (unsigned int seconds)
1486 {
1487 Sleep(seconds*1000);
1488 return 0;
1489 }
1490
1491 int mkstemp(char *template)
1492 {
1493 return git_mkstemp_mode(template, 0600);
1494 }
1495
1496 int gettimeofday(struct timeval *tv, void *tz UNUSED)
1497 {
1498 FILETIME ft;
1499 long long hnsec;
1500
1501 GetSystemTimeAsFileTime(&ft);
1502 hnsec = filetime_to_hnsec(&ft);
1503 tv->tv_sec = hnsec / 10000000;
1504 tv->tv_usec = (hnsec % 10000000) / 10;
1505 return 0;
1506 }
1507
1508 int pipe(int filedes[2])
1509 {
1510 HANDLE h[2];
1511
1512 /* this creates non-inheritable handles */
1513 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
1514 errno = err_win_to_posix(GetLastError());
1515 return -1;
1516 }
1517 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
1518 if (filedes[0] < 0) {
1519 CloseHandle(h[0]);
1520 CloseHandle(h[1]);
1521 return -1;
1522 }
1523 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
1524 if (filedes[1] < 0) {
1525 close(filedes[0]);
1526 CloseHandle(h[1]);
1527 return -1;
1528 }
1529 return 0;
1530 }
1531
1532 #ifndef __MINGW64__
1533 struct tm *gmtime_r(const time_t *timep, struct tm *result)
1534 {
1535 if (gmtime_s(result, timep) == 0)
1536 return result;
1537 return NULL;
1538 }
1539
1540 struct tm *localtime_r(const time_t *timep, struct tm *result)
1541 {
1542 if (localtime_s(result, timep) == 0)
1543 return result;
1544 return NULL;
1545 }
1546 #endif
1547
1548 char *mingw_getcwd(char *pointer, int len)
1549 {
1550 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1551 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1552 HANDLE hnd;
1553
1554 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1555 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1556 return NULL;
1557 }
1558 hnd = CreateFileW(cwd, 0,
1559 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1560 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1561 if (hnd != INVALID_HANDLE_VALUE) {
1562 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1563 CloseHandle(hnd);
1564 if (!ret || ret >= ARRAY_SIZE(wpointer))
1565 return NULL;
1566 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1567 return NULL;
1568 return pointer;
1569 }
1570 if (GetFileAttributesW(cwd) == INVALID_FILE_ATTRIBUTES) {
1571 errno = ENOENT;
1572 return NULL;
1573 }
1574 if (xwcstoutf(pointer, cwd, len) < 0)
1575 return NULL;
1576 convert_slashes(pointer);
1577 return pointer;
1578 }
1579
1580 /*
1581 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1582 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1583 */
1584 static const char *quote_arg_msvc(const char *arg)
1585 {
1586 /* count chars to quote */
1587 int len = 0, n = 0;
1588 int force_quotes = 0;
1589 char *q, *d;
1590 const char *p = arg;
1591 if (!*p) force_quotes = 1;
1592 while (*p) {
1593 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1594 force_quotes = 1;
1595 else if (*p == '"')
1596 n++;
1597 else if (*p == '\\') {
1598 int count = 0;
1599 while (*p == '\\') {
1600 count++;
1601 p++;
1602 len++;
1603 }
1604 if (*p == '"' || !*p)
1605 n += count*2 + 1;
1606 continue;
1607 }
1608 len++;
1609 p++;
1610 }
1611 if (!force_quotes && n == 0)
1612 return arg;
1613
1614 /* insert \ where necessary */
1615 d = q = xmalloc(st_add3(len, n, 3));
1616 *d++ = '"';
1617 while (*arg) {
1618 if (*arg == '"')
1619 *d++ = '\\';
1620 else if (*arg == '\\') {
1621 int count = 0;
1622 while (*arg == '\\') {
1623 count++;
1624 *d++ = *arg++;
1625 }
1626 if (*arg == '"' || !*arg) {
1627 while (count-- > 0)
1628 *d++ = '\\';
1629 /* don't escape the surrounding end quote */
1630 if (!*arg)
1631 break;
1632 *d++ = '\\';
1633 }
1634 }
1635 *d++ = *arg++;
1636 }
1637 *d++ = '"';
1638 *d++ = '\0';
1639 return q;
1640 }
1641
1642 #include "quote.h"
1643
1644 static const char *quote_arg_msys2(const char *arg)
1645 {
1646 struct strbuf buf = STRBUF_INIT;
1647 const char *p2 = arg, *p;
1648
1649 for (p = arg; *p; p++) {
1650 int ws = isspace(*p);
1651 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1652 *p != '?' && *p != '*' && *p != '~')
1653 continue;
1654 if (!buf.len)
1655 strbuf_addch(&buf, '"');
1656 if (p != p2)
1657 strbuf_add(&buf, p2, p - p2);
1658 if (*p == '\\' || *p == '"')
1659 strbuf_addch(&buf, '\\');
1660 p2 = p;
1661 }
1662
1663 if (p == arg)
1664 strbuf_addch(&buf, '"');
1665 else if (!buf.len)
1666 return arg;
1667 else
1668 strbuf_add(&buf, p2, p - p2);
1669
1670 strbuf_addch(&buf, '"');
1671 return strbuf_detach(&buf, 0);
1672 }
1673
1674 static const char *parse_interpreter(const char *cmd)
1675 {
1676 static char buf[100];
1677 char *p, *opt;
1678 ssize_t n; /* read() can return negative values */
1679 int fd;
1680
1681 /* don't even try a .exe */
1682 n = strlen(cmd);
1683 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1684 return NULL;
1685
1686 fd = open(cmd, O_RDONLY);
1687 if (fd < 0)
1688 return NULL;
1689 n = read(fd, buf, sizeof(buf)-1);
1690 close(fd);
1691 if (n < 4) /* at least '#!/x' and not error */
1692 return NULL;
1693
1694 if (buf[0] != '#' || buf[1] != '!')
1695 return NULL;
1696 buf[n] = '\0';
1697 p = buf + strcspn(buf, "\r\n");
1698 if (!*p)
1699 return NULL;
1700
1701 *p = '\0';
1702 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1703 return NULL;
1704 /* strip options */
1705 if ((opt = strchr(p+1, ' ')))
1706 *opt = '\0';
1707 return p+1;
1708 }
1709
1710 /*
1711 * exe_only means that we only want to detect .exe files, but not scripts
1712 * (which do not have an extension)
1713 */
1714 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1715 int isexe, int exe_only)
1716 {
1717 char path[MAX_PATH];
1718 wchar_t wpath[MAX_PATH];
1719 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1720
1721 if (xutftowcs_path(wpath, path) < 0)
1722 return NULL;
1723
1724 if (!isexe && _waccess(wpath, F_OK) == 0)
1725 return xstrdup(path);
1726 wpath[wcslen(wpath)-4] = '\0';
1727 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1728 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1729 path[strlen(path)-4] = '\0';
1730 return xstrdup(path);
1731 }
1732 }
1733 return NULL;
1734 }
1735
1736 /*
1737 * Determines the absolute path of cmd using the split path in path.
1738 * If cmd contains a slash or backslash, no lookup is performed.
1739 */
1740 static char *path_lookup(const char *cmd, int exe_only)
1741 {
1742 const char *path;
1743 char *prog = NULL;
1744 size_t len = strlen(cmd);
1745 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1746
1747 if (strpbrk(cmd, "/\\"))
1748 return xstrdup(cmd);
1749
1750 path = mingw_getenv("PATH");
1751 if (!path)
1752 return NULL;
1753
1754 while (!prog) {
1755 const char *sep = strchrnul(path, ';');
1756 int dirlen = sep - path;
1757 if (dirlen)
1758 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1759 if (!*sep)
1760 break;
1761 path = sep + 1;
1762 }
1763
1764 return prog;
1765 }
1766
1767 char *mingw_locate_in_PATH(const char *cmd)
1768 {
1769 return path_lookup(cmd, 0);
1770 }
1771
1772 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1773 {
1774 while (*s && *s != c)
1775 s++;
1776 return s;
1777 }
1778
1779 /* Compare only keys */
1780 static int wenvcmp(const void *a, const void *b)
1781 {
1782 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1783 size_t p_len, q_len;
1784
1785 /* Find the keys */
1786 p_len = wcschrnul(p, L'=') - p;
1787 q_len = wcschrnul(q, L'=') - q;
1788
1789 /* If the length differs, include the shorter key's NUL */
1790 if (p_len < q_len)
1791 p_len++;
1792 else if (p_len > q_len)
1793 p_len = q_len + 1;
1794
1795 return _wcsnicmp(p, q, p_len);
1796 }
1797
1798 /*
1799 * Build an environment block combining the inherited environment
1800 * merged with the given list of settings.
1801 *
1802 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1803 * Values of the form "KEY" in deltaenv delete inherited values.
1804 *
1805 * Multiple entries in deltaenv for the same key are explicitly allowed.
1806 *
1807 * We return a contiguous block of UNICODE strings with a final trailing
1808 * zero word.
1809 */
1810 static wchar_t *make_environment_block(char **deltaenv)
1811 {
1812 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1813 size_t wlen, s, delta_size, size;
1814
1815 wchar_t **array = NULL;
1816 size_t alloc = 0, nr = 0, i;
1817
1818 size = 1; /* for extra NUL at the end */
1819
1820 /* If there is no deltaenv to apply, simply return a copy. */
1821 if (!deltaenv || !*deltaenv) {
1822 for (p = wenv; p && *p; ) {
1823 size_t s = wcslen(p) + 1;
1824 size += s;
1825 p += s;
1826 }
1827
1828 DUP_ARRAY(result, wenv, size);
1829 FreeEnvironmentStringsW(wenv);
1830 return result;
1831 }
1832
1833 /*
1834 * If there is a deltaenv, let's accumulate all keys into `array`,
1835 * sort them using the stable git_stable_qsort() and then copy,
1836 * skipping duplicate keys
1837 */
1838 for (p = wenv; p && *p; ) {
1839 ALLOC_GROW(array, nr + 1, alloc);
1840 s = wcslen(p) + 1;
1841 array[nr++] = p;
1842 p += s;
1843 size += s;
1844 }
1845
1846 /* (over-)assess size needed for wchar version of deltaenv */
1847 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1848 delta_size += strlen(deltaenv[i]) * 2 + 1;
1849 ALLOC_ARRAY(wdeltaenv, delta_size);
1850
1851 /* convert the deltaenv, appending to array */
1852 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1853 ALLOC_GROW(array, nr + 1, alloc);
1854 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1855 array[nr++] = p;
1856 p += wlen + 1;
1857 }
1858
1859 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
1860 ALLOC_ARRAY(result, size + delta_size);
1861
1862 for (p = result, i = 0; i < nr; i++) {
1863 /* Skip any duplicate keys; last one wins */
1864 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1865 i++;
1866
1867 /* Skip "to delete" entry */
1868 if (!wcschr(array[i], L'='))
1869 continue;
1870
1871 size = wcslen(array[i]) + 1;
1872 COPY_ARRAY(p, array[i], size);
1873 p += size;
1874 }
1875 *p = L'\0';
1876
1877 free(array);
1878 free(wdeltaenv);
1879 FreeEnvironmentStringsW(wenv);
1880 return result;
1881 }
1882
1883 static void do_unset_environment_variables(void)
1884 {
1885 static int done;
1886 char *p = unset_environment_variables;
1887
1888 if (done || !p)
1889 return;
1890 done = 1;
1891
1892 for (;;) {
1893 char *comma = strchr(p, ',');
1894
1895 if (comma)
1896 *comma = '\0';
1897 unsetenv(p);
1898 if (!comma)
1899 break;
1900 p = comma + 1;
1901 }
1902 }
1903
1904 struct pinfo_t {
1905 struct pinfo_t *next;
1906 pid_t pid;
1907 HANDLE proc;
1908 };
1909 static struct pinfo_t *pinfo = NULL;
1910 CRITICAL_SECTION pinfo_cs;
1911
1912 /* Used to match and chomp off path components */
1913 static inline int match_last_path_component(const char *path, size_t *len,
1914 const char *component)
1915 {
1916 size_t component_len = strlen(component);
1917 if (*len < component_len + 1 ||
1918 !is_dir_sep(path[*len - component_len - 1]) ||
1919 fspathncmp(path + *len - component_len, component, component_len))
1920 return 0;
1921 *len -= component_len + 1;
1922 /* chomp off repeated dir separators */
1923 while (*len > 0 && is_dir_sep(path[*len - 1]))
1924 (*len)--;
1925 return 1;
1926 }
1927
1928 static int is_msys2_sh(const char *cmd)
1929 {
1930 if (!cmd)
1931 return 0;
1932
1933 if (!strcmp(cmd, "sh")) {
1934 static int ret = -1;
1935 char *p;
1936
1937 if (ret >= 0)
1938 return ret;
1939
1940 p = path_lookup(cmd, 0);
1941 if (!p)
1942 ret = 0;
1943 else {
1944 size_t len = strlen(p);
1945
1946 ret = match_last_path_component(p, &len, "sh.exe") &&
1947 match_last_path_component(p, &len, "bin") &&
1948 match_last_path_component(p, &len, "usr");
1949 free(p);
1950 }
1951 return ret;
1952 }
1953
1954 if (ends_with(cmd, "\\sh.exe") || ends_with(cmd, "/sh.exe")) {
1955 static char *sh;
1956
1957 if (!sh)
1958 sh = path_lookup("sh", 0);
1959
1960 return !fspathcmp(cmd, sh);
1961 }
1962
1963 return 0;
1964 }
1965
1966 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1967 const char *dir,
1968 int prepend_cmd, int fhin, int fhout, int fherr)
1969 {
1970 STARTUPINFOEXW si;
1971 PROCESS_INFORMATION pi;
1972 LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1973 HANDLE stdhandles[3];
1974 DWORD stdhandles_count = 0;
1975 SIZE_T size;
1976 struct strbuf args;
1977 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1978 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1979 BOOL ret;
1980 HANDLE cons;
1981 const char *(*quote_arg)(const char *arg) =
1982 is_msys2_sh(cmd ? cmd : *argv) ?
1983 quote_arg_msys2 : quote_arg_msvc;
1984 const char *strace_env;
1985
1986 /* Make sure to override previous errors, if any */
1987 errno = 0;
1988
1989 do_unset_environment_variables();
1990
1991 /* Determine whether or not we are associated to a console */
1992 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
1993 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1994 FILE_ATTRIBUTE_NORMAL, NULL);
1995 if (cons == INVALID_HANDLE_VALUE) {
1996 /* There is no console associated with this process.
1997 * Since the child is a console process, Windows
1998 * would normally create a console window. But
1999 * since we'll be redirecting std streams, we do
2000 * not need the console.
2001 * It is necessary to use DETACHED_PROCESS
2002 * instead of CREATE_NO_WINDOW to make ssh
2003 * recognize that it has no console.
2004 */
2005 flags |= DETACHED_PROCESS;
2006 } else {
2007 /* There is already a console. If we specified
2008 * DETACHED_PROCESS here, too, Windows would
2009 * disassociate the child from the console.
2010 * The same is true for CREATE_NO_WINDOW.
2011 * Go figure!
2012 */
2013 CloseHandle(cons);
2014 }
2015 memset(&si, 0, sizeof(si));
2016 si.StartupInfo.cb = sizeof(si);
2017 si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
2018 si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
2019 si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
2020
2021 /* The list of handles cannot contain duplicates */
2022 if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
2023 stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
2024 if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
2025 si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
2026 stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
2027 if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
2028 si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
2029 si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
2030 stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
2031 if (stdhandles_count)
2032 si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
2033
2034 if (*argv && !strcmp(cmd, *argv))
2035 wcmd[0] = L'\0';
2036 else if (xutftowcs_path(wcmd, cmd) < 0)
2037 return -1;
2038 if (dir && xutftowcs_path(wdir, dir) < 0)
2039 return -1;
2040
2041 /* concatenate argv, quoting args as we go */
2042 strbuf_init(&args, 0);
2043 if (prepend_cmd) {
2044 char *quoted = (char *)quote_arg(cmd);
2045 strbuf_addstr(&args, quoted);
2046 if (quoted != cmd)
2047 free(quoted);
2048 }
2049 for (; *argv; argv++) {
2050 char *quoted = (char *)quote_arg(*argv);
2051 if (*args.buf)
2052 strbuf_addch(&args, ' ');
2053 strbuf_addstr(&args, quoted);
2054 if (quoted != *argv)
2055 free(quoted);
2056 }
2057
2058 strace_env = getenv("GIT_STRACE_COMMANDS");
2059 if (strace_env) {
2060 char *p = path_lookup("strace.exe", 1);
2061 if (!p)
2062 return error("strace not found!");
2063 if (xutftowcs_path(wcmd, p) < 0) {
2064 free(p);
2065 return -1;
2066 }
2067 free(p);
2068 if (!strcmp("1", strace_env) ||
2069 !strcasecmp("yes", strace_env) ||
2070 !strcasecmp("true", strace_env))
2071 strbuf_insert(&args, 0, "strace ", 7);
2072 else {
2073 const char *quoted = quote_arg(strace_env);
2074 struct strbuf buf = STRBUF_INIT;
2075 strbuf_addf(&buf, "strace -o %s ", quoted);
2076 if (quoted != strace_env)
2077 free((char *)quoted);
2078 strbuf_insert(&args, 0, buf.buf, buf.len);
2079 strbuf_release(&buf);
2080 }
2081 }
2082
2083 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
2084 xutftowcs(wargs, args.buf, 2 * args.len + 1);
2085 strbuf_release(&args);
2086
2087 wenvblk = make_environment_block(deltaenv);
2088
2089 memset(&pi, 0, sizeof(pi));
2090 if (stdhandles_count &&
2091 (InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
2092 GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
2093 (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
2094 (HeapAlloc(GetProcessHeap(), 0, size))) &&
2095 InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
2096 UpdateProcThreadAttribute(attr_list, 0,
2097 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
2098 stdhandles,
2099 stdhandles_count * sizeof(HANDLE),
2100 NULL, NULL)) {
2101 si.lpAttributeList = attr_list;
2102 flags |= EXTENDED_STARTUPINFO_PRESENT;
2103 }
2104
2105 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
2106 stdhandles_count ? TRUE : FALSE,
2107 flags, wenvblk, dir ? wdir : NULL,
2108 &si.StartupInfo, &pi);
2109
2110 /*
2111 * On the off-chance that something with the file handle restriction
2112 * went wrong, silently fall back to trying without it.
2113 */
2114 if (!ret && stdhandles_count) {
2115 DWORD err = GetLastError();
2116 struct strbuf buf = STRBUF_INIT;
2117
2118 flags &= ~EXTENDED_STARTUPINFO_PRESENT;
2119 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
2120 TRUE, flags, wenvblk, dir ? wdir : NULL,
2121 &si.StartupInfo, &pi);
2122 if (!ret)
2123 errno = err_win_to_posix(GetLastError());
2124 if (ret && buf.len) {
2125 warning("failed to restrict file handles (%ld)\n\n%s",
2126 err, buf.buf);
2127 }
2128 strbuf_release(&buf);
2129 } else if (!ret)
2130 errno = err_win_to_posix(GetLastError());
2131
2132 if (si.lpAttributeList)
2133 DeleteProcThreadAttributeList(si.lpAttributeList);
2134 if (attr_list)
2135 HeapFree(GetProcessHeap(), 0, attr_list);
2136
2137 free(wenvblk);
2138 free(wargs);
2139
2140 if (!ret)
2141 return -1;
2142
2143 CloseHandle(pi.hThread);
2144
2145 /*
2146 * The process ID is the human-readable identifier of the process
2147 * that we want to present in log and error messages. The handle
2148 * is not useful for this purpose. But we cannot close it, either,
2149 * because it is not possible to turn a process ID into a process
2150 * handle after the process terminated.
2151 * Keep the handle in a list for waitpid.
2152 */
2153 EnterCriticalSection(&pinfo_cs);
2154 {
2155 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
2156 info->pid = pi.dwProcessId;
2157 info->proc = pi.hProcess;
2158 info->next = pinfo;
2159 pinfo = info;
2160 }
2161 LeaveCriticalSection(&pinfo_cs);
2162
2163 return (pid_t)pi.dwProcessId;
2164 }
2165
2166 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
2167 {
2168 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
2169 }
2170
2171 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
2172 const char *dir,
2173 int fhin, int fhout, int fherr)
2174 {
2175 pid_t pid;
2176 char *prog = path_lookup(cmd, 0);
2177
2178 if (!prog) {
2179 errno = ENOENT;
2180 pid = -1;
2181 }
2182 else {
2183 const char *interpr = parse_interpreter(prog);
2184
2185 if (interpr) {
2186 const char *argv0 = argv[0];
2187 char *iprog = path_lookup(interpr, 1);
2188 argv[0] = prog;
2189 if (!iprog) {
2190 errno = ENOENT;
2191 pid = -1;
2192 }
2193 else {
2194 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
2195 fhin, fhout, fherr);
2196 free(iprog);
2197 }
2198 argv[0] = argv0;
2199 }
2200 else
2201 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
2202 fhin, fhout, fherr);
2203 free(prog);
2204 }
2205 return pid;
2206 }
2207
2208 static int try_shell_exec(const char *cmd, char *const *argv)
2209 {
2210 const char *interpr = parse_interpreter(cmd);
2211 char *prog;
2212 int pid = 0;
2213
2214 if (!interpr)
2215 return 0;
2216 prog = path_lookup(interpr, 1);
2217 if (prog) {
2218 int exec_id;
2219 int argc = 0;
2220 char **argv2;
2221 while (argv[argc]) argc++;
2222 ALLOC_ARRAY(argv2, argc + 1);
2223 argv2[0] = (char *)cmd; /* full path to the script file */
2224 COPY_ARRAY(&argv2[1], &argv[1], argc);
2225 exec_id = trace2_exec(prog, (const char **)argv2);
2226 pid = mingw_spawnv(prog, (const char **)argv2, 1);
2227 if (pid >= 0) {
2228 int status;
2229 if (waitpid(pid, &status, 0) < 0)
2230 status = 255;
2231 trace2_exec_result(exec_id, status);
2232 exit(status);
2233 }
2234 trace2_exec_result(exec_id, -1);
2235 pid = 1; /* indicate that we tried but failed */
2236 free(prog);
2237 free(argv2);
2238 }
2239 return pid;
2240 }
2241
2242 int mingw_execv(const char *cmd, char *const *argv)
2243 {
2244 /* check if git_command is a shell script */
2245 if (!try_shell_exec(cmd, argv)) {
2246 int pid, status;
2247 int exec_id;
2248
2249 exec_id = trace2_exec(cmd, (const char **)argv);
2250 pid = mingw_spawnv(cmd, (const char **)argv, 0);
2251 if (pid < 0) {
2252 trace2_exec_result(exec_id, -1);
2253 return -1;
2254 }
2255 if (waitpid(pid, &status, 0) < 0)
2256 status = 255;
2257 trace2_exec_result(exec_id, status);
2258 exit(status);
2259 }
2260 return -1;
2261 }
2262
2263 int mingw_execvp(const char *cmd, char *const *argv)
2264 {
2265 char *prog = path_lookup(cmd, 0);
2266
2267 if (prog) {
2268 mingw_execv(prog, argv);
2269 free(prog);
2270 } else
2271 errno = ENOENT;
2272
2273 return -1;
2274 }
2275
2276 int mingw_kill(pid_t pid, int sig)
2277 {
2278 if (pid > 0 && sig == SIGTERM) {
2279 HANDLE h = OpenProcess(PROCESS_CREATE_THREAD |
2280 PROCESS_QUERY_INFORMATION |
2281 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2282 PROCESS_VM_READ | PROCESS_TERMINATE,
2283 FALSE, pid);
2284 int ret;
2285
2286 if (h)
2287 ret = exit_process(h, 128 + sig);
2288 else {
2289 h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
2290 if (!h) {
2291 errno = err_win_to_posix(GetLastError());
2292 return -1;
2293 }
2294 ret = terminate_process_tree(h, 128 + sig);
2295 }
2296 if (ret)
2297 errno = err_win_to_posix(GetLastError());
2298 return ret;
2299 } else if (pid > 0 && sig == 0) {
2300 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
2301 if (h) {
2302 CloseHandle(h);
2303 return 0;
2304 }
2305 /*
2306 * OpenProcess returns ERROR_INVALID_PARAMETER for
2307 * non-existent PIDs. Map this to ESRCH for POSIX
2308 * compatibility with kill(pid, 0).
2309 */
2310 if (GetLastError() == ERROR_INVALID_PARAMETER)
2311 errno = ESRCH;
2312 else
2313 errno = err_win_to_posix(GetLastError());
2314 return -1;
2315 }
2316
2317 errno = EINVAL;
2318 return -1;
2319 }
2320
2321 /*
2322 * UTF-8 versions of getenv(), putenv() and unsetenv().
2323 * Internally, they use the CRT's stock UNICODE routines
2324 * to avoid data loss.
2325 */
2326 char *mingw_getenv(const char *name)
2327 {
2328 #define GETENV_MAX_RETAIN 64
2329 static char *values[GETENV_MAX_RETAIN];
2330 static int value_counter;
2331 size_t len_key, len_value;
2332 wchar_t *w_key;
2333 char *value;
2334 wchar_t w_value[32768];
2335
2336 if (!name || !*name)
2337 return NULL;
2338
2339 len_key = strlen(name) + 1;
2340 /* We cannot use xcalloc() here because that uses getenv() itself */
2341 w_key = calloc(len_key, sizeof(wchar_t));
2342 if (!w_key)
2343 die("Out of memory, (tried to allocate %"PRIuMAX" wchar_t's)",
2344 (uintmax_t)len_key);
2345 xutftowcs(w_key, name, len_key);
2346 /* GetEnvironmentVariableW() only sets the last error upon failure */
2347 SetLastError(ERROR_SUCCESS);
2348 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
2349 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
2350 free(w_key);
2351 return NULL;
2352 }
2353 free(w_key);
2354
2355 len_value = len_value * 3 + 1;
2356 /* We cannot use xcalloc() here because that uses getenv() itself */
2357 value = calloc(len_value, sizeof(char));
2358 if (!value)
2359 die("Out of memory, (tried to allocate %"PRIuMAX" bytes)",
2360 (uintmax_t)len_value);
2361 xwcstoutf(value, w_value, len_value);
2362
2363 /*
2364 * We return `value` which is an allocated value and the caller is NOT
2365 * expecting to have to free it, so we keep a round-robin array,
2366 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
2367 */
2368 free(values[value_counter]);
2369 values[value_counter++] = value;
2370 if (value_counter >= ARRAY_SIZE(values))
2371 value_counter = 0;
2372
2373 return value;
2374 }
2375
2376 int mingw_putenv(const char *namevalue)
2377 {
2378 size_t size;
2379 wchar_t *wide, *equal;
2380 BOOL result;
2381
2382 if (!namevalue || !*namevalue)
2383 return 0;
2384
2385 size = strlen(namevalue) * 2 + 1;
2386 wide = calloc(size, sizeof(wchar_t));
2387 if (!wide)
2388 die("Out of memory, (tried to allocate %" PRIuMAX " wchar_t's)",
2389 (uintmax_t)size);
2390 xutftowcs(wide, namevalue, size);
2391 equal = wcschr(wide, L'=');
2392 if (!equal)
2393 result = SetEnvironmentVariableW(wide, NULL);
2394 else {
2395 *equal = L'\0';
2396 result = SetEnvironmentVariableW(wide, equal + 1);
2397 }
2398 free(wide);
2399
2400 if (!result)
2401 errno = err_win_to_posix(GetLastError());
2402
2403 return result ? 0 : -1;
2404 }
2405
2406 static void ensure_socket_initialization(void)
2407 {
2408 WSADATA wsa;
2409 static int initialized = 0;
2410
2411 if (initialized)
2412 return;
2413
2414 if (WSAStartup(MAKEWORD(2,2), &wsa))
2415 die("unable to initialize winsock subsystem, error %d",
2416 WSAGetLastError());
2417
2418 atexit((void(*)(void)) WSACleanup);
2419 initialized = 1;
2420 }
2421
2422 #undef gethostname
2423 int mingw_gethostname(char *name, int namelen)
2424 {
2425 ensure_socket_initialization();
2426 return gethostname(name, namelen);
2427 }
2428
2429 #undef gethostbyname
2430 struct hostent *mingw_gethostbyname(const char *host)
2431 {
2432 ensure_socket_initialization();
2433 return gethostbyname(host);
2434 }
2435
2436 #undef getaddrinfo
2437 int mingw_getaddrinfo(const char *node, const char *service,
2438 const struct addrinfo *hints, struct addrinfo **res)
2439 {
2440 ensure_socket_initialization();
2441 return getaddrinfo(node, service, hints, res);
2442 }
2443
2444 int mingw_socket(int domain, int type, int protocol)
2445 {
2446 int sockfd;
2447 SOCKET s;
2448
2449 ensure_socket_initialization();
2450 s = WSASocket(domain, type, protocol, NULL, 0, 0);
2451 if (s == INVALID_SOCKET) {
2452 /*
2453 * WSAGetLastError() values are regular BSD error codes
2454 * biased by WSABASEERR.
2455 * However, strerror() does not know about networking
2456 * specific errors, which are values beginning at 38 or so.
2457 * Therefore, we choose to leave the biased error code
2458 * in errno so that _if_ someone looks up the code somewhere,
2459 * then it is at least the number that are usually listed.
2460 */
2461 errno = WSAGetLastError();
2462 return -1;
2463 }
2464 /* convert into a file descriptor */
2465 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
2466 closesocket(s);
2467 return error("unable to make a socket file descriptor: %s",
2468 strerror(errno));
2469 }
2470 return sockfd;
2471 }
2472
2473 #undef connect
2474 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
2475 {
2476 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2477 return connect(s, sa, sz);
2478 }
2479
2480 #undef bind
2481 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
2482 {
2483 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2484 return bind(s, sa, sz);
2485 }
2486
2487 #undef setsockopt
2488 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
2489 {
2490 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2491 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
2492 }
2493
2494 #undef shutdown
2495 int mingw_shutdown(int sockfd, int how)
2496 {
2497 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2498 return shutdown(s, how);
2499 }
2500
2501 #undef listen
2502 int mingw_listen(int sockfd, int backlog)
2503 {
2504 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2505 return listen(s, backlog);
2506 }
2507
2508 #undef accept
2509 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2510 {
2511 int sockfd2;
2512
2513 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2514 SOCKET s2 = accept(s1, sa, sz);
2515
2516 /* convert into a file descriptor */
2517 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2518 int err = errno;
2519 closesocket(s2);
2520 return error("unable to make a socket file descriptor: %s",
2521 strerror(err));
2522 }
2523 return sockfd2;
2524 }
2525
2526 #undef rename
2527 int mingw_rename(const char *pold, const char *pnew)
2528 {
2529 static int supports_file_rename_info_ex = 1;
2530 DWORD attrs = INVALID_FILE_ATTRIBUTES, gle;
2531 int tries = 0;
2532 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2533 int wpnew_len;
2534
2535 if (xutftowcs_path(wpold, pold) < 0)
2536 return -1;
2537 wpnew_len = xutftowcs_path(wpnew, pnew);
2538 if (wpnew_len < 0)
2539 return -1;
2540
2541 repeat:
2542 if (supports_file_rename_info_ex) {
2543 /*
2544 * Our minimum required Windows version is still set to Windows
2545 * 8.1. We thus have to declare required infrastructure for
2546 * FileRenameInfoEx ourselves until we bump _WIN32_WINNT to
2547 * 0x0A00. Furthermore, we have to handle cases where the
2548 * FileRenameInfoEx call isn't supported yet.
2549 */
2550 #define FILE_RENAME_FLAG_REPLACE_IF_EXISTS 0x00000001
2551 #define FILE_RENAME_FLAG_POSIX_SEMANTICS 0x00000002
2552 FILE_INFO_BY_HANDLE_CLASS FileRenameInfoEx = 22;
2553 struct {
2554 /*
2555 * This is usually an unnamed union, but that is not
2556 * part of ISO C99. We thus inline the field, as we
2557 * really only care for the Flags field anyway.
2558 */
2559 DWORD Flags;
2560 HANDLE RootDirectory;
2561 DWORD FileNameLength;
2562 /*
2563 * The actual structure is defined with a single-character
2564 * flex array so that the structure has to be allocated on
2565 * the heap. As we declare this structure ourselves though
2566 * we can avoid the allocation and define FileName to have
2567 * MAX_PATH bytes.
2568 */
2569 WCHAR FileName[MAX_PATH];
2570 } rename_info = { 0 };
2571 HANDLE old_handle = INVALID_HANDLE_VALUE;
2572 BOOL success;
2573
2574 old_handle = CreateFileW(wpold, DELETE,
2575 FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
2576 NULL, OPEN_EXISTING,
2577 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
2578 NULL);
2579 if (old_handle == INVALID_HANDLE_VALUE) {
2580 errno = err_win_to_posix(GetLastError());
2581 return -1;
2582 }
2583
2584 rename_info.Flags = FILE_RENAME_FLAG_REPLACE_IF_EXISTS |
2585 FILE_RENAME_FLAG_POSIX_SEMANTICS;
2586 rename_info.FileNameLength = wpnew_len * sizeof(WCHAR);
2587 memcpy(rename_info.FileName, wpnew, wpnew_len * sizeof(WCHAR));
2588
2589 success = SetFileInformationByHandle(old_handle, FileRenameInfoEx,
2590 &rename_info, sizeof(rename_info));
2591 gle = GetLastError();
2592 CloseHandle(old_handle);
2593 if (success)
2594 return 0;
2595
2596 /*
2597 * When we see ERROR_INVALID_PARAMETER we can assume that the
2598 * current system doesn't support FileRenameInfoEx. Keep us
2599 * from using it in future calls and retry.
2600 */
2601 if (gle == ERROR_INVALID_PARAMETER ||
2602 gle == ERROR_NOT_SUPPORTED ||
2603 gle == ERROR_INVALID_FUNCTION) {
2604 supports_file_rename_info_ex = 0;
2605 goto repeat;
2606 }
2607
2608 /*
2609 * In theory, we shouldn't get ERROR_ACCESS_DENIED because we
2610 * always open files with FILE_SHARE_DELETE But in practice we
2611 * cannot assume that Git is the only one accessing files, and
2612 * other applications may not set FILE_SHARE_DELETE. So we have
2613 * to retry.
2614 */
2615 } else {
2616 if (MoveFileExW(wpold, wpnew,
2617 MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED))
2618 return 0;
2619 gle = GetLastError();
2620 }
2621
2622 /* revert file attributes on failure */
2623 if (attrs != INVALID_FILE_ATTRIBUTES)
2624 SetFileAttributesW(wpnew, attrs);
2625
2626 if (!is_file_in_use_error(gle)) {
2627 errno = err_win_to_posix(gle);
2628 return -1;
2629 }
2630
2631 if (attrs == INVALID_FILE_ATTRIBUTES &&
2632 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
2633 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
2634 DWORD attrsold = GetFileAttributesW(wpold);
2635 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2636 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2637 errno = EISDIR;
2638 else if (!_wrmdir(wpnew))
2639 goto repeat;
2640 return -1;
2641 }
2642 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
2643 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY))
2644 goto repeat;
2645 }
2646 if (retry_ask_yes_no(&tries, "Rename from '%s' to '%s' failed. "
2647 "Should I try again?", pold, pnew))
2648 goto repeat;
2649
2650 errno = EACCES;
2651 return -1;
2652 }
2653
2654 /*
2655 * Note that this doesn't return the actual pagesize, but
2656 * the allocation granularity. If future Windows specific git code
2657 * needs the real getpagesize function, we need to find another solution.
2658 */
2659 int mingw_getpagesize(void)
2660 {
2661 SYSTEM_INFO si;
2662 GetSystemInfo(&si);
2663 return si.dwAllocationGranularity;
2664 }
2665
2666 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2667 enum EXTENDED_NAME_FORMAT {
2668 NameDisplay = 3,
2669 NameUserPrincipal = 8
2670 };
2671
2672 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2673 {
2674 DECLARE_PROC_ADDR(secur32.dll, BOOL, SEC_ENTRY, GetUserNameExW,
2675 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2676 static wchar_t wbuffer[1024];
2677 DWORD len;
2678
2679 if (!INIT_PROC_ADDR(GetUserNameExW))
2680 return NULL;
2681
2682 len = ARRAY_SIZE(wbuffer);
2683 if (GetUserNameExW(type, wbuffer, &len)) {
2684 char *converted = xmalloc((len *= 3));
2685 if (xwcstoutf(converted, wbuffer, len) >= 0)
2686 return converted;
2687 free(converted);
2688 }
2689
2690 return NULL;
2691 }
2692
2693 char *mingw_query_user_email(void)
2694 {
2695 return get_extended_user_info(NameUserPrincipal);
2696 }
2697
2698 struct passwd *getpwuid(int uid UNUSED)
2699 {
2700 static unsigned initialized;
2701 static char user_name[100];
2702 static struct passwd *p;
2703 wchar_t buf[100];
2704 DWORD len;
2705
2706 if (initialized)
2707 return p;
2708
2709 len = ARRAY_SIZE(buf);
2710 if (!GetUserNameW(buf, &len)) {
2711 initialized = 1;
2712 return NULL;
2713 }
2714
2715 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
2716 initialized = 1;
2717 return NULL;
2718 }
2719
2720 p = xmalloc(sizeof(*p));
2721 p->pw_name = user_name;
2722 p->pw_gecos = get_extended_user_info(NameDisplay);
2723 if (!p->pw_gecos)
2724 /*
2725 * Data returned by getpwuid(3P) is treated as internal and
2726 * must never be written to or freed.
2727 */
2728 p->pw_gecos = (char *) "unknown";
2729 p->pw_dir = NULL;
2730
2731 initialized = 1;
2732 return p;
2733 }
2734
2735 static HANDLE timer_event;
2736 static HANDLE timer_thread;
2737 static int timer_interval;
2738 static int one_shot;
2739 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2740
2741 /* The timer works like this:
2742 * The thread, ticktack(), is a trivial routine that most of the time
2743 * only waits to receive the signal to terminate. The main thread tells
2744 * the thread to terminate by setting the timer_event to the signalled
2745 * state.
2746 * But ticktack() interrupts the wait state after the timer's interval
2747 * length to call the signal handler.
2748 */
2749
2750 static unsigned __stdcall ticktack(void *dummy UNUSED)
2751 {
2752 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2753 mingw_raise(SIGALRM);
2754 if (one_shot)
2755 break;
2756 }
2757 return 0;
2758 }
2759
2760 static int start_timer_thread(void)
2761 {
2762 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2763 if (timer_event) {
2764 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2765 if (!timer_thread ) {
2766 errno = ENOMEM;
2767 return error("cannot start timer thread");
2768 }
2769 } else {
2770 errno = ENOMEM;
2771 return error("cannot allocate resources for timer");
2772 }
2773 return 0;
2774 }
2775
2776 static void stop_timer_thread(void)
2777 {
2778 if (timer_event)
2779 SetEvent(timer_event); /* tell thread to terminate */
2780 if (timer_thread) {
2781 int rc = WaitForSingleObject(timer_thread, 10000);
2782 if (rc == WAIT_TIMEOUT)
2783 error("timer thread did not terminate timely");
2784 else if (rc != WAIT_OBJECT_0)
2785 error("waiting for timer thread failed: %lu",
2786 GetLastError());
2787 CloseHandle(timer_thread);
2788 }
2789 if (timer_event)
2790 CloseHandle(timer_event);
2791 timer_event = NULL;
2792 timer_thread = NULL;
2793 }
2794
2795 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2796 {
2797 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2798 }
2799
2800 int setitimer(int type UNUSED, struct itimerval *in, struct itimerval *out)
2801 {
2802 static const struct timeval zero;
2803 static int atexit_done;
2804
2805 if (out) {
2806 errno = EINVAL;
2807 return error("setitimer param 3 != NULL not implemented");
2808 }
2809 if (!is_timeval_eq(&in->it_interval, &zero) &&
2810 !is_timeval_eq(&in->it_interval, &in->it_value)) {
2811 errno = EINVAL;
2812 return error("setitimer: it_interval must be zero or eq it_value");
2813 }
2814
2815 if (timer_thread)
2816 stop_timer_thread();
2817
2818 if (is_timeval_eq(&in->it_value, &zero) &&
2819 is_timeval_eq(&in->it_interval, &zero))
2820 return 0;
2821
2822 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2823 one_shot = is_timeval_eq(&in->it_interval, &zero);
2824 if (!atexit_done) {
2825 atexit(stop_timer_thread);
2826 atexit_done = 1;
2827 }
2828 return start_timer_thread();
2829 }
2830
2831 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2832 {
2833 if (sig == SIGCHLD)
2834 return -1;
2835 else if (sig != SIGALRM) {
2836 errno = EINVAL;
2837 return error("sigaction only implemented for SIGALRM");
2838 }
2839 if (out) {
2840 errno = EINVAL;
2841 return error("sigaction: param 3 != NULL not implemented");
2842 }
2843
2844 timer_fn = in->sa_handler;
2845 return 0;
2846 }
2847
2848 #undef signal
2849 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2850 {
2851 sig_handler_t old;
2852
2853 switch (sig) {
2854 case SIGALRM:
2855 old = timer_fn;
2856 timer_fn = handler;
2857 break;
2858
2859 case SIGINT:
2860 old = sigint_fn;
2861 sigint_fn = handler;
2862 break;
2863
2864 default:
2865 return signal(sig, handler);
2866 }
2867
2868 return old;
2869 }
2870
2871 #undef raise
2872 int mingw_raise(int sig)
2873 {
2874 switch (sig) {
2875 case SIGALRM:
2876 if (timer_fn == SIG_DFL) {
2877 if (isatty(STDERR_FILENO))
2878 fputs("Alarm clock\n", stderr);
2879 exit(128 + SIGALRM);
2880 } else if (timer_fn != SIG_IGN)
2881 timer_fn(SIGALRM);
2882 return 0;
2883
2884 case SIGINT:
2885 if (sigint_fn == SIG_DFL)
2886 exit(128 + SIGINT);
2887 else if (sigint_fn != SIG_IGN)
2888 sigint_fn(SIGINT);
2889 return 0;
2890
2891 #if defined(_MSC_VER)
2892 case SIGILL:
2893 case SIGFPE:
2894 case SIGSEGV:
2895 case SIGTERM:
2896 case SIGBREAK:
2897 case SIGABRT:
2898 case SIGABRT_COMPAT:
2899 /*
2900 * The <signal.h> header in the MS C Runtime defines 8 signals
2901 * as being supported on the platform. Anything else causes an
2902 * "Invalid signal or error" (which in DEBUG builds causes the
2903 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2904 * already know will fail.
2905 */
2906 return raise(sig);
2907 default:
2908 errno = EINVAL;
2909 return -1;
2910
2911 #else
2912
2913 default:
2914 return raise(sig);
2915
2916 #endif
2917
2918 }
2919 }
2920
2921 int link(const char *oldpath, const char *newpath)
2922 {
2923 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2924 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2925 xutftowcs_path(wnewpath, newpath) < 0)
2926 return -1;
2927
2928 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2929 errno = err_win_to_posix(GetLastError());
2930 return -1;
2931 }
2932 return 0;
2933 }
2934
2935 int symlink(const char *target, const char *link)
2936 {
2937 wchar_t wtarget[MAX_PATH], wlink[MAX_PATH];
2938 int len;
2939
2940 /* fail if symlinks are disabled or API is not supported (WinXP) */
2941 if (!repo_has_symlinks(the_repository)) {
2942 errno = ENOSYS;
2943 return -1;
2944 }
2945
2946 if ((len = xutftowcs_path(wtarget, target)) < 0
2947 || xutftowcs_path(wlink, link) < 0)
2948 return -1;
2949
2950 /* convert target dir separators to backslashes */
2951 while (len--)
2952 if (wtarget[len] == '/')
2953 wtarget[len] = '\\';
2954
2955 /* create file symlink */
2956 if (!CreateSymbolicLinkW(wlink, wtarget, symlink_file_flags)) {
2957 errno = err_win_to_posix(GetLastError());
2958 return -1;
2959 }
2960
2961 /* convert to directory symlink if target exists */
2962 switch (process_phantom_symlink(wtarget, wlink)) {
2963 case PHANTOM_SYMLINK_RETRY: {
2964 /* if target doesn't exist, add to phantom symlinks list */
2965 wchar_t wfullpath[MAX_PATH];
2966 struct phantom_symlink_info *psi;
2967
2968 /* convert to absolute path to be independent of cwd */
2969 len = GetFullPathNameW(wlink, MAX_PATH, wfullpath, NULL);
2970 if (!len || len >= MAX_PATH) {
2971 errno = err_win_to_posix(GetLastError());
2972 return -1;
2973 }
2974
2975 /* over-allocate and fill phantom_symlink_info structure */
2976 psi = xmalloc(sizeof(struct phantom_symlink_info)
2977 + sizeof(wchar_t) * (len + wcslen(wtarget) + 2));
2978 psi->wlink = (wchar_t *)(psi + 1);
2979 wcscpy(psi->wlink, wfullpath);
2980 psi->wtarget = psi->wlink + len + 1;
2981 wcscpy(psi->wtarget, wtarget);
2982
2983 EnterCriticalSection(&phantom_symlinks_cs);
2984 psi->next = phantom_symlinks;
2985 phantom_symlinks = psi;
2986 LeaveCriticalSection(&phantom_symlinks_cs);
2987 break;
2988 }
2989 case PHANTOM_SYMLINK_DIRECTORY:
2990 /* if we created a dir symlink, process other phantom symlinks */
2991 process_phantom_symlinks();
2992 break;
2993 default:
2994 break;
2995 }
2996 return 0;
2997 }
2998
2999 int readlink(const char *path, char *buf, size_t bufsiz)
3000 {
3001 WCHAR wpath[MAX_PATH];
3002 char tmpbuf[MAX_PATH];
3003 int len;
3004 DWORD tag;
3005
3006 if (xutftowcs_path(wpath, path) < 0)
3007 return -1;
3008
3009 if (read_reparse_point(wpath, TRUE, tmpbuf, &len, &tag) < 0)
3010 return -1;
3011
3012 /*
3013 * Adapt to strange readlink() API: Copy up to bufsiz *bytes*, potentially
3014 * cutting off a UTF-8 sequence. Insufficient bufsize is *not* a failure
3015 * condition. There is no conversion function that produces invalid UTF-8,
3016 * so convert to a (hopefully large enough) temporary buffer, then memcpy
3017 * the requested number of bytes (including '\0' for robustness).
3018 */
3019 memcpy(buf, tmpbuf, min(bufsiz, len + 1));
3020 return min(bufsiz, len);
3021 }
3022
3023 pid_t waitpid(pid_t pid, int *status, int options)
3024 {
3025 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
3026 FALSE, pid);
3027 if (!h) {
3028 errno = ECHILD;
3029 return -1;
3030 }
3031
3032 if (pid > 0 && options & WNOHANG) {
3033 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
3034 CloseHandle(h);
3035 return 0;
3036 }
3037 options &= ~WNOHANG;
3038 }
3039
3040 if (options == 0) {
3041 struct pinfo_t **ppinfo;
3042 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
3043 CloseHandle(h);
3044 return 0;
3045 }
3046
3047 if (status)
3048 GetExitCodeProcess(h, (LPDWORD)status);
3049
3050 EnterCriticalSection(&pinfo_cs);
3051
3052 ppinfo = &pinfo;
3053 while (*ppinfo) {
3054 struct pinfo_t *info = *ppinfo;
3055 if (info->pid == pid) {
3056 CloseHandle(info->proc);
3057 *ppinfo = info->next;
3058 free(info);
3059 break;
3060 }
3061 ppinfo = &info->next;
3062 }
3063
3064 LeaveCriticalSection(&pinfo_cs);
3065
3066 CloseHandle(h);
3067 return pid;
3068 }
3069 CloseHandle(h);
3070
3071 errno = EINVAL;
3072 return -1;
3073 }
3074
3075 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
3076 {
3077 int upos = 0, wpos = 0;
3078 const unsigned char *utf = (const unsigned char*) utfs;
3079 if (!utf || !wcs || wcslen < 1) {
3080 errno = EINVAL;
3081 return -1;
3082 }
3083 /* reserve space for \0 */
3084 wcslen--;
3085 if (utflen < 0)
3086 utflen = INT_MAX;
3087
3088 while (upos < utflen) {
3089 int c = utf[upos++] & 0xff;
3090 if (utflen == INT_MAX && c == 0)
3091 break;
3092
3093 if (wpos >= wcslen) {
3094 wcs[wpos] = 0;
3095 errno = ERANGE;
3096 return -1;
3097 }
3098
3099 if (c < 0x80) {
3100 /* ASCII */
3101 wcs[wpos++] = c;
3102 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
3103 (utf[upos] & 0xc0) == 0x80) {
3104 /* 2-byte utf-8 */
3105 c = ((c & 0x1f) << 6);
3106 c |= (utf[upos++] & 0x3f);
3107 wcs[wpos++] = c;
3108 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
3109 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
3110 (utf[upos] & 0xc0) == 0x80 &&
3111 (utf[upos + 1] & 0xc0) == 0x80) {
3112 /* 3-byte utf-8 */
3113 c = ((c & 0x0f) << 12);
3114 c |= ((utf[upos++] & 0x3f) << 6);
3115 c |= (utf[upos++] & 0x3f);
3116 wcs[wpos++] = c;
3117 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
3118 wpos + 1 < wcslen &&
3119 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
3120 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
3121 (utf[upos] & 0xc0) == 0x80 &&
3122 (utf[upos + 1] & 0xc0) == 0x80 &&
3123 (utf[upos + 2] & 0xc0) == 0x80) {
3124 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
3125 c = ((c & 0x07) << 18);
3126 c |= ((utf[upos++] & 0x3f) << 12);
3127 c |= ((utf[upos++] & 0x3f) << 6);
3128 c |= (utf[upos++] & 0x3f);
3129 c -= 0x10000;
3130 wcs[wpos++] = 0xd800 | (c >> 10);
3131 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
3132 } else if (c >= 0xa0) {
3133 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
3134 wcs[wpos++] = c;
3135 } else {
3136 /* invalid utf-8 byte, non-printable unicode: convert to hex */
3137 static const char *hex = "0123456789abcdef";
3138 wcs[wpos++] = hex[c >> 4];
3139 if (wpos < wcslen)
3140 wcs[wpos++] = hex[c & 0x0f];
3141 }
3142 }
3143 wcs[wpos] = 0;
3144 return wpos;
3145 }
3146
3147 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
3148 {
3149 if (!wcs || !utf || utflen < 1) {
3150 errno = EINVAL;
3151 return -1;
3152 }
3153 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
3154 if (utflen)
3155 return utflen - 1;
3156 errno = ERANGE;
3157 return -1;
3158 }
3159
3160 static void setup_windows_environment(void)
3161 {
3162 char *tmp = getenv("TMPDIR");
3163
3164 /* on Windows it is TMP and TEMP */
3165 if (!tmp) {
3166 if (!(tmp = getenv("TMP")))
3167 tmp = getenv("TEMP");
3168 if (tmp) {
3169 setenv("TMPDIR", tmp, 1);
3170 tmp = getenv("TMPDIR");
3171 }
3172 }
3173
3174 if (tmp) {
3175 /*
3176 * Convert all dir separators to forward slashes,
3177 * to help shell commands called from the Git
3178 * executable (by not mistaking the dir separators
3179 * for escape characters).
3180 */
3181 convert_slashes(tmp);
3182 }
3183
3184 /* simulate TERM to enable auto-color (see color.c) */
3185 if (!getenv("TERM"))
3186 setenv("TERM", "cygwin", 1);
3187
3188 /* calculate HOME if not set */
3189 if (!getenv("HOME")) {
3190 /*
3191 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
3192 * location, thus also check if the path exists (i.e. is not
3193 * disconnected)
3194 */
3195 if ((tmp = getenv("HOMEDRIVE"))) {
3196 struct strbuf buf = STRBUF_INIT;
3197 strbuf_addstr(&buf, tmp);
3198 if ((tmp = getenv("HOMEPATH"))) {
3199 strbuf_addstr(&buf, tmp);
3200 if (is_directory(buf.buf))
3201 setenv("HOME", buf.buf, 1);
3202 else
3203 tmp = NULL; /* use $USERPROFILE */
3204 }
3205 strbuf_release(&buf);
3206 }
3207 /* use $USERPROFILE if the home share is not available */
3208 if (!tmp && (tmp = getenv("USERPROFILE")))
3209 setenv("HOME", tmp, 1);
3210 }
3211 }
3212
3213 int mingw_platform_has_symlinks(void)
3214 {
3215 static int has_symlinks = -1;
3216 /*
3217 * Change 'core.symlinks' default to false, unless native symlinks are
3218 * enabled in MSys2 (via 'MSYS=winsymlinks:nativestrict'). Thus we can
3219 * run the test suite (which doesn't obey config files) with or without
3220 * symlink support.
3221 */
3222 if (has_symlinks < 0) {
3223 const char *tmp = getenv("MSYS");
3224 has_symlinks = (tmp && strstr(tmp, "winsymlinks:nativestrict")) ? 1 : 0;
3225 }
3226
3227 return has_symlinks;
3228 }
3229
3230 static void get_current_user_sid(PSID *sid, HANDLE *linked_token)
3231 {
3232 HANDLE token;
3233 DWORD len = 0;
3234 TOKEN_ELEVATION_TYPE elevationType;
3235 DWORD size;
3236
3237 *sid = NULL;
3238 *linked_token = NULL;
3239
3240 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
3241 return;
3242
3243 if (!GetTokenInformation(token, TokenUser, NULL, 0, &len)) {
3244 TOKEN_USER *info = xmalloc((size_t)len);
3245 if (GetTokenInformation(token, TokenUser, info, len, &len)) {
3246 len = GetLengthSid(info->User.Sid);
3247 *sid = xmalloc(len);
3248 if (!CopySid(len, *sid, info->User.Sid)) {
3249 error(_("failed to copy SID (%ld)"),
3250 GetLastError());
3251 FREE_AND_NULL(*sid);
3252 }
3253 }
3254 FREE_AND_NULL(info);
3255 }
3256
3257 if (GetTokenInformation(token, TokenElevationType, &elevationType, sizeof(elevationType), &size) &&
3258 elevationType == TokenElevationTypeLimited) {
3259 /*
3260 * The current process is run by a member of the Administrators
3261 * group, but is not running elevated.
3262 */
3263 if (!GetTokenInformation(token, TokenLinkedToken, linked_token, sizeof(*linked_token), &size))
3264 linked_token = NULL; /* there is no linked token */
3265 }
3266
3267 CloseHandle(token);
3268 }
3269
3270 static BOOL user_sid_to_user_name(PSID sid, LPSTR *str)
3271 {
3272 SID_NAME_USE pe_use;
3273 DWORD len_user = 0, len_domain = 0;
3274 BOOL translate_sid_to_user;
3275
3276 /*
3277 * returns only FALSE, because the string pointers are NULL
3278 */
3279 LookupAccountSidA(NULL, sid, NULL, &len_user, NULL, &len_domain,
3280 &pe_use);
3281 /*
3282 * Alloc needed space of the strings
3283 */
3284 ALLOC_ARRAY((*str), (size_t)len_domain + (size_t)len_user);
3285 translate_sid_to_user = LookupAccountSidA(NULL, sid,
3286 (*str) + len_domain, &len_user, *str, &len_domain, &pe_use);
3287 if (!translate_sid_to_user)
3288 FREE_AND_NULL(*str);
3289 else
3290 (*str)[len_domain] = '/';
3291 return translate_sid_to_user;
3292 }
3293
3294 static int acls_supported(const char *path)
3295 {
3296 size_t offset = offset_1st_component(path);
3297 WCHAR wroot[MAX_PATH];
3298 DWORD file_system_flags;
3299
3300 if (offset &&
3301 xutftowcsn(wroot, path, MAX_PATH, offset) > 0 &&
3302 GetVolumeInformationW(wroot, NULL, 0, NULL, NULL,
3303 &file_system_flags, NULL, 0))
3304 return !!(file_system_flags & FILE_PERSISTENT_ACLS);
3305
3306 return 0;
3307 }
3308
3309 int is_path_owned_by_current_sid(const char *path, struct strbuf *report)
3310 {
3311 WCHAR wpath[MAX_PATH];
3312 PSID sid = NULL;
3313 PSECURITY_DESCRIPTOR descriptor = NULL;
3314 DWORD err;
3315
3316 static wchar_t home[MAX_PATH];
3317
3318 int result = 0;
3319
3320 if (xutftowcs_path(wpath, path) < 0)
3321 return 0;
3322
3323 /*
3324 * On Windows, the home directory is owned by the administrator, but for
3325 * all practical purposes, it belongs to the user. Do pretend that it is
3326 * owned by the user.
3327 */
3328 if (!*home) {
3329 DWORD size = ARRAY_SIZE(home);
3330 DWORD len = GetEnvironmentVariableW(L"HOME", home, size);
3331 if (!len || len > size)
3332 wcscpy(home, L"::N/A::");
3333 }
3334 if (!wcsicmp(wpath, home))
3335 return 1;
3336
3337 /* Get the owner SID */
3338 err = GetNamedSecurityInfoW(wpath, SE_FILE_OBJECT,
3339 OWNER_SECURITY_INFORMATION |
3340 DACL_SECURITY_INFORMATION,
3341 &sid, NULL, NULL, NULL, &descriptor);
3342
3343 if (err != ERROR_SUCCESS)
3344 error(_("failed to get owner for '%s' (%ld)"), path, err);
3345 else if (sid && IsValidSid(sid)) {
3346 /* Now, verify that the SID matches the current user's */
3347 static PSID current_user_sid;
3348 static HANDLE linked_token;
3349 BOOL is_member;
3350
3351 if (!current_user_sid)
3352 get_current_user_sid(&current_user_sid, &linked_token);
3353
3354 if (current_user_sid &&
3355 IsValidSid(current_user_sid) &&
3356 EqualSid(sid, current_user_sid))
3357 result = 1;
3358 else if (IsWellKnownSid(sid, WinBuiltinAdministratorsSid) &&
3359 ((CheckTokenMembership(NULL, sid, &is_member) &&
3360 is_member) ||
3361 (linked_token &&
3362 CheckTokenMembership(linked_token, sid, &is_member) &&
3363 is_member)))
3364 /*
3365 * If owned by the Administrators group, and the
3366 * current user is an administrator, we consider that
3367 * okay, too.
3368 */
3369 result = 1;
3370 else if (report &&
3371 IsWellKnownSid(sid, WinWorldSid) &&
3372 !acls_supported(path)) {
3373 /*
3374 * On FAT32 volumes, ownership is not actually recorded.
3375 */
3376 strbuf_addf(report, "'%s' is on a file system that does "
3377 "not record ownership\n", path);
3378 } else if (report) {
3379 PCSTR str1, str2, str3, str4;
3380 LPSTR to_free1 = NULL, to_free3 = NULL,
3381 to_local_free2 = NULL, to_local_free4 = NULL;
3382
3383 if (user_sid_to_user_name(sid, &to_free1))
3384 str1 = to_free1;
3385 else
3386 str1 = "(inconvertible)";
3387 if (ConvertSidToStringSidA(sid, &to_local_free2))
3388 str2 = to_local_free2;
3389 else
3390 str2 = "(inconvertible)";
3391
3392 if (!current_user_sid) {
3393 str3 = "(none)";
3394 str4 = "(none)";
3395 }
3396 else if (!IsValidSid(current_user_sid)) {
3397 str3 = "(invalid)";
3398 str4 = "(invalid)";
3399 } else {
3400 if (user_sid_to_user_name(current_user_sid,
3401 &to_free3))
3402 str3 = to_free3;
3403 else
3404 str3 = "(inconvertible)";
3405 if (ConvertSidToStringSidA(current_user_sid,
3406 &to_local_free4))
3407 str4 = to_local_free4;
3408 else
3409 str4 = "(inconvertible)";
3410 }
3411 strbuf_addf(report,
3412 "'%s' is owned by:\n"
3413 "\t%s (%s)\nbut the current user is:\n"
3414 "\t%s (%s)\n",
3415 path, str1, str2, str3, str4);
3416 free(to_free1);
3417 LocalFree(to_local_free2);
3418 free(to_free3);
3419 LocalFree(to_local_free4);
3420 }
3421 }
3422
3423 /*
3424 * We can release the security descriptor struct only now because `sid`
3425 * actually points into this struct.
3426 */
3427 if (descriptor)
3428 LocalFree(descriptor);
3429
3430 return result;
3431 }
3432
3433 int is_valid_win32_path(const char *path, int allow_literal_nul)
3434 {
3435 const char *p = path;
3436 int preceding_space_or_period = 0, i = 0, periods = 0;
3437
3438 if (!repo_protect_ntfs(the_repository))
3439 return 1;
3440
3441 skip_dos_drive_prefix((char **)&path);
3442 goto segment_start;
3443
3444 for (;;) {
3445 char c = *(path++);
3446 switch (c) {
3447 case '\0':
3448 case '/': case '\\':
3449 /* cannot end in ` ` or `.`, except for `.` and `..` */
3450 if (preceding_space_or_period &&
3451 (i != periods || periods > 2))
3452 return 0;
3453 if (!c)
3454 return 1;
3455
3456 i = periods = preceding_space_or_period = 0;
3457
3458 segment_start:
3459 switch (*path) {
3460 case 'a': case 'A': /* AUX */
3461 if (((c = path[++i]) != 'u' && c != 'U') ||
3462 ((c = path[++i]) != 'x' && c != 'X')) {
3463 not_a_reserved_name:
3464 path += i;
3465 continue;
3466 }
3467 break;
3468 case 'c': case 'C':
3469 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
3470 if ((c = path[++i]) != 'o' && c != 'O')
3471 goto not_a_reserved_name;
3472 c = path[++i];
3473 if (c == 'm' || c == 'M') { /* COM1 ... COM9 */
3474 c = path[++i];
3475 if (c < '1' || c > '9')
3476 goto not_a_reserved_name;
3477 } else if (c == 'n' || c == 'N') { /* CON */
3478 c = path[i + 1];
3479 if ((c == 'i' || c == 'I') &&
3480 ((c = path[i + 2]) == 'n' ||
3481 c == 'N') &&
3482 path[i + 3] == '$')
3483 i += 3; /* CONIN$ */
3484 else if ((c == 'o' || c == 'O') &&
3485 ((c = path[i + 2]) == 'u' ||
3486 c == 'U') &&
3487 ((c = path[i + 3]) == 't' ||
3488 c == 'T') &&
3489 path[i + 4] == '$')
3490 i += 4; /* CONOUT$ */
3491 } else
3492 goto not_a_reserved_name;
3493 break;
3494 case 'l': case 'L': /* LPT<N> */
3495 if (((c = path[++i]) != 'p' && c != 'P') ||
3496 ((c = path[++i]) != 't' && c != 'T') ||
3497 !isdigit(path[++i]))
3498 goto not_a_reserved_name;
3499 break;
3500 case 'n': case 'N': /* NUL */
3501 if (((c = path[++i]) != 'u' && c != 'U') ||
3502 ((c = path[++i]) != 'l' && c != 'L') ||
3503 (allow_literal_nul &&
3504 !path[i + 1] && p == path))
3505 goto not_a_reserved_name;
3506 break;
3507 case 'p': case 'P': /* PRN */
3508 if (((c = path[++i]) != 'r' && c != 'R') ||
3509 ((c = path[++i]) != 'n' && c != 'N'))
3510 goto not_a_reserved_name;
3511 break;
3512 default:
3513 continue;
3514 }
3515
3516 /*
3517 * So far, this looks like a reserved name. Let's see
3518 * whether it actually is one: trailing spaces, a file
3519 * extension, or an NTFS Alternate Data Stream do not
3520 * matter, the name is still reserved if any of those
3521 * follow immediately after the actual name.
3522 */
3523 i++;
3524 if (path[i] == ' ') {
3525 preceding_space_or_period = 1;
3526 while (path[++i] == ' ')
3527 ; /* skip all spaces */
3528 }
3529
3530 c = path[i];
3531 if (c && c != '.' && c != ':' && !is_xplatform_dir_sep(c))
3532 goto not_a_reserved_name;
3533
3534 /* contains reserved name */
3535 return 0;
3536 case '.':
3537 periods++;
3538 /* fallthru */
3539 case ' ':
3540 preceding_space_or_period = 1;
3541 i++;
3542 continue;
3543 case ':': /* DOS drive prefix was already skipped */
3544 case '<': case '>': case '"': case '|': case '?': case '*':
3545 /* illegal character */
3546 return 0;
3547 default:
3548 if (c > '\0' && c < '\x20')
3549 /* illegal character */
3550 return 0;
3551 }
3552 preceding_space_or_period = 0;
3553 i++;
3554 }
3555 }
3556
3557 #if !defined(_MSC_VER)
3558 /*
3559 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
3560 * mingw startup code, see init.c in mingw runtime).
3561 */
3562 int _CRT_glob = 0;
3563 #endif
3564
3565 static NORETURN void die_startup(void)
3566 {
3567 fputs("fatal: not enough memory for initialization", stderr);
3568 exit(128);
3569 }
3570
3571 static void *malloc_startup(size_t size)
3572 {
3573 void *result = malloc(size);
3574 if (!result)
3575 die_startup();
3576 return result;
3577 }
3578
3579 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
3580 {
3581 len = xwcstoutf(buffer, wcs, len) + 1;
3582 return memcpy(malloc_startup(len), buffer, len);
3583 }
3584
3585 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
3586 DWORD desired_access, DWORD flags)
3587 {
3588 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
3589 wchar_t buf[MAX_PATH];
3590 DWORD max = ARRAY_SIZE(buf);
3591 HANDLE handle;
3592 DWORD ret = GetEnvironmentVariableW(key, buf, max);
3593
3594 if (!ret || ret >= max)
3595 return;
3596
3597 /* make sure this does not leak into child processes */
3598 SetEnvironmentVariableW(key, NULL);
3599 if (!wcscmp(buf, L"off")) {
3600 close(fd);
3601 handle = GetStdHandle(std_id);
3602 if (handle != INVALID_HANDLE_VALUE)
3603 CloseHandle(handle);
3604 return;
3605 }
3606 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
3607 handle = GetStdHandle(STD_OUTPUT_HANDLE);
3608 if (handle == INVALID_HANDLE_VALUE) {
3609 close(fd);
3610 handle = GetStdHandle(std_id);
3611 if (handle != INVALID_HANDLE_VALUE)
3612 CloseHandle(handle);
3613 } else {
3614 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
3615 SetStdHandle(std_id, handle);
3616 dup2(new_fd, fd);
3617 /* do *not* close the new_fd: that would close stdout */
3618 }
3619 return;
3620 }
3621 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
3622 flags, NULL);
3623 if (handle != INVALID_HANDLE_VALUE) {
3624 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
3625 SetStdHandle(std_id, handle);
3626 dup2(new_fd, fd);
3627 close(new_fd);
3628 }
3629 }
3630
3631 static void maybe_redirect_std_handles(void)
3632 {
3633 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
3634 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
3635 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
3636 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
3637 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
3638 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
3639 }
3640
3641 static void adjust_symlink_flags(void)
3642 {
3643 /*
3644 * Starting with Windows 10 Build 14972, symbolic links can be created
3645 * using CreateSymbolicLink() without elevation by passing the flag
3646 * SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE (0x02) as last
3647 * parameter, provided the Developer Mode has been enabled. Some
3648 * earlier Windows versions complain about this flag with an
3649 * ERROR_INVALID_PARAMETER, hence we have to test the build number
3650 * specifically.
3651 */
3652 if (GetVersion() >= 14972 << 16) {
3653 symlink_file_flags |= 2;
3654 symlink_directory_flags |= 2;
3655 }
3656 }
3657
3658 static BOOL WINAPI handle_ctrl_c(DWORD ctrl_type)
3659 {
3660 if (ctrl_type != CTRL_C_EVENT)
3661 return FALSE; /* we did not handle this */
3662 mingw_raise(SIGINT);
3663 return TRUE; /* we did handle this */
3664 }
3665
3666 #ifdef _MSC_VER
3667 #ifdef _DEBUG
3668 #include <crtdbg.h>
3669 #endif
3670 #endif
3671
3672 /*
3673 * We implement wmain() and compile with -municode, which would
3674 * normally ignore main(), but we call the latter from the former
3675 * so that we can handle non-ASCII command-line parameters
3676 * appropriately.
3677 *
3678 * To be more compatible with the core git code, we convert
3679 * argv into UTF8 and pass them directly to main().
3680 */
3681 int wmain(int argc, const wchar_t **wargv)
3682 {
3683 int i, exit_status;
3684 size_t maxlen;
3685 char *buffer, **save;
3686 const char **argv;
3687
3688 trace2_initialize_clock();
3689
3690 #ifdef _MSC_VER
3691 #ifdef _DEBUG
3692 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
3693 #endif
3694
3695 #ifdef USE_MSVC_CRTDBG
3696 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
3697 #endif
3698 #endif
3699
3700 SetConsoleCtrlHandler(handle_ctrl_c, TRUE);
3701
3702 maybe_redirect_std_handles();
3703 adjust_symlink_flags();
3704
3705 /* determine size of argv and environ conversion buffer */
3706 maxlen = wcslen(wargv[0]);
3707 for (i = 1; i < argc; i++)
3708 maxlen = max(maxlen, wcslen(wargv[i]));
3709
3710 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
3711 maxlen = 3 * maxlen + 1;
3712 buffer = malloc_startup(maxlen);
3713
3714 /*
3715 * Create a UTF-8 version of w_argv. Also create a "save" copy
3716 * to remember all the string pointers because parse_options()
3717 * will remove claimed items from the argv that we pass down.
3718 */
3719 ALLOC_ARRAY(argv, argc + 1);
3720 ALLOC_ARRAY(save, argc + 1);
3721 for (i = 0; i < argc; i++)
3722 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
3723 argv[i] = save[i] = NULL;
3724 free(buffer);
3725
3726 /* fix Windows specific environment settings */
3727 setup_windows_environment();
3728
3729 unset_environment_variables = xstrdup("PERL5LIB");
3730
3731 /* initialize critical section for waitpid pinfo_t list */
3732 InitializeCriticalSection(&pinfo_cs);
3733 InitializeCriticalSection(&phantom_symlinks_cs);
3734
3735 /* set up default file mode and file modes for stdin/out/err */
3736 _fmode = _O_BINARY;
3737 _setmode(_fileno(stdin), _O_BINARY);
3738 _setmode(_fileno(stdout), _O_BINARY);
3739 _setmode(_fileno(stderr), _O_BINARY);
3740
3741 /* initialize Unicode console */
3742 winansi_init();
3743
3744 /* invoke the real main() using our utf8 version of argv. */
3745 exit_status = main(argc, argv);
3746
3747 for (i = 0; i < argc; i++)
3748 free(save[i]);
3749 free(save);
3750 free(argv);
3751
3752 return exit_status;
3753 }
3754
3755 int uname(struct utsname *buf)
3756 {
3757 unsigned v = (unsigned)GetVersion();
3758 memset(buf, 0, sizeof(*buf));
3759 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
3760 xsnprintf(buf->release, sizeof(buf->release),
3761 "%u.%u", v & 0xff, (v >> 8) & 0xff);
3762 /* assuming NT variants only.. */
3763 xsnprintf(buf->version, sizeof(buf->version),
3764 "%u", (v >> 16) & 0x7fff);
3765 return 0;
3766 }
3767
3768 #ifndef NO_UNIX_SOCKETS
3769 int mingw_have_unix_sockets(void)
3770 {
3771 SC_HANDLE scm, srvc;
3772 SERVICE_STATUS_PROCESS status;
3773 DWORD bytes;
3774 int ret = 0;
3775 scm = OpenSCManagerA(NULL, NULL, SC_MANAGER_CONNECT);
3776 if (scm) {
3777 srvc = OpenServiceA(scm, "afunix", SERVICE_QUERY_STATUS);
3778 if (srvc) {
3779 if(QueryServiceStatusEx(srvc, SC_STATUS_PROCESS_INFO, (LPBYTE)&status, sizeof(SERVICE_STATUS_PROCESS), &bytes))
3780 ret = status.dwCurrentState == SERVICE_RUNNING;
3781 CloseServiceHandle(srvc);
3782 }
3783 CloseServiceHandle(scm);
3784 }
3785 return ret;
3786 }
3787 #endif