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"
19 #ifndef FILE_NAME_NORMALIZED
20 # define FILE_NAME_NORMALIZED 0
23 #ifndef IO_REPARSE_TAG_SYMLINK
24 #define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
27 /* Options which we always provide to _wopen.
29 * _O_BINARY - Raw access; no translation of CR or LF characters
30 * _O_NOINHERIT - Do not mark the created handle as inheritable by child processes.
31 * The Windows default is 'not inheritable', but the CRT's default (following
32 * POSIX convention) is 'inheritable'. We have no desire for our handles to be
33 * inheritable on Windows, so specify the flag to get default behavior back. */
34 #define STANDARD_OPEN_FLAGS (_O_BINARY | _O_NOINHERIT)
36 /* Allowable mode bits on Win32. Using mode bits that are not supported on
37 * Win32 (eg S_IRWXU) is generally ignored, but Wine warns loudly about it
38 * so we simply remove them.
40 #define WIN32_MODE_MASK (_S_IREAD | _S_IWRITE)
42 /* GetFinalPathNameByHandleW signature */
43 typedef DWORD(WINAPI
*PFGetFinalPathNameByHandleW
)(HANDLE
, LPWSTR
, DWORD
, DWORD
);
46 * Truncate or extend file.
48 * We now take a "git_off_t" rather than "long" because
49 * files may be longer than 2Gb.
51 int p_ftruncate(int fd
, git_off_t size
)
58 #if !defined(__MINGW32__) || defined(MINGW_HAS_SECURE_API)
59 return ((_chsize_s(fd
, size
) == 0) ? 0 : -1);
61 /* TODO MINGW32 Find a replacement for _chsize() that handles big files. */
62 if (size
> INT32_MAX
) {
66 return _chsize(fd
, (long)size
);
70 int p_mkdir(const char *path
, mode_t mode
)
76 if (git_win32_path_from_utf8(buf
, path
) < 0)
82 int p_link(const char *old
, const char *new)
90 int p_unlink(const char *path
)
95 if (git_win32_path_from_utf8(buf
, path
) < 0)
98 error
= _wunlink(buf
);
100 /* If the file could not be deleted because it was
101 * read-only, clear the bit and try again */
102 if (error
== -1 && errno
== EACCES
) {
104 error
= _wunlink(buf
);
112 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
114 if (fh
== INVALID_HANDLE_VALUE
) {
119 if (!FlushFileBuffers(fh
)) {
120 DWORD code
= GetLastError();
122 if (code
== ERROR_INVALID_HANDLE
)
133 GIT_INLINE(time_t) filetime_to_time_t(const FILETIME
*ft
)
135 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
136 winTime
-= 116444736000000000LL; /* Windows to Unix Epoch conversion */
137 winTime
/= 10000000; /* Nano to seconds resolution */
138 return (time_t)winTime
;
141 static bool path_is_volume(wchar_t *target
, size_t target_len
)
143 return (target_len
&& wcsncmp(target
, L
"\\??\\Volume{", 11) == 0);
146 /* On success, returns the length, in characters, of the path stored in dest.
147 * On failure, returns a negative value. */
148 static int readlink_w(
150 const git_win32_path path
)
152 BYTE buf
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
153 GIT_REPARSE_DATA_BUFFER
*reparse_buf
= (GIT_REPARSE_DATA_BUFFER
*)buf
;
154 HANDLE handle
= NULL
;
161 handle
= CreateFileW(path
, GENERIC_READ
,
162 FILE_SHARE_READ
| FILE_SHARE_DELETE
, NULL
, OPEN_EXISTING
,
163 FILE_FLAG_OPEN_REPARSE_POINT
| FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
165 if (handle
== INVALID_HANDLE_VALUE
) {
170 if (!DeviceIoControl(handle
, FSCTL_GET_REPARSE_POINT
, NULL
, 0,
171 reparse_buf
, sizeof(buf
), &ioctl_ret
, NULL
)) {
176 switch (reparse_buf
->ReparseTag
) {
177 case IO_REPARSE_TAG_SYMLINK
:
178 target
= reparse_buf
->SymbolicLinkReparseBuffer
.PathBuffer
+
179 (reparse_buf
->SymbolicLinkReparseBuffer
.SubstituteNameOffset
/ sizeof(WCHAR
));
180 target_len
= reparse_buf
->SymbolicLinkReparseBuffer
.SubstituteNameLength
/ sizeof(WCHAR
);
182 case IO_REPARSE_TAG_MOUNT_POINT
:
183 target
= reparse_buf
->MountPointReparseBuffer
.PathBuffer
+
184 (reparse_buf
->MountPointReparseBuffer
.SubstituteNameOffset
/ sizeof(WCHAR
));
185 target_len
= reparse_buf
->MountPointReparseBuffer
.SubstituteNameLength
/ sizeof(WCHAR
);
192 if (path_is_volume(target
, target_len
)) {
193 /* This path is a reparse point that represents another volume mounted
194 * at this location, it is not a symbolic link our input was canonical.
198 } else if (target_len
) {
199 /* The path may need to have a prefix removed. */
200 target_len
= git_win32__canonicalize_path(target
, target_len
);
202 /* Need one additional character in the target buffer
203 * for the terminating NULL. */
204 if (GIT_WIN_PATH_UTF16
> target_len
) {
205 wcscpy(dest
, target
);
206 error
= (int)target_len
;
215 #define WIN32_IS_WSEP(CH) ((CH) == L'/' || (CH) == L'\\')
222 WIN32_FILE_ATTRIBUTE_DATA fdata
;
224 if (GetFileAttributesExW(path
, GetFileExInfoStandard
, &fdata
)) {
230 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
235 if (!(fdata
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
242 buf
->st_mode
= (mode_t
)fMode
;
243 buf
->st_size
= ((git_off_t
)fdata
.nFileSizeHigh
<< 32) + fdata
.nFileSizeLow
;
244 buf
->st_dev
= buf
->st_rdev
= (_getdrive() - 1);
245 buf
->st_atime
= filetime_to_time_t(&(fdata
.ftLastAccessTime
));
246 buf
->st_mtime
= filetime_to_time_t(&(fdata
.ftLastWriteTime
));
247 buf
->st_ctime
= filetime_to_time_t(&(fdata
.ftCreationTime
));
249 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
250 git_win32_path target
;
252 if (readlink_w(target
, path
) >= 0) {
253 buf
->st_mode
= (buf
->st_mode
& ~S_IFMT
) | S_IFLNK
;
255 /* st_size gets the UTF-8 length of the target name, in bytes,
256 * not counting the NULL terminator */
257 if ((buf
->st_size
= git__utf16_to_8(NULL
, 0, target
)) < 0)
267 /* To match POSIX behavior, set ENOTDIR when any of the folders in the
268 * file path is a regular file, otherwise set ENOENT.
271 size_t path_len
= wcslen(path
);
273 /* scan up path until we find an existing item */
277 /* remove last directory component */
278 for (path_len
--; path_len
> 0 && !WIN32_IS_WSEP(path
[path_len
]); path_len
--);
283 path
[path_len
] = L
'\0';
284 attrs
= GetFileAttributesW(path
);
286 if (attrs
!= INVALID_FILE_ATTRIBUTES
) {
287 if (!(attrs
& FILE_ATTRIBUTE_DIRECTORY
))
297 static int do_lstat(const char *path
, struct stat
*buf
, bool posixly_correct
)
299 git_win32_path path_w
;
302 if ((len
= git_win32_path_from_utf8(path_w
, path
)) < 0)
305 git_win32__path_trim_end(path_w
, len
);
307 return lstat_w(path_w
, buf
, posixly_correct
);
310 int p_lstat(const char *filename
, struct stat
*buf
)
312 return do_lstat(filename
, buf
, false);
315 int p_lstat_posixly(const char *filename
, struct stat
*buf
)
317 return do_lstat(filename
, buf
, true);
320 int p_readlink(const char *path
, char *buf
, size_t bufsiz
)
322 git_win32_path path_w
, target_w
;
323 git_win32_utf8_path target
;
326 /* readlink(2) does not NULL-terminate the string written
327 * to the target buffer. Furthermore, the target buffer need
328 * not be large enough to hold the entire result. A truncated
329 * result should be written in this case. Since this truncation
330 * could occur in the middle of the encoding of a code point,
331 * we need to buffer the result on the stack. */
333 if (git_win32_path_from_utf8(path_w
, path
) < 0 ||
334 readlink_w(target_w
, path_w
) < 0 ||
335 (len
= git_win32_path_to_utf8(target
, target_w
)) < 0)
338 bufsiz
= min((size_t)len
, bufsiz
);
339 memcpy(buf
, target
, bufsiz
);
344 int p_symlink(const char *old
, const char *new)
346 /* Real symlinks on NTFS require admin privileges. Until this changes,
347 * libgit2 just creates a text file with the link target in the contents.
349 return git_futils_fake_symlink(old
, new);
352 int p_open(const char *path
, int flags
, ...)
357 if (git_win32_path_from_utf8(buf
, path
) < 0)
360 if (flags
& O_CREAT
) {
363 va_start(arg_list
, flags
);
364 mode
= (mode_t
)va_arg(arg_list
, int);
368 return _wopen(buf
, flags
| STANDARD_OPEN_FLAGS
, mode
& WIN32_MODE_MASK
);
371 int p_creat(const char *path
, mode_t mode
)
375 if (git_win32_path_from_utf8(buf
, path
) < 0)
379 _O_WRONLY
| _O_CREAT
| _O_TRUNC
| STANDARD_OPEN_FLAGS
,
380 mode
& WIN32_MODE_MASK
);
383 int p_getcwd(char *buffer_out
, size_t size
)
386 wchar_t *cwd
= _wgetcwd(buf
, GIT_WIN_PATH_UTF16
);
391 /* Convert the working directory back to UTF-8 */
392 if (git__utf16_to_8(buffer_out
, size
, cwd
) < 0) {
393 DWORD code
= GetLastError();
395 if (code
== ERROR_INSUFFICIENT_BUFFER
)
407 * Returns the address of the GetFinalPathNameByHandleW function.
408 * This function is available on Windows Vista and higher.
410 static PFGetFinalPathNameByHandleW
get_fpnbyhandle(void)
412 static PFGetFinalPathNameByHandleW pFunc
= NULL
;
413 PFGetFinalPathNameByHandleW toReturn
= pFunc
;
416 HMODULE hModule
= GetModuleHandleW(L
"kernel32");
419 toReturn
= (PFGetFinalPathNameByHandleW
)GetProcAddress(hModule
, "GetFinalPathNameByHandleW");
429 static int getfinalpath_w(
433 PFGetFinalPathNameByHandleW pgfp
= get_fpnbyhandle();
440 /* Use FILE_FLAG_BACKUP_SEMANTICS so we can open a directory. Do not
441 * specify FILE_FLAG_OPEN_REPARSE_POINT; we want to open a handle to the
442 * target of the link. */
443 hFile
= CreateFileW(path
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_DELETE
,
444 NULL
, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
446 if (INVALID_HANDLE_VALUE
== hFile
)
449 /* Call GetFinalPathNameByHandle */
450 dwChars
= pgfp(hFile
, dest
, GIT_WIN_PATH_UTF16
, FILE_NAME_NORMALIZED
);
453 if (!dwChars
|| dwChars
>= GIT_WIN_PATH_UTF16
)
456 /* The path may be delivered to us with a prefix; canonicalize */
457 return (int)git_win32__canonicalize_path(dest
, dwChars
);
460 static int follow_and_lstat_link(git_win32_path path
, struct stat
* buf
)
462 git_win32_path target_w
;
464 if (getfinalpath_w(target_w
, path
) < 0)
467 return lstat_w(target_w
, buf
, false);
470 int p_stat(const char* path
, struct stat
* buf
)
472 git_win32_path path_w
;
475 if ((len
= git_win32_path_from_utf8(path_w
, path
)) < 0 ||
476 lstat_w(path_w
, buf
, false) < 0)
479 /* The item is a symbolic link or mount point. No need to iterate
480 * to follow multiple links; use GetFinalPathNameFromHandle. */
481 if (S_ISLNK(buf
->st_mode
))
482 return follow_and_lstat_link(path_w
, buf
);
487 int p_chdir(const char* path
)
491 if (git_win32_path_from_utf8(buf
, path
) < 0)
497 int p_chmod(const char* path
, mode_t mode
)
501 if (git_win32_path_from_utf8(buf
, path
) < 0)
504 return _wchmod(buf
, mode
);
507 int p_rmdir(const char* path
)
512 if (git_win32_path_from_utf8(buf
, path
) < 0)
515 error
= _wrmdir(buf
);
518 switch (GetLastError()) {
519 /* _wrmdir() is documented to return EACCES if "A program has an open
520 * handle to the directory." This sounds like what everybody else calls
521 * EBUSY. Let's convert appropriate error codes.
523 case ERROR_SHARING_VIOLATION
:
527 /* This error can be returned when trying to rmdir an extant file. */
528 case ERROR_DIRECTORY
:
537 char *p_realpath(const char *orig_path
, char *buffer
)
539 git_win32_path orig_path_w
, buffer_w
;
541 if (git_win32_path_from_utf8(orig_path_w
, orig_path
) < 0)
544 /* Note that if the path provided is a relative path, then the current directory
545 * is used to resolve the path -- which is a concurrency issue because the current
546 * directory is a process-wide variable. */
547 if (!GetFullPathNameW(orig_path_w
, GIT_WIN_PATH_UTF16
, buffer_w
, NULL
)) {
548 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
)
549 errno
= ENAMETOOLONG
;
556 /* The path must exist. */
557 if (GetFileAttributesW(buffer_w
) == INVALID_FILE_ATTRIBUTES
) {
562 if (!buffer
&& !(buffer
= git__malloc(GIT_WIN_PATH_UTF8
))) {
567 /* Convert the path to UTF-8. If the caller provided a buffer, then it
568 * is assumed to be GIT_WIN_PATH_UTF8 characters in size. If it isn't,
569 * then we may overflow. */
570 if (git_win32_path_to_utf8(buffer
, buffer_w
) < 0)
573 git_path_mkposix(buffer
);
578 int p_vsnprintf(char *buffer
, size_t count
, const char *format
, va_list argptr
)
580 #if defined(_MSC_VER)
584 return _vscprintf(format
, argptr
);
587 len
= _vsnprintf_s(buffer
, count
, _TRUNCATE
, format
, argptr
);
589 len
= _vsnprintf(buffer
, count
, format
, argptr
);
593 return _vscprintf(format
, argptr
);
597 return vsnprintf(buffer
, count
, format
, argptr
);
601 int p_snprintf(char *buffer
, size_t count
, const char *format
, ...)
606 va_start(va
, format
);
607 r
= p_vsnprintf(buffer
, count
, format
, va
);
614 int p_mkstemp(char *tmp_path
)
616 #if defined(_MSC_VER) && _MSC_VER >= 1500
617 if (_mktemp_s(tmp_path
, strlen(tmp_path
) + 1) != 0)
620 if (_mktemp(tmp_path
) == NULL
)
624 return p_open(tmp_path
, O_RDWR
| O_CREAT
| O_EXCL
, 0744); //-V536
627 int p_access(const char* path
, mode_t mode
)
631 if (git_win32_path_from_utf8(buf
, path
) < 0)
634 return _waccess(buf
, mode
& WIN32_MODE_MASK
);
637 static int ensure_writable(wchar_t *fpath
)
641 attrs
= GetFileAttributesW(fpath
);
642 if (attrs
== INVALID_FILE_ATTRIBUTES
) {
643 if (GetLastError() == ERROR_FILE_NOT_FOUND
)
646 giterr_set(GITERR_OS
, "failed to get attributes");
650 if (!(attrs
& FILE_ATTRIBUTE_READONLY
))
653 attrs
&= ~FILE_ATTRIBUTE_READONLY
;
654 if (!SetFileAttributesW(fpath
, attrs
)) {
655 giterr_set(GITERR_OS
, "failed to set attributes");
662 int p_rename(const char *from
, const char *to
)
664 git_win32_path wfrom
;
667 int rename_succeeded
;
670 if (git_win32_path_from_utf8(wfrom
, from
) < 0 ||
671 git_win32_path_from_utf8(wto
, to
) < 0)
674 /* wait up to 50ms if file is locked by another thread or process */
676 rename_succeeded
= 0;
677 while (rename_tries
< 10) {
678 if (ensure_writable(wto
) == 0 &&
679 MoveFileExW(wfrom
, wto
, MOVEFILE_REPLACE_EXISTING
| MOVEFILE_COPY_ALLOWED
) != 0) {
680 rename_succeeded
= 1;
684 error
= GetLastError();
685 if (error
== ERROR_SHARING_VIOLATION
|| error
== ERROR_ACCESS_DENIED
) {
692 return rename_succeeded
? 0 : -1;
695 int p_recv(GIT_SOCKET socket
, void *buffer
, size_t length
, int flags
)
697 if ((size_t)((int)length
) != length
)
698 return -1; /* giterr_set will be done by caller */
700 return recv(socket
, buffer
, (int)length
, flags
);
703 int p_send(GIT_SOCKET socket
, const void *buffer
, size_t length
, int flags
)
705 if ((size_t)((int)length
) != length
)
706 return -1; /* giterr_set will be done by caller */
708 return send(socket
, buffer
, (int)length
, flags
);
712 * Borrowed from http://old.nabble.com/Porting-localtime_r-and-gmtime_r-td15282276.html
713 * On Win32, `gmtime_r` doesn't exist but `gmtime` is threadsafe, so we can use that
716 p_localtime_r (const time_t *timer
, struct tm
*result
)
718 struct tm
*local_result
;
719 local_result
= localtime (timer
);
721 if (local_result
== NULL
|| result
== NULL
)
724 memcpy (result
, local_result
, sizeof (struct tm
));
728 p_gmtime_r (const time_t *timer
, struct tm
*result
)
730 struct tm
*local_result
;
731 local_result
= gmtime (timer
);
733 if (local_result
== NULL
|| result
== NULL
)
736 memcpy (result
, local_result
, sizeof (struct tm
));
740 int p_inet_pton(int af
, const char *src
, void *dst
)
742 struct sockaddr_storage sin
;
744 int sin_len
= sizeof(struct sockaddr_storage
), addr_len
;
748 addr
= &((struct sockaddr_in
*)&sin
)->sin_addr
;
749 addr_len
= sizeof(struct in_addr
);
750 } else if (af
== AF_INET6
) {
751 addr
= &((struct sockaddr_in6
*)&sin
)->sin6_addr
;
752 addr_len
= sizeof(struct in6_addr
);
754 errno
= EAFNOSUPPORT
;
758 if ((error
= WSAStringToAddressA((LPSTR
)src
, af
, NULL
, (LPSOCKADDR
)&sin
, &sin_len
)) == 0) {
759 memcpy(dst
, addr
, addr_len
);
763 switch(WSAGetLastError()) {
769 case WSA_NOT_ENOUGH_MEMORY
: