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 /* GetFinalPathNameByHandleW signature */
37 typedef DWORD(WINAPI
*PFGetFinalPathNameByHandleW
)(HANDLE
, LPWSTR
, DWORD
, DWORD
);
39 int p_ftruncate(int fd
, long size
)
41 #if defined(_MSC_VER) && _MSC_VER >= 1500
42 return _chsize_s(fd
, size
);
44 return _chsize(fd
, size
);
48 int p_mkdir(const char *path
, mode_t mode
)
54 if (git_win32_path_from_utf8(buf
, path
) < 0)
60 int p_link(const char *old
, const char *new)
68 int p_unlink(const char *path
)
73 if (git_win32_path_from_utf8(buf
, path
) < 0)
76 error
= _wunlink(buf
);
78 /* If the file could not be deleted because it was
79 * read-only, clear the bit and try again */
80 if (error
== -1 && errno
== EACCES
) {
82 error
= _wunlink(buf
);
90 HANDLE fh
= (HANDLE
)_get_osfhandle(fd
);
92 if (fh
== INVALID_HANDLE_VALUE
) {
97 if (!FlushFileBuffers(fh
)) {
98 DWORD code
= GetLastError();
100 if (code
== ERROR_INVALID_HANDLE
)
111 GIT_INLINE(time_t) filetime_to_time_t(const FILETIME
*ft
)
113 long long winTime
= ((long long)ft
->dwHighDateTime
<< 32) + ft
->dwLowDateTime
;
114 winTime
-= 116444736000000000LL; /* Windows to Unix Epoch conversion */
115 winTime
/= 10000000; /* Nano to seconds resolution */
116 return (time_t)winTime
;
119 static bool path_is_volume(wchar_t *target
, size_t target_len
)
121 return (target_len
&& wcsncmp(target
, L
"\\??\\Volume{", 11) == 0);
124 /* On success, returns the length, in characters, of the path stored in dest.
125 * On failure, returns a negative value. */
126 static int readlink_w(
128 const git_win32_path path
)
130 BYTE buf
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
131 GIT_REPARSE_DATA_BUFFER
*reparse_buf
= (GIT_REPARSE_DATA_BUFFER
*)buf
;
132 HANDLE handle
= NULL
;
139 handle
= CreateFileW(path
, GENERIC_READ
,
140 FILE_SHARE_READ
| FILE_SHARE_DELETE
, NULL
, OPEN_EXISTING
,
141 FILE_FLAG_OPEN_REPARSE_POINT
| FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
143 if (handle
== INVALID_HANDLE_VALUE
) {
148 if (!DeviceIoControl(handle
, FSCTL_GET_REPARSE_POINT
, NULL
, 0,
149 reparse_buf
, sizeof(buf
), &ioctl_ret
, NULL
)) {
154 switch (reparse_buf
->ReparseTag
) {
155 case IO_REPARSE_TAG_SYMLINK
:
156 target
= reparse_buf
->SymbolicLinkReparseBuffer
.PathBuffer
+
157 (reparse_buf
->SymbolicLinkReparseBuffer
.SubstituteNameOffset
/ sizeof(WCHAR
));
158 target_len
= reparse_buf
->SymbolicLinkReparseBuffer
.SubstituteNameLength
/ sizeof(WCHAR
);
160 case IO_REPARSE_TAG_MOUNT_POINT
:
161 target
= reparse_buf
->MountPointReparseBuffer
.PathBuffer
+
162 (reparse_buf
->MountPointReparseBuffer
.SubstituteNameOffset
/ sizeof(WCHAR
));
163 target_len
= reparse_buf
->MountPointReparseBuffer
.SubstituteNameLength
/ sizeof(WCHAR
);
170 if (path_is_volume(target
, target_len
)) {
171 /* This path is a reparse point that represents another volume mounted
172 * at this location, it is not a symbolic link our input was canonical.
176 } else if (target_len
) {
177 /* The path may need to have a prefix removed. */
178 target_len
= git_win32__canonicalize_path(target
, target_len
);
180 /* Need one additional character in the target buffer
181 * for the terminating NULL. */
182 if (GIT_WIN_PATH_UTF16
> target_len
) {
183 wcscpy(dest
, target
);
184 error
= (int)target_len
;
193 #define WIN32_IS_WSEP(CH) ((CH) == L'/' || (CH) == L'\\')
200 WIN32_FILE_ATTRIBUTE_DATA fdata
;
202 if (GetFileAttributesExW(path
, GetFileExInfoStandard
, &fdata
)) {
208 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
213 if (!(fdata
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
))
220 buf
->st_mode
= (mode_t
)fMode
;
221 buf
->st_size
= ((git_off_t
)fdata
.nFileSizeHigh
<< 32) + fdata
.nFileSizeLow
;
222 buf
->st_dev
= buf
->st_rdev
= (_getdrive() - 1);
223 buf
->st_atime
= filetime_to_time_t(&(fdata
.ftLastAccessTime
));
224 buf
->st_mtime
= filetime_to_time_t(&(fdata
.ftLastWriteTime
));
225 buf
->st_ctime
= filetime_to_time_t(&(fdata
.ftCreationTime
));
227 if (fdata
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
228 git_win32_path target
;
230 if (readlink_w(target
, path
) >= 0) {
231 buf
->st_mode
= (buf
->st_mode
& ~S_IFMT
) | S_IFLNK
;
233 /* st_size gets the UTF-8 length of the target name, in bytes,
234 * not counting the NULL terminator */
235 if ((buf
->st_size
= git__utf16_to_8(NULL
, 0, target
)) < 0)
245 /* To match POSIX behavior, set ENOTDIR when any of the folders in the
246 * file path is a regular file, otherwise set ENOENT.
249 size_t path_len
= wcslen(path
);
251 /* scan up path until we find an existing item */
255 /* remove last directory component */
256 for (path_len
--; path_len
> 0 && !WIN32_IS_WSEP(path
[path_len
]); path_len
--);
261 path
[path_len
] = L
'\0';
262 attrs
= GetFileAttributesW(path
);
264 if (attrs
!= INVALID_FILE_ATTRIBUTES
) {
265 if (!(attrs
& FILE_ATTRIBUTE_DIRECTORY
))
275 static int do_lstat(const char *path
, struct stat
*buf
, bool posixly_correct
)
277 git_win32_path path_w
;
280 if ((len
= git_win32_path_from_utf8(path_w
, path
)) < 0)
283 git_win32__path_trim_end(path_w
, len
);
285 return lstat_w(path_w
, buf
, posixly_correct
);
288 int p_lstat(const char *filename
, struct stat
*buf
)
290 return do_lstat(filename
, buf
, false);
293 int p_lstat_posixly(const char *filename
, struct stat
*buf
)
295 return do_lstat(filename
, buf
, true);
298 int p_readlink(const char *path
, char *buf
, size_t bufsiz
)
300 git_win32_path path_w
, target_w
;
301 git_win32_utf8_path target
;
304 /* readlink(2) does not NULL-terminate the string written
305 * to the target buffer. Furthermore, the target buffer need
306 * not be large enough to hold the entire result. A truncated
307 * result should be written in this case. Since this truncation
308 * could occur in the middle of the encoding of a code point,
309 * we need to buffer the result on the stack. */
311 if (git_win32_path_from_utf8(path_w
, path
) < 0 ||
312 readlink_w(target_w
, path_w
) < 0 ||
313 (len
= git_win32_path_to_utf8(target
, target_w
)) < 0)
316 bufsiz
= min((size_t)len
, bufsiz
);
317 memcpy(buf
, target
, bufsiz
);
322 int p_symlink(const char *old
, const char *new)
324 /* Real symlinks on NTFS require admin privileges. Until this changes,
325 * libgit2 just creates a text file with the link target in the contents.
327 return git_futils_fake_symlink(old
, new);
330 int p_open(const char *path
, int flags
, ...)
335 if (git_win32_path_from_utf8(buf
, path
) < 0)
338 if (flags
& O_CREAT
) {
341 va_start(arg_list
, flags
);
342 mode
= (mode_t
)va_arg(arg_list
, int);
346 return _wopen(buf
, flags
| STANDARD_OPEN_FLAGS
, mode
);
349 int p_creat(const char *path
, mode_t mode
)
353 if (git_win32_path_from_utf8(buf
, path
) < 0)
356 return _wopen(buf
, _O_WRONLY
| _O_CREAT
| _O_TRUNC
| STANDARD_OPEN_FLAGS
, mode
);
359 int p_getcwd(char *buffer_out
, size_t size
)
362 wchar_t *cwd
= _wgetcwd(buf
, GIT_WIN_PATH_UTF16
);
367 /* Convert the working directory back to UTF-8 */
368 if (git__utf16_to_8(buffer_out
, size
, cwd
) < 0) {
369 DWORD code
= GetLastError();
371 if (code
== ERROR_INSUFFICIENT_BUFFER
)
383 * Returns the address of the GetFinalPathNameByHandleW function.
384 * This function is available on Windows Vista and higher.
386 static PFGetFinalPathNameByHandleW
get_fpnbyhandle(void)
388 static PFGetFinalPathNameByHandleW pFunc
= NULL
;
389 PFGetFinalPathNameByHandleW toReturn
= pFunc
;
392 HMODULE hModule
= GetModuleHandleW(L
"kernel32");
395 toReturn
= (PFGetFinalPathNameByHandleW
)GetProcAddress(hModule
, "GetFinalPathNameByHandleW");
405 static int getfinalpath_w(
409 PFGetFinalPathNameByHandleW pgfp
= get_fpnbyhandle();
416 /* Use FILE_FLAG_BACKUP_SEMANTICS so we can open a directory. Do not
417 * specify FILE_FLAG_OPEN_REPARSE_POINT; we want to open a handle to the
418 * target of the link. */
419 hFile
= CreateFileW(path
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_DELETE
,
420 NULL
, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
422 if (INVALID_HANDLE_VALUE
== hFile
)
425 /* Call GetFinalPathNameByHandle */
426 dwChars
= pgfp(hFile
, dest
, GIT_WIN_PATH_UTF16
, FILE_NAME_NORMALIZED
);
429 if (!dwChars
|| dwChars
>= GIT_WIN_PATH_UTF16
)
432 /* The path may be delivered to us with a prefix; canonicalize */
433 return (int)git_win32__canonicalize_path(dest
, dwChars
);
436 static int follow_and_lstat_link(git_win32_path path
, struct stat
* buf
)
438 git_win32_path target_w
;
440 if (getfinalpath_w(target_w
, path
) < 0)
443 return lstat_w(target_w
, buf
, false);
446 int p_stat(const char* path
, struct stat
* buf
)
448 git_win32_path path_w
;
451 if ((len
= git_win32_path_from_utf8(path_w
, path
)) < 0 ||
452 lstat_w(path_w
, buf
, false) < 0)
455 /* The item is a symbolic link or mount point. No need to iterate
456 * to follow multiple links; use GetFinalPathNameFromHandle. */
457 if (S_ISLNK(buf
->st_mode
))
458 return follow_and_lstat_link(path_w
, buf
);
463 int p_chdir(const char* path
)
467 if (git_win32_path_from_utf8(buf
, path
) < 0)
473 int p_chmod(const char* path
, mode_t mode
)
477 if (git_win32_path_from_utf8(buf
, path
) < 0)
480 return _wchmod(buf
, mode
);
483 int p_rmdir(const char* path
)
488 if (git_win32_path_from_utf8(buf
, path
) < 0)
491 error
= _wrmdir(buf
);
494 switch (GetLastError()) {
495 /* _wrmdir() is documented to return EACCES if "A program has an open
496 * handle to the directory." This sounds like what everybody else calls
497 * EBUSY. Let's convert appropriate error codes.
499 case ERROR_SHARING_VIOLATION
:
503 /* This error can be returned when trying to rmdir an extant file. */
504 case ERROR_DIRECTORY
:
513 char *p_realpath(const char *orig_path
, char *buffer
)
515 git_win32_path orig_path_w
, buffer_w
;
517 if (git_win32_path_from_utf8(orig_path_w
, orig_path
) < 0)
520 /* Note that if the path provided is a relative path, then the current directory
521 * is used to resolve the path -- which is a concurrency issue because the current
522 * directory is a process-wide variable. */
523 if (!GetFullPathNameW(orig_path_w
, GIT_WIN_PATH_UTF16
, buffer_w
, NULL
)) {
524 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
)
525 errno
= ENAMETOOLONG
;
532 /* The path must exist. */
533 if (GetFileAttributesW(buffer_w
) == INVALID_FILE_ATTRIBUTES
) {
538 if (!buffer
&& !(buffer
= git__malloc(GIT_WIN_PATH_UTF8
))) {
543 /* Convert the path to UTF-8. If the caller provided a buffer, then it
544 * is assumed to be GIT_WIN_PATH_UTF8 characters in size. If it isn't,
545 * then we may overflow. */
546 if (git_win32_path_to_utf8(buffer
, buffer_w
) < 0)
549 git_path_mkposix(buffer
);
554 int p_vsnprintf(char *buffer
, size_t count
, const char *format
, va_list argptr
)
556 #if defined(_MSC_VER)
560 return _vscprintf(format
, argptr
);
563 len
= _vsnprintf_s(buffer
, count
, _TRUNCATE
, format
, argptr
);
565 len
= _vsnprintf(buffer
, count
, format
, argptr
);
569 return _vscprintf(format
, argptr
);
573 return vsnprintf(buffer
, count
, format
, argptr
);
577 int p_snprintf(char *buffer
, size_t count
, const char *format
, ...)
582 va_start(va
, format
);
583 r
= p_vsnprintf(buffer
, count
, format
, va
);
590 int p_mkstemp(char *tmp_path
)
592 #if defined(_MSC_VER) && _MSC_VER >= 1500
593 if (_mktemp_s(tmp_path
, strlen(tmp_path
) + 1) != 0)
596 if (_mktemp(tmp_path
) == NULL
)
600 return p_open(tmp_path
, O_RDWR
| O_CREAT
| O_EXCL
, 0744); //-V536
603 int p_access(const char* path
, mode_t mode
)
607 if (git_win32_path_from_utf8(buf
, path
) < 0)
610 return _waccess(buf
, mode
);
613 static int ensure_writable(wchar_t *fpath
)
617 attrs
= GetFileAttributesW(fpath
);
618 if (attrs
== INVALID_FILE_ATTRIBUTES
) {
619 if (GetLastError() == ERROR_FILE_NOT_FOUND
)
622 giterr_set(GITERR_OS
, "failed to get attributes");
626 if (!(attrs
& FILE_ATTRIBUTE_READONLY
))
629 attrs
&= ~FILE_ATTRIBUTE_READONLY
;
630 if (!SetFileAttributesW(fpath
, attrs
)) {
631 giterr_set(GITERR_OS
, "failed to set attributes");
638 int p_rename(const char *from
, const char *to
)
640 git_win32_path wfrom
;
643 int rename_succeeded
;
646 if (git_win32_path_from_utf8(wfrom
, from
) < 0 ||
647 git_win32_path_from_utf8(wto
, to
) < 0)
650 /* wait up to 50ms if file is locked by another thread or process */
652 rename_succeeded
= 0;
653 while (rename_tries
< 10) {
654 if (ensure_writable(wto
) == 0 &&
655 MoveFileExW(wfrom
, wto
, MOVEFILE_REPLACE_EXISTING
| MOVEFILE_COPY_ALLOWED
) != 0) {
656 rename_succeeded
= 1;
660 error
= GetLastError();
661 if (error
== ERROR_SHARING_VIOLATION
|| error
== ERROR_ACCESS_DENIED
) {
668 return rename_succeeded
? 0 : -1;
671 int p_recv(GIT_SOCKET socket
, void *buffer
, size_t length
, int flags
)
673 if ((size_t)((int)length
) != length
)
674 return -1; /* giterr_set will be done by caller */
676 return recv(socket
, buffer
, (int)length
, flags
);
679 int p_send(GIT_SOCKET socket
, const void *buffer
, size_t length
, int flags
)
681 if ((size_t)((int)length
) != length
)
682 return -1; /* giterr_set will be done by caller */
684 return send(socket
, buffer
, (int)length
, flags
);
688 * Borrowed from http://old.nabble.com/Porting-localtime_r-and-gmtime_r-td15282276.html
689 * On Win32, `gmtime_r` doesn't exist but `gmtime` is threadsafe, so we can use that
692 p_localtime_r (const time_t *timer
, struct tm
*result
)
694 struct tm
*local_result
;
695 local_result
= localtime (timer
);
697 if (local_result
== NULL
|| result
== NULL
)
700 memcpy (result
, local_result
, sizeof (struct tm
));
704 p_gmtime_r (const time_t *timer
, struct tm
*result
)
706 struct tm
*local_result
;
707 local_result
= gmtime (timer
);
709 if (local_result
== NULL
|| result
== NULL
)
712 memcpy (result
, local_result
, sizeof (struct tm
));
716 int p_inet_pton(int af
, const char *src
, void *dst
)
718 struct sockaddr_storage sin
;
720 int sin_len
= sizeof(struct sockaddr_storage
), addr_len
;
724 addr
= &((struct sockaddr_in
*)&sin
)->sin_addr
;
725 addr_len
= sizeof(struct in_addr
);
726 } else if (af
== AF_INET6
) {
727 addr
= &((struct sockaddr_in6
*)&sin
)->sin6_addr
;
728 addr_len
= sizeof(struct in6_addr
);
730 errno
= EAFNOSUPPORT
;
734 if ((error
= WSAStringToAddressA((LPSTR
)src
, af
, NULL
, (LPSOCKADDR
)&sin
, &sin_len
)) == 0) {
735 memcpy(dst
, addr
, addr_len
);
739 switch(WSAGetLastError()) {
745 case WSA_NOT_ENOUGH_MEMORY
: