2 * Copyright (C) the libgit2 contributors. All rights reserved.
4 * This file is part of libgit2, distributed under the GNU GPL v2 with
5 * a Linking Exception. For full terms see the included COPYING file.
8 #include "../fileops.h"
12 #include "repository.h"
21 #ifndef FILE_NAME_NORMALIZED
22 # define FILE_NAME_NORMALIZED 0
25 #ifndef IO_REPARSE_TAG_SYMLINK
26 #define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
29 /* Allowable mode bits on Win32. Using mode bits that are not supported on
30 * Win32 (eg S_IRWXU) is generally ignored, but Wine warns loudly about it
31 * so we simply remove them.
33 #define WIN32_MODE_MASK (_S_IREAD | _S_IWRITE)
35 /* GetFinalPathNameByHandleW signature */
36 typedef DWORD(WINAPI
*PFGetFinalPathNameByHandleW
)(HANDLE
, LPWSTR
, DWORD
, DWORD
);
38 unsigned long git_win32__createfile_sharemode
=
39 FILE_SHARE_READ
| FILE_SHARE_WRITE
;
40 int git_win32__retries
= 10;
42 GIT_INLINE(void) set_errno(void)
44 switch (GetLastError()) {
45 case ERROR_FILE_NOT_FOUND
:
46 case ERROR_PATH_NOT_FOUND
:
47 case ERROR_INVALID_DRIVE
:
48 case ERROR_NO_MORE_FILES
:
49 case ERROR_BAD_NETPATH
:
50 case ERROR_BAD_NET_NAME
:
51 case ERROR_BAD_PATHNAME
:
52 case ERROR_FILENAME_EXCED_RANGE
:
55 case ERROR_BAD_ENVIRONMENT
:
58 case ERROR_BAD_FORMAT
:
59 case ERROR_INVALID_STARTING_CODESEG
:
60 case ERROR_INVALID_STACKSEG
:
61 case ERROR_INVALID_MODULETYPE
:
62 case ERROR_INVALID_EXE_SIGNATURE
:
63 case ERROR_EXE_MARKED_INVALID
:
64 case ERROR_BAD_EXE_FORMAT
:
65 case ERROR_ITERATED_DATA_EXCEEDS_64k
:
66 case ERROR_INVALID_MINALLOCSIZE
:
67 case ERROR_DYNLINK_FROM_INVALID_RING
:
68 case ERROR_IOPL_NOT_ENABLED
:
69 case ERROR_INVALID_SEGDPL
:
70 case ERROR_AUTODATASEG_EXCEEDS_64k
:
71 case ERROR_RING2SEG_MUST_BE_MOVABLE
:
72 case ERROR_RELOC_CHAIN_XEEDS_SEGLIM
:
73 case ERROR_INFLOOP_IN_RELOC_CHAIN
:
76 case ERROR_INVALID_HANDLE
:
77 case ERROR_INVALID_TARGET_HANDLE
:
78 case ERROR_DIRECT_ACCESS_HANDLE
:
81 case ERROR_WAIT_NO_CHILDREN
:
82 case ERROR_CHILD_NOT_COMPLETE
:
85 case ERROR_NO_PROC_SLOTS
:
86 case ERROR_MAX_THRDS_REACHED
:
87 case ERROR_NESTING_NOT_ALLOWED
:
90 case ERROR_ARENA_TRASHED
:
91 case ERROR_NOT_ENOUGH_MEMORY
:
92 case ERROR_INVALID_BLOCK
:
93 case ERROR_NOT_ENOUGH_QUOTA
:
96 case ERROR_ACCESS_DENIED
:
97 case ERROR_CURRENT_DIRECTORY
:
98 case ERROR_WRITE_PROTECT
:
100 case ERROR_NOT_READY
:
101 case ERROR_BAD_COMMAND
:
103 case ERROR_BAD_LENGTH
:
105 case ERROR_NOT_DOS_DISK
:
106 case ERROR_SECTOR_NOT_FOUND
:
107 case ERROR_OUT_OF_PAPER
:
108 case ERROR_WRITE_FAULT
:
109 case ERROR_READ_FAULT
:
110 case ERROR_GEN_FAILURE
:
111 case ERROR_SHARING_VIOLATION
:
112 case ERROR_LOCK_VIOLATION
:
113 case ERROR_WRONG_DISK
:
114 case ERROR_SHARING_BUFFER_EXCEEDED
:
115 case ERROR_NETWORK_ACCESS_DENIED
:
116 case ERROR_CANNOT_MAKE
:
118 case ERROR_DRIVE_LOCKED
:
119 case ERROR_SEEK_ON_DEVICE
:
120 case ERROR_NOT_LOCKED
:
121 case ERROR_LOCK_FAILED
:
124 case ERROR_FILE_EXISTS
:
125 case ERROR_ALREADY_EXISTS
:
128 case ERROR_NOT_SAME_DEVICE
:
131 case ERROR_INVALID_FUNCTION
:
132 case ERROR_INVALID_ACCESS
:
133 case ERROR_INVALID_DATA
:
134 case ERROR_INVALID_PARAMETER
:
135 case ERROR_NEGATIVE_SEEK
:
138 case ERROR_TOO_MANY_OPEN_FILES
:
141 case ERROR_DISK_FULL
:
144 case ERROR_BROKEN_PIPE
:
147 case ERROR_DIR_NOT_EMPTY
:
155 GIT_INLINE(bool) last_error_retryable(void)
157 int os_error
= GetLastError();
159 return (os_error
== ERROR_SHARING_VIOLATION
||
160 os_error
== ERROR_ACCESS_DENIED
);
163 #define do_with_retries(fn, remediation) \
165 int __tries, __ret; \
166 for (__tries = 0; __tries < git_win32__retries; __tries++) { \
167 if (__tries && (__ret = (remediation)) != 0) \
169 if ((__ret = (fn)) != GIT_RETRY) \
176 static int ensure_writable(wchar_t *path)
180 if ((attrs
= GetFileAttributesW(path
)) == INVALID_FILE_ATTRIBUTES
)
183 if ((attrs
& FILE_ATTRIBUTE_READONLY
) == 0)
186 if (!SetFileAttributesW(path
, (attrs
& ~FILE_ATTRIBUTE_READONLY
)))
197 * Truncate or extend file.
199 * We now take a "git_off_t" rather than "long" because
200 * files may be longer than 2Gb.
202 int p_ftruncate(int fd
, git_off_t size
)
209 #if !defined(__MINGW32__) || defined(MINGW_HAS_SECURE_API)
210 return ((_chsize_s(fd
, size
) == 0) ? 0 : -1);
212 /* TODO MINGW32 Find a replacement for _chsize() that handles big files. */
213 if (size
> INT32_MAX
) {
217 return _chsize(fd
, (long)size
);
221 int p_mkdir(const char *path
, mode_t mode
)
227 if (git_win32_path_from_utf8(buf
, path
) < 0)
233 int p_link(const char *old
, const char *new)
241 GIT_INLINE(int) unlink_once(const wchar_t *path
)
243 if (DeleteFileW(path
))
246 if (last_error_retryable())
253 int p_unlink(const char *path
)
255 git_win32_path wpath
;
257 if (git_win32_path_from_utf8(wpath
, path
) < 0)
260 do_with_retries(unlink_once(wpath
), ensure_writable(wpath
));
265 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
269 if (fh
== INVALID_HANDLE_VALUE
) {
274 if (!FlushFileBuffers(fh
)) {
275 DWORD code
= GetLastError();
277 if (code
== ERROR_INVALID_HANDLE
)
288 #define WIN32_IS_WSEP(CH) ((CH) == L'/' || (CH) == L'\\')
295 WIN32_FILE_ATTRIBUTE_DATA fdata
;
297 if (GetFileAttributesExW(path
, GetFileExInfoStandard
, &fdata
)) {
301 return git_win32__file_attribute_to_stat(buf
, &fdata
, path
);
304 switch (GetLastError()) {
305 case ERROR_ACCESS_DENIED
:
313 /* To match POSIX behavior, set ENOTDIR when any of the folders in the
314 * file path is a regular file, otherwise set ENOENT.
316 if (errno
== ENOENT
&& posix_enotdir
) {
317 size_t path_len
= wcslen(path
);
319 /* scan up path until we find an existing item */
323 /* remove last directory component */
324 for (path_len
--; path_len
> 0 && !WIN32_IS_WSEP(path
[path_len
]); path_len
--);
329 path
[path_len
] = L
'\0';
330 attrs
= GetFileAttributesW(path
);
332 if (attrs
!= INVALID_FILE_ATTRIBUTES
) {
333 if (!(attrs
& FILE_ATTRIBUTE_DIRECTORY
))
343 static int do_lstat(const char *path
, struct stat
*buf
, bool posixly_correct
)
345 git_win32_path path_w
;
348 if ((len
= git_win32_path_from_utf8(path_w
, path
)) < 0)
351 git_win32__path_trim_end(path_w
, len
);
353 return lstat_w(path_w
, buf
, posixly_correct
);
356 int p_lstat(const char *filename
, struct stat
*buf
)
358 return do_lstat(filename
, buf
, false);
361 int p_lstat_posixly(const char *filename
, struct stat
*buf
)
363 return do_lstat(filename
, buf
, true);
366 int p_readlink(const char *path
, char *buf
, size_t bufsiz
)
368 git_win32_path path_w
, target_w
;
369 git_win32_utf8_path target
;
372 /* readlink(2) does not NULL-terminate the string written
373 * to the target buffer. Furthermore, the target buffer need
374 * not be large enough to hold the entire result. A truncated
375 * result should be written in this case. Since this truncation
376 * could occur in the middle of the encoding of a code point,
377 * we need to buffer the result on the stack. */
379 if (git_win32_path_from_utf8(path_w
, path
) < 0 ||
380 git_win32_path_readlink_w(target_w
, path_w
) < 0 ||
381 (len
= git_win32_path_to_utf8(target
, target_w
)) < 0)
384 bufsiz
= min((size_t)len
, bufsiz
);
385 memcpy(buf
, target
, bufsiz
);
390 int p_symlink(const char *old
, const char *new)
392 /* Real symlinks on NTFS require admin privileges. Until this changes,
393 * libgit2 just creates a text file with the link target in the contents.
395 return git_futils_fake_symlink(old
, new);
401 SECURITY_ATTRIBUTES security
;
402 DWORD creation_disposition
;
407 GIT_INLINE(void) open_opts_from_posix(struct open_opts
*opts
, int flags
, mode_t mode
)
409 memset(opts
, 0, sizeof(struct open_opts
));
411 switch (flags
& (O_WRONLY
| O_RDWR
)) {
413 opts
->access
= GENERIC_WRITE
;
416 opts
->access
= GENERIC_READ
| GENERIC_WRITE
;
419 opts
->access
= GENERIC_READ
;
423 opts
->sharing
= (DWORD
)git_win32__createfile_sharemode
;
425 switch (flags
& (O_CREAT
| O_TRUNC
| O_EXCL
)) {
426 case O_CREAT
| O_EXCL
:
427 case O_CREAT
| O_TRUNC
| O_EXCL
:
428 opts
->creation_disposition
= CREATE_NEW
;
430 case O_CREAT
| O_TRUNC
:
431 opts
->creation_disposition
= CREATE_ALWAYS
;
434 opts
->creation_disposition
= TRUNCATE_EXISTING
;
437 opts
->creation_disposition
= OPEN_ALWAYS
;
440 opts
->creation_disposition
= OPEN_EXISTING
;
444 opts
->attributes
= ((flags
& O_CREAT
) && !(mode
& S_IWRITE
)) ?
445 FILE_ATTRIBUTE_READONLY
: FILE_ATTRIBUTE_NORMAL
;
446 opts
->osf_flags
= flags
& (O_RDONLY
| O_APPEND
);
448 opts
->security
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
449 opts
->security
.lpSecurityDescriptor
= NULL
;
450 opts
->security
.bInheritHandle
= 0;
453 GIT_INLINE(int) open_once(
455 struct open_opts
*opts
)
459 HANDLE handle
= CreateFileW(path
, opts
->access
, opts
->sharing
,
460 &opts
->security
, opts
->creation_disposition
, opts
->attributes
, 0);
462 if (handle
== INVALID_HANDLE_VALUE
) {
463 if (last_error_retryable())
470 if ((fd
= _open_osfhandle((intptr_t)handle
, opts
->osf_flags
)) < 0)
476 int p_open(const char *path
, int flags
, ...)
478 git_win32_path wpath
;
480 struct open_opts opts
= {0};
482 if (git_win32_path_from_utf8(wpath
, path
) < 0)
485 if (flags
& O_CREAT
) {
488 va_start(arg_list
, flags
);
489 mode
= (mode_t
)va_arg(arg_list
, int);
493 open_opts_from_posix(&opts
, flags
, mode
);
496 open_once(wpath
, &opts
),
500 int p_creat(const char *path
, mode_t mode
)
502 return p_open(path
, O_WRONLY
| O_CREAT
| O_TRUNC
, mode
);
505 int p_utimes(const char *path
, const struct p_timeval times
[2])
507 git_win32_path wpath
;
509 DWORD attrs_orig
, attrs_new
= 0;
510 struct open_opts opts
= { 0 };
512 if (git_win32_path_from_utf8(wpath
, path
) < 0)
515 attrs_orig
= GetFileAttributesW(wpath
);
517 if (attrs_orig
& FILE_ATTRIBUTE_READONLY
) {
518 attrs_new
= attrs_orig
& ~FILE_ATTRIBUTE_READONLY
;
520 if (!SetFileAttributesW(wpath
, attrs_new
)) {
521 giterr_set(GITERR_OS
, "failed to set attributes");
526 open_opts_from_posix(&opts
, O_RDWR
, 0);
528 if ((fd
= open_once(wpath
, &opts
)) < 0) {
533 error
= p_futimes(fd
, times
);
537 if (attrs_orig
!= attrs_new
) {
538 DWORD os_error
= GetLastError();
539 SetFileAttributesW(wpath
, attrs_orig
);
540 SetLastError(os_error
);
546 int p_futimes(int fd
, const struct p_timeval times
[2])
549 FILETIME atime
= { 0 }, mtime
= { 0 };
555 SystemTimeToFileTime(&st
, &atime
);
556 SystemTimeToFileTime(&st
, &mtime
);
559 git_win32__timeval_to_filetime(&atime
, times
[0]);
560 git_win32__timeval_to_filetime(&mtime
, times
[1]);
563 if ((handle
= (HANDLE
)_get_osfhandle(fd
)) == INVALID_HANDLE_VALUE
)
566 if (SetFileTime(handle
, NULL
, &atime
, &mtime
) == 0)
572 int p_getcwd(char *buffer_out
, size_t size
)
575 wchar_t *cwd
= _wgetcwd(buf
, GIT_WIN_PATH_UTF16
);
580 /* Convert the working directory back to UTF-8 */
581 if (git__utf16_to_8(buffer_out
, size
, cwd
) < 0) {
582 DWORD code
= GetLastError();
584 if (code
== ERROR_INSUFFICIENT_BUFFER
)
596 * Returns the address of the GetFinalPathNameByHandleW function.
597 * This function is available on Windows Vista and higher.
599 static PFGetFinalPathNameByHandleW
get_fpnbyhandle(void)
601 static PFGetFinalPathNameByHandleW pFunc
= NULL
;
602 PFGetFinalPathNameByHandleW toReturn
= pFunc
;
605 HMODULE hModule
= GetModuleHandleW(L
"kernel32");
608 toReturn
= (PFGetFinalPathNameByHandleW
)GetProcAddress(hModule
, "GetFinalPathNameByHandleW");
618 static int getfinalpath_w(
622 PFGetFinalPathNameByHandleW pgfp
= get_fpnbyhandle();
629 /* Use FILE_FLAG_BACKUP_SEMANTICS so we can open a directory. Do not
630 * specify FILE_FLAG_OPEN_REPARSE_POINT; we want to open a handle to the
631 * target of the link. */
632 hFile
= CreateFileW(path
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_DELETE
,
633 NULL
, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
635 if (INVALID_HANDLE_VALUE
== hFile
)
638 /* Call GetFinalPathNameByHandle */
639 dwChars
= pgfp(hFile
, dest
, GIT_WIN_PATH_UTF16
, FILE_NAME_NORMALIZED
);
642 if (!dwChars
|| dwChars
>= GIT_WIN_PATH_UTF16
)
645 /* The path may be delivered to us with a prefix; canonicalize */
646 return (int)git_win32__canonicalize_path(dest
, dwChars
);
649 static int follow_and_lstat_link(git_win32_path path
, struct stat
* buf
)
651 git_win32_path target_w
;
653 if (getfinalpath_w(target_w
, path
) < 0)
656 return lstat_w(target_w
, buf
, false);
659 int p_fstat(int fd
, struct stat
*buf
)
661 BY_HANDLE_FILE_INFORMATION fhInfo
;
663 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
665 if (fh
== INVALID_HANDLE_VALUE
||
666 !GetFileInformationByHandle(fh
, &fhInfo
)) {
671 git_win32__file_information_to_stat(buf
, &fhInfo
);
675 int p_stat(const char* path
, struct stat
* buf
)
677 git_win32_path path_w
;
680 if ((len
= git_win32_path_from_utf8(path_w
, path
)) < 0 ||
681 lstat_w(path_w
, buf
, false) < 0)
684 /* The item is a symbolic link or mount point. No need to iterate
685 * to follow multiple links; use GetFinalPathNameFromHandle. */
686 if (S_ISLNK(buf
->st_mode
))
687 return follow_and_lstat_link(path_w
, buf
);
692 int p_chdir(const char* path
)
696 if (git_win32_path_from_utf8(buf
, path
) < 0)
702 int p_chmod(const char* path
, mode_t mode
)
706 if (git_win32_path_from_utf8(buf
, path
) < 0)
709 return _wchmod(buf
, mode
);
712 int p_rmdir(const char* path
)
717 if (git_win32_path_from_utf8(buf
, path
) < 0)
720 error
= _wrmdir(buf
);
723 switch (GetLastError()) {
724 /* _wrmdir() is documented to return EACCES if "A program has an open
725 * handle to the directory." This sounds like what everybody else calls
726 * EBUSY. Let's convert appropriate error codes.
728 case ERROR_SHARING_VIOLATION
:
732 /* This error can be returned when trying to rmdir an extant file. */
733 case ERROR_DIRECTORY
:
742 char *p_realpath(const char *orig_path
, char *buffer
)
744 git_win32_path orig_path_w
, buffer_w
;
746 if (git_win32_path_from_utf8(orig_path_w
, orig_path
) < 0)
749 /* Note that if the path provided is a relative path, then the current directory
750 * is used to resolve the path -- which is a concurrency issue because the current
751 * directory is a process-wide variable. */
752 if (!GetFullPathNameW(orig_path_w
, GIT_WIN_PATH_UTF16
, buffer_w
, NULL
)) {
753 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
)
754 errno
= ENAMETOOLONG
;
761 /* The path must exist. */
762 if (GetFileAttributesW(buffer_w
) == INVALID_FILE_ATTRIBUTES
) {
767 if (!buffer
&& !(buffer
= git__malloc(GIT_WIN_PATH_UTF8
))) {
772 /* Convert the path to UTF-8. If the caller provided a buffer, then it
773 * is assumed to be GIT_WIN_PATH_UTF8 characters in size. If it isn't,
774 * then we may overflow. */
775 if (git_win32_path_to_utf8(buffer
, buffer_w
) < 0)
778 git_path_mkposix(buffer
);
783 int p_vsnprintf(char *buffer
, size_t count
, const char *format
, va_list argptr
)
785 #if defined(_MSC_VER)
789 return _vscprintf(format
, argptr
);
792 len
= _vsnprintf_s(buffer
, count
, _TRUNCATE
, format
, argptr
);
794 len
= _vsnprintf(buffer
, count
, format
, argptr
);
798 return _vscprintf(format
, argptr
);
802 return vsnprintf(buffer
, count
, format
, argptr
);
806 int p_snprintf(char *buffer
, size_t count
, const char *format
, ...)
811 va_start(va
, format
);
812 r
= p_vsnprintf(buffer
, count
, format
, va
);
819 int p_mkstemp(char *tmp_path
)
821 #if defined(_MSC_VER) && _MSC_VER >= 1500
822 if (_mktemp_s(tmp_path
, strlen(tmp_path
) + 1) != 0)
825 if (_mktemp(tmp_path
) == NULL
)
829 return p_open(tmp_path
, O_RDWR
| O_CREAT
| O_EXCL
, 0744); //-V536
832 int p_access(const char* path
, mode_t mode
)
836 if (git_win32_path_from_utf8(buf
, path
) < 0)
839 return _waccess(buf
, mode
& WIN32_MODE_MASK
);
842 GIT_INLINE(int) rename_once(const wchar_t *from
, const wchar_t *to
)
844 if (MoveFileExW(from
, to
, MOVEFILE_REPLACE_EXISTING
| MOVEFILE_COPY_ALLOWED
))
847 if (last_error_retryable())
854 int p_rename(const char *from
, const char *to
)
856 git_win32_path wfrom
, wto
;
858 if (git_win32_path_from_utf8(wfrom
, from
) < 0 ||
859 git_win32_path_from_utf8(wto
, to
) < 0)
862 do_with_retries(rename_once(wfrom
, wto
), ensure_writable(wto
));
865 int p_recv(GIT_SOCKET socket
, void *buffer
, size_t length
, int flags
)
867 if ((size_t)((int)length
) != length
)
868 return -1; /* giterr_set will be done by caller */
870 return recv(socket
, buffer
, (int)length
, flags
);
873 int p_send(GIT_SOCKET socket
, const void *buffer
, size_t length
, int flags
)
875 if ((size_t)((int)length
) != length
)
876 return -1; /* giterr_set will be done by caller */
878 return send(socket
, buffer
, (int)length
, flags
);
882 * Borrowed from http://old.nabble.com/Porting-localtime_r-and-gmtime_r-td15282276.html
883 * On Win32, `gmtime_r` doesn't exist but `gmtime` is threadsafe, so we can use that
886 p_localtime_r (const time_t *timer
, struct tm
*result
)
888 struct tm
*local_result
;
889 local_result
= localtime (timer
);
891 if (local_result
== NULL
|| result
== NULL
)
894 memcpy (result
, local_result
, sizeof (struct tm
));
898 p_gmtime_r (const time_t *timer
, struct tm
*result
)
900 struct tm
*local_result
;
901 local_result
= gmtime (timer
);
903 if (local_result
== NULL
|| result
== NULL
)
906 memcpy (result
, local_result
, sizeof (struct tm
));
910 int p_inet_pton(int af
, const char *src
, void *dst
)
912 struct sockaddr_storage sin
;
914 int sin_len
= sizeof(struct sockaddr_storage
), addr_len
;
918 addr
= &((struct sockaddr_in
*)&sin
)->sin_addr
;
919 addr_len
= sizeof(struct in_addr
);
920 } else if (af
== AF_INET6
) {
921 addr
= &((struct sockaddr_in6
*)&sin
)->sin6_addr
;
922 addr_len
= sizeof(struct in6_addr
);
924 errno
= EAFNOSUPPORT
;
928 if ((error
= WSAStringToAddressA((LPSTR
)src
, af
, NULL
, (LPSOCKADDR
)&sin
, &sin_len
)) == 0) {
929 memcpy(dst
, addr
, addr_len
);
933 switch(WSAGetLastError()) {
939 case WSA_NOT_ENOUGH_MEMORY
: