posix_w32.c 23.4 KB
Newer Older
1
/*
Edward Thomson committed
2
 * Copyright (C) the libgit2 contributors. All rights reserved.
Vicent Marti committed
3 4 5 6
 *
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
 */
7 8 9

#include "common.h"

10
#include "../posix.h"
11
#include "../futils.h"
12
#include "fs_path.h"
13
#include "path_w32.h"
14
#include "utf-conv.h"
15
#include "reparse.h"
Vicent Marti committed
16
#include <errno.h>
17
#include <io.h>
18
#include <fcntl.h>
19
#include <ws2tcpip.h>
Vicent Marti committed
20

21
#ifndef FILE_NAME_NORMALIZED
22 23 24
# define FILE_NAME_NORMALIZED 0
#endif

25 26 27 28
#ifndef IO_REPARSE_TAG_SYMLINK
#define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
#endif

29 30 31 32
#ifndef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
# define SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE 0x02
#endif

33 34 35 36
#ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
# define SYMBOLIC_LINK_FLAG_DIRECTORY 0x01
#endif

37 38 39 40 41 42
/* Allowable mode bits on Win32.  Using mode bits that are not supported on
 * Win32 (eg S_IRWXU) is generally ignored, but Wine warns loudly about it
 * so we simply remove them.
 */
#define WIN32_MODE_MASK (_S_IREAD | _S_IWRITE)

43 44
unsigned long git_win32__createfile_sharemode =
 FILE_SHARE_READ | FILE_SHARE_WRITE;
45
int git_win32__retries = 10;
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
GIT_INLINE(void) set_errno(void)
{
	switch (GetLastError()) {
	case ERROR_FILE_NOT_FOUND:
	case ERROR_PATH_NOT_FOUND:
	case ERROR_INVALID_DRIVE:
	case ERROR_NO_MORE_FILES:
	case ERROR_BAD_NETPATH:
	case ERROR_BAD_NET_NAME:
	case ERROR_BAD_PATHNAME:
	case ERROR_FILENAME_EXCED_RANGE:
		errno = ENOENT;
		break;
	case ERROR_BAD_ENVIRONMENT:
		errno = E2BIG;
		break;
	case ERROR_BAD_FORMAT:
	case ERROR_INVALID_STARTING_CODESEG:
	case ERROR_INVALID_STACKSEG:
	case ERROR_INVALID_MODULETYPE:
	case ERROR_INVALID_EXE_SIGNATURE:
	case ERROR_EXE_MARKED_INVALID:
	case ERROR_BAD_EXE_FORMAT:
	case ERROR_ITERATED_DATA_EXCEEDS_64k:
	case ERROR_INVALID_MINALLOCSIZE:
	case ERROR_DYNLINK_FROM_INVALID_RING:
	case ERROR_IOPL_NOT_ENABLED:
	case ERROR_INVALID_SEGDPL:
	case ERROR_AUTODATASEG_EXCEEDS_64k:
	case ERROR_RING2SEG_MUST_BE_MOVABLE:
	case ERROR_RELOC_CHAIN_XEEDS_SEGLIM:
	case ERROR_INFLOOP_IN_RELOC_CHAIN:
		errno = ENOEXEC;
		break;
	case ERROR_INVALID_HANDLE:
	case ERROR_INVALID_TARGET_HANDLE:
	case ERROR_DIRECT_ACCESS_HANDLE:
		errno = EBADF;
		break;
	case ERROR_WAIT_NO_CHILDREN:
	case ERROR_CHILD_NOT_COMPLETE:
		errno = ECHILD;
		break;
	case ERROR_NO_PROC_SLOTS:
	case ERROR_MAX_THRDS_REACHED:
	case ERROR_NESTING_NOT_ALLOWED:
		errno = EAGAIN;
		break;
	case ERROR_ARENA_TRASHED:
	case ERROR_NOT_ENOUGH_MEMORY:
	case ERROR_INVALID_BLOCK:
	case ERROR_NOT_ENOUGH_QUOTA:
		errno = ENOMEM;
		break;
	case ERROR_ACCESS_DENIED:
	case ERROR_CURRENT_DIRECTORY:
	case ERROR_WRITE_PROTECT:
	case ERROR_BAD_UNIT:
	case ERROR_NOT_READY:
	case ERROR_BAD_COMMAND:
	case ERROR_CRC:
	case ERROR_BAD_LENGTH:
	case ERROR_SEEK:
	case ERROR_NOT_DOS_DISK:
	case ERROR_SECTOR_NOT_FOUND:
	case ERROR_OUT_OF_PAPER:
	case ERROR_WRITE_FAULT:
	case ERROR_READ_FAULT:
	case ERROR_GEN_FAILURE:
	case ERROR_SHARING_VIOLATION:
	case ERROR_LOCK_VIOLATION:
	case ERROR_WRONG_DISK:
	case ERROR_SHARING_BUFFER_EXCEEDED:
	case ERROR_NETWORK_ACCESS_DENIED:
	case ERROR_CANNOT_MAKE:
	case ERROR_FAIL_I24:
	case ERROR_DRIVE_LOCKED:
	case ERROR_SEEK_ON_DEVICE:
	case ERROR_NOT_LOCKED:
	case ERROR_LOCK_FAILED:
		errno = EACCES;
		break;
	case ERROR_FILE_EXISTS:
	case ERROR_ALREADY_EXISTS:
		errno = EEXIST;
		break;
	case ERROR_NOT_SAME_DEVICE:
		errno = EXDEV;
		break;
	case ERROR_INVALID_FUNCTION:
	case ERROR_INVALID_ACCESS:
	case ERROR_INVALID_DATA:
	case ERROR_INVALID_PARAMETER:
	case ERROR_NEGATIVE_SEEK:
		errno = EINVAL;
		break;
	case ERROR_TOO_MANY_OPEN_FILES:
		errno = EMFILE;
		break;
	case ERROR_DISK_FULL:
		errno = ENOSPC;
		break;
	case ERROR_BROKEN_PIPE:
		errno = EPIPE;
		break;
	case ERROR_DIR_NOT_EMPTY:
		errno = ENOTEMPTY;
		break;
	default:
		errno = EINVAL;
	}
}

160 161 162 163 164 165 166 167
GIT_INLINE(bool) last_error_retryable(void)
{
	int os_error = GetLastError();

	return (os_error == ERROR_SHARING_VIOLATION ||
		os_error == ERROR_ACCESS_DENIED);
}

168
#define do_with_retries(fn, remediation) \
169
	do {                                                             \
170 171
		int __retry, __ret;                                          \
		for (__retry = git_win32__retries; __retry; __retry--) {     \
172 173
			if ((__ret = (fn)) != GIT_RETRY)                         \
				return __ret;                                        \
174 175 176 177 178
			if (__retry > 1 && (__ret = (remediation)) != 0) {       \
				if (__ret == GIT_RETRY)                              \
					continue;                                        \
				return __ret;                                        \
			}                                                        \
179 180 181 182 183
			Sleep(5);                                                \
		}                                                            \
		return -1;                                                   \
	} while (0)                                                      \

184 185 186 187 188 189 190 191 192 193 194 195 196
static int ensure_writable(wchar_t *path)
{
	DWORD attrs;

	if ((attrs = GetFileAttributesW(path)) == INVALID_FILE_ATTRIBUTES)
		goto on_error;

	if ((attrs & FILE_ATTRIBUTE_READONLY) == 0)
		return 0;

	if (!SetFileAttributesW(path, (attrs & ~FILE_ATTRIBUTE_READONLY)))
		goto on_error;

197
	return GIT_RETRY;
198 199 200 201 202 203

on_error:
	set_errno();
	return -1;
}

204 205 206 207 208 209
/**
 * Truncate or extend file.
 *
 * We now take a "git_off_t" rather than "long" because
 * files may be longer than 2Gb.
 */
210
int p_ftruncate(int fd, off64_t size)
211
{
212 213 214 215 216
	if (size < 0) {
		errno = EINVAL;
		return -1;
	}

217
#if !defined(__MINGW32__) || defined(MINGW_HAS_SECURE_API)
218
	return ((_chsize_s(fd, size) == 0) ? 0 : -1);
219
#else
220
	/* TODO MINGW32 Find a replacement for _chsize() that handles big files. */
221 222 223 224 225
	if (size > INT32_MAX) {
		errno = EFBIG;
		return -1;
	}
	return _chsize(fd, (long)size);
226 227 228
#endif
}

229 230 231 232 233 234
int p_mkdir(const char *path, mode_t mode)
{
	git_win32_path buf;

	GIT_UNUSED(mode);

235
	if (git_win32_path_from_utf8(buf, path) < 0)
236 237 238 239 240
		return -1;

	return _wmkdir(buf);
}

241 242 243 244 245 246 247 248
int p_link(const char *old, const char *new)
{
	GIT_UNUSED(old);
	GIT_UNUSED(new);
	errno = ENOSYS;
	return -1;
}

249 250
GIT_INLINE(int) unlink_once(const wchar_t *path)
{
251 252
	DWORD error;

253 254 255
	if (DeleteFileW(path))
		return 0;

256 257 258 259 260 261 262 263 264 265 266 267 268 269
	if ((error = GetLastError()) == ERROR_ACCESS_DENIED) {
		WIN32_FILE_ATTRIBUTE_DATA fdata;
		if (!GetFileAttributesExW(path, GetFileExInfoStandard, &fdata) ||
		    !(fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) ||
		    !(fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
			goto out;

		if (RemoveDirectoryW(path))
			return 0;
	}

out:
	SetLastError(error);

270 271 272 273 274 275 276
	if (last_error_retryable())
		return GIT_RETRY;

	set_errno();
	return -1;
}

Vicent Marti committed
277 278
int p_unlink(const char *path)
{
279
	git_win32_path wpath;
280

281
	if (git_win32_path_from_utf8(wpath, path) < 0)
282 283
		return -1;

284
	do_with_retries(unlink_once(wpath), ensure_writable(wpath));
Vicent Marti committed
285 286 287 288 289 290
}

int p_fsync(int fd)
{
	HANDLE fh = (HANDLE)_get_osfhandle(fd);

291 292
	p_fsync__cnt++;

Vicent Marti committed
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
	if (fh == INVALID_HANDLE_VALUE) {
		errno = EBADF;
		return -1;
	}

	if (!FlushFileBuffers(fh)) {
		DWORD code = GetLastError();

		if (code == ERROR_INVALID_HANDLE)
			errno = EINVAL;
		else
			errno = EIO;

		return -1;
	}

	return 0;
}

312 313 314 315 316 317 318 319 320 321
#define WIN32_IS_WSEP(CH) ((CH) == L'/' || (CH) == L'\\')

static int lstat_w(
	wchar_t *path,
	struct stat *buf,
	bool posix_enotdir)
{
	WIN32_FILE_ATTRIBUTE_DATA fdata;

	if (GetFileAttributesExW(path, GetFileExInfoStandard, &fdata)) {
322 323 324
		if (!buf)
			return 0;

325
		return git_win32__file_attribute_to_stat(buf, &fdata, path);
Vicent Marti committed
326 327
	}

328 329 330 331 332 333 334 335
	switch (GetLastError()) {
	case ERROR_ACCESS_DENIED:
		errno = EACCES;
		break;
	default:
		errno = ENOENT;
		break;
	}
336

337 338
	/* To match POSIX behavior, set ENOTDIR when any of the folders in the
	 * file path is a regular file, otherwise set ENOENT.
339
	 */
340
	if (errno == ENOENT && posix_enotdir) {
341 342
		size_t path_len = wcslen(path);

343 344
		/* scan up path until we find an existing item */
		while (1) {
345 346
			DWORD attrs;

347
			/* remove last directory component */
348
			for (path_len--; path_len > 0 && !WIN32_IS_WSEP(path[path_len]); path_len--);
349

350
			if (path_len <= 0)
351 352
				break;

353 354
			path[path_len] = L'\0';
			attrs = GetFileAttributesW(path);
355

356
			if (attrs != INVALID_FILE_ATTRIBUTES) {
357
				if (!(attrs & FILE_ATTRIBUTE_DIRECTORY))
Eduardo Bart committed
358
					errno = ENOTDIR;
359
				break;
360 361 362 363
			}
		}
	}

364
	return -1;
Vicent Marti committed
365 366
}

367
static int do_lstat(const char *path, struct stat *buf, bool posixly_correct)
Vicent Marti committed
368
{
369 370 371
	git_win32_path path_w;
	int len;

372
	if ((len = git_win32_path_from_utf8(path_w, path)) < 0)
373 374
		return -1;

375
	git_win32_path_trim_end(path_w, len);
376 377

	return lstat_w(path_w, buf, posixly_correct);
378
}
Vicent Marti committed
379

380
int p_lstat(const char *filename, struct stat *buf)
381
{
382
	return do_lstat(filename, buf, false);
Vicent Marti committed
383 384
}

385
int p_lstat_posixly(const char *filename, struct stat *buf)
386
{
387
	return do_lstat(filename, buf, true);
388
}
389

390
int p_readlink(const char *path, char *buf, size_t bufsiz)
Vicent Marti committed
391
{
392 393 394 395 396 397 398 399 400 401 402
	git_win32_path path_w, target_w;
	git_win32_utf8_path target;
	int len;

	/* readlink(2) does not NULL-terminate the string written
	 * to the target buffer. Furthermore, the target buffer need
	 * not be large enough to hold the entire result. A truncated
	 * result should be written in this case. Since this truncation
	 * could occur in the middle of the encoding of a code point,
	 * we need to buffer the result on the stack. */

403
	if (git_win32_path_from_utf8(path_w, path) < 0 ||
404
		git_win32_path_readlink_w(target_w, path_w) < 0 ||
405 406
		(len = git_win32_path_to_utf8(target, target_w)) < 0)
		return -1;
407

408 409
	bufsiz = min((size_t)len, bufsiz);
	memcpy(buf, target, bufsiz);
410

411
	return (int)bufsiz;
Vicent Marti committed
412 413
}

414 415
static bool target_is_dir(const char *target, const char *path)
{
416
	git_str resolved = GIT_STR_INIT;
417 418 419
	git_win32_path resolved_w;
	bool isdir = true;

420
	if (git_fs_path_is_absolute(target))
421
		git_win32_path_from_utf8(resolved_w, target);
422 423
	else if (git_fs_path_dirname_r(&resolved, path) < 0 ||
		 git_fs_path_apply_relative(&resolved, target) < 0 ||
424 425 426 427 428 429
		 git_win32_path_from_utf8(resolved_w, resolved.ptr) < 0)
		goto out;

	isdir = GetFileAttributesW(resolved_w) & FILE_ATTRIBUTE_DIRECTORY;

out:
430
	git_str_dispose(&resolved);
431 432 433
	return isdir;
}

434
int p_symlink(const char *target, const char *path)
Ben Straub committed
435
{
436
	git_win32_path target_w, path_w;
437
	DWORD dwFlags;
438

439 440 441 442 443 444 445
	/*
	 * Convert both target and path to Windows-style paths. Note that we do
	 * not want to use `git_win32_path_from_utf8` for converting the target,
	 * as that function will automatically pre-pend the current working
	 * directory in case the path is not absolute. As Git will instead use
	 * relative symlinks, this is not someting we want.
	 */
446
	if (git_win32_path_from_utf8(path_w, path) < 0 ||
447
	    git_win32_path_relative_from_utf8(target_w, target) < 0)
448 449
		return -1;

450
	dwFlags = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
451
	if (target_is_dir(target, path))
452 453 454
		dwFlags |= SYMBOLIC_LINK_FLAG_DIRECTORY;

	if (!CreateSymbolicLinkW(path_w, target_w, dwFlags))
455 456 457
		return -1;

	return 0;
Ben Straub committed
458 459
}

460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
struct open_opts {
	DWORD access;
	DWORD sharing;
	SECURITY_ATTRIBUTES security;
	DWORD creation_disposition;
	DWORD attributes;
	int osf_flags;
};

GIT_INLINE(void) open_opts_from_posix(struct open_opts *opts, int flags, mode_t mode)
{
	memset(opts, 0, sizeof(struct open_opts));

	switch (flags & (O_WRONLY | O_RDWR)) {
	case O_WRONLY:
		opts->access = GENERIC_WRITE;
		break;
	case O_RDWR:
		opts->access = GENERIC_READ | GENERIC_WRITE;
		break;
	default:
		opts->access = GENERIC_READ;
		break;
	}

	opts->sharing = (DWORD)git_win32__createfile_sharemode;

	switch (flags & (O_CREAT | O_TRUNC | O_EXCL)) {
	case O_CREAT | O_EXCL:
	case O_CREAT | O_TRUNC | O_EXCL:
		opts->creation_disposition = CREATE_NEW;
		break;
	case O_CREAT | O_TRUNC:
		opts->creation_disposition = CREATE_ALWAYS;
		break;
	case O_TRUNC:
		opts->creation_disposition = TRUNCATE_EXISTING;
		break;
	case O_CREAT:
		opts->creation_disposition = OPEN_ALWAYS;
		break;
	default:
		opts->creation_disposition = OPEN_EXISTING;
		break;
	}

	opts->attributes = ((flags & O_CREAT) && !(mode & S_IWRITE)) ?
		FILE_ATTRIBUTE_READONLY : FILE_ATTRIBUTE_NORMAL;
	opts->osf_flags = flags & (O_RDONLY | O_APPEND);

	opts->security.nLength = sizeof(SECURITY_ATTRIBUTES);
	opts->security.lpSecurityDescriptor = NULL;
	opts->security.bInheritHandle = 0;
}

515 516
GIT_INLINE(int) open_once(
	const wchar_t *path,
517
	struct open_opts *opts)
518
{
519 520
	int fd;

521 522
	HANDLE handle = CreateFileW(path, opts->access, opts->sharing,
		&opts->security, opts->creation_disposition, opts->attributes, 0);
523

524 525 526 527 528 529 530 531
	if (handle == INVALID_HANDLE_VALUE) {
		if (last_error_retryable())
			return GIT_RETRY;

		set_errno();
		return -1;
	}

532 533 534 535
	if ((fd = _open_osfhandle((intptr_t)handle, opts->osf_flags)) < 0)
		CloseHandle(handle);

	return fd;
536 537
}

538
int p_open(const char *path, int flags, ...)
539
{
540
	git_win32_path wpath;
541
	mode_t mode = 0;
542
	struct open_opts opts = {0};
543

544 545 546 547 548 549 550
	#ifdef GIT_DEBUG_STRICT_OPEN
	if (strstr(path, "//") != NULL) {
		errno = EACCES;
		return -1;
	}
	#endif

551
	if (git_win32_path_from_utf8(wpath, path) < 0)
552
		return -1;
553

554
	if (flags & O_CREAT) {
555 556 557
		va_list arg_list;

		va_start(arg_list, flags);
liyuray committed
558
		mode = (mode_t)va_arg(arg_list, int);
559 560 561
		va_end(arg_list);
	}

562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
	open_opts_from_posix(&opts, flags, mode);

	do_with_retries(
		open_once(wpath, &opts),
		0);
}

int p_creat(const char *path, mode_t mode)
{
	return p_open(path, O_WRONLY | O_CREAT | O_TRUNC, mode);
}

int p_utimes(const char *path, const struct p_timeval times[2])
{
	git_win32_path wpath;
	int fd, error;
	DWORD attrs_orig, attrs_new = 0;
	struct open_opts opts = { 0 };

	if (git_win32_path_from_utf8(wpath, path) < 0)
		return -1;

	attrs_orig = GetFileAttributesW(wpath);

	if (attrs_orig & FILE_ATTRIBUTE_READONLY) {
		attrs_new = attrs_orig & ~FILE_ATTRIBUTE_READONLY;

		if (!SetFileAttributesW(wpath, attrs_new)) {
590
			git_error_set(GIT_ERROR_OS, "failed to set attributes");
591 592
			return -1;
		}
593 594
	}

595
	open_opts_from_posix(&opts, O_RDWR, 0);
596

597 598 599
	if ((fd = open_once(wpath, &opts)) < 0) {
		error = -1;
		goto done;
600 601
	}

602 603
	error = p_futimes(fd, times);
	close(fd);
604

605 606 607 608 609 610 611 612
done:
	if (attrs_orig != attrs_new) {
		DWORD os_error = GetLastError();
		SetFileAttributesW(wpath, attrs_orig);
		SetLastError(os_error);
	}

	return error;
613 614
}

615
int p_futimes(int fd, const struct p_timeval times[2])
616
{
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
	HANDLE handle;
	FILETIME atime = { 0 }, mtime = { 0 };

	if (times == NULL) {
		SYSTEMTIME st;

		GetSystemTime(&st);
		SystemTimeToFileTime(&st, &atime);
		SystemTimeToFileTime(&st, &mtime);
	}
	else {
		git_win32__timeval_to_filetime(&atime, times[0]);
		git_win32__timeval_to_filetime(&mtime, times[1]);
	}

	if ((handle = (HANDLE)_get_osfhandle(fd)) == INVALID_HANDLE_VALUE)
		return -1;

	if (SetFileTime(handle, NULL, &atime, &mtime) == 0)
		return -1;

	return 0;
639 640 641 642
}

int p_getcwd(char *buffer_out, size_t size)
{
643 644
	git_win32_path buf;
	wchar_t *cwd = _wgetcwd(buf, GIT_WIN_PATH_UTF16);
645

646
	if (!cwd)
647 648
		return -1;

649 650
	git_win32_path_remove_namespace(cwd, wcslen(cwd));

651 652 653
	/* Convert the working directory back to UTF-8 */
	if (git__utf16_to_8(buffer_out, size, cwd) < 0) {
		DWORD code = GetLastError();
654

655 656 657 658
		if (code == ERROR_INSUFFICIENT_BUFFER)
			errno = ERANGE;
		else
			errno = EINVAL;
659

660 661
		return -1;
	}
662

663
	git_fs_path_mkposix(buffer_out);
664
	return 0;
665 666
}

667 668 669 670 671 672 673 674 675 676 677 678 679
static int getfinalpath_w(
	git_win32_path dest,
	const wchar_t *path)
{
	HANDLE hFile;
	DWORD dwChars;

	/* Use FILE_FLAG_BACKUP_SEMANTICS so we can open a directory. Do not
	* specify FILE_FLAG_OPEN_REPARSE_POINT; we want to open a handle to the
	* target of the link. */
	hFile = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE,
		NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

680
	if (INVALID_HANDLE_VALUE == hFile)
681 682 683
		return -1;

	/* Call GetFinalPathNameByHandle */
684
	dwChars = GetFinalPathNameByHandleW(hFile, dest, GIT_WIN_PATH_UTF16, FILE_NAME_NORMALIZED);
685
	CloseHandle(hFile);
686

687
	if (!dwChars || dwChars >= GIT_WIN_PATH_UTF16)
688 689
		return -1;

690 691
	/* The path may be delivered to us with a namespace prefix; remove */
	return (int)git_win32_path_remove_namespace(dest, dwChars);
692 693
}

694
static int follow_and_lstat_link(git_win32_path path, struct stat *buf)
695 696 697 698 699 700 701 702 703
{
	git_win32_path target_w;

	if (getfinalpath_w(target_w, path) < 0)
		return -1;

	return lstat_w(target_w, buf, false);
}

704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
int p_fstat(int fd, struct stat *buf)
{
	BY_HANDLE_FILE_INFORMATION fhInfo;

	HANDLE fh = (HANDLE)_get_osfhandle(fd);

	if (fh == INVALID_HANDLE_VALUE ||
		!GetFileInformationByHandle(fh, &fhInfo)) {
		errno = EBADF;
		return -1;
	}

	git_win32__file_information_to_stat(buf, &fhInfo);
	return 0;
}

720
int p_stat(const char *path, struct stat *buf)
721
{
722 723
	git_win32_path path_w;
	int len;
724

725 726
	if ((len = git_win32_path_from_utf8(path_w, path)) < 0 ||
		lstat_w(path_w, buf, false) < 0)
727 728 729 730 731 732 733 734
		return -1;

	/* The item is a symbolic link or mount point. No need to iterate
	 * to follow multiple links; use GetFinalPathNameFromHandle. */
	if (S_ISLNK(buf->st_mode))
		return follow_and_lstat_link(path_w, buf);

	return 0;
735 736
}

737
int p_chdir(const char *path)
738
{
739
	git_win32_path buf;
740

741
	if (git_win32_path_from_utf8(buf, path) < 0)
742 743
		return -1;

744
	return _wchdir(buf);
745 746
}

747
int p_chmod(const char *path, mode_t mode)
748
{
749
	git_win32_path buf;
750

751
	if (git_win32_path_from_utf8(buf, path) < 0)
752 753
		return -1;

754
	return _wchmod(buf, mode);
755 756
}

757
int p_rmdir(const char *path)
758
{
759
	git_win32_path buf;
760 761
	int error;

762
	if (git_win32_path_from_utf8(buf, path) < 0)
763
		return -1;
764 765 766

	error = _wrmdir(buf);

767
	if (error == -1) {
768 769 770 771 772 773 774 775
		switch (GetLastError()) {
			/* _wrmdir() is documented to return EACCES if "A program has an open
			 * handle to the directory."  This sounds like what everybody else calls
			 * EBUSY.  Let's convert appropriate error codes.
			 */
			case ERROR_SHARING_VIOLATION:
				errno = EBUSY;
				break;
776

777 778 779 780 781 782
			/* This error can be returned when trying to rmdir an extant file. */
			case ERROR_DIRECTORY:
				errno = ENOTDIR;
				break;
		}
	}
783

784
	return error;
Vicent Marti committed
785 786
}

787
char *p_realpath(const char *orig_path, char *buffer)
788
{
789
	git_win32_path orig_path_w, buffer_w;
790

791
	if (git_win32_path_from_utf8(orig_path_w, orig_path) < 0)
792
		return NULL;
793

794 795 796 797 798 799 800 801
	/* Note that if the path provided is a relative path, then the current directory
	 * is used to resolve the path -- which is a concurrency issue because the current
	 * directory is a process-wide variable. */
	if (!GetFullPathNameW(orig_path_w, GIT_WIN_PATH_UTF16, buffer_w, NULL)) {
		if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
			errno = ENAMETOOLONG;
		else
			errno = EINVAL;
802

803 804
		return NULL;
	}
805

806
	/* The path must exist. */
807
	if (GetFileAttributesW(buffer_w) == INVALID_FILE_ATTRIBUTES) {
808
		errno = ENOENT;
809
		return NULL;
810
	}
811

812 813 814
	if (!buffer && !(buffer = git__malloc(GIT_WIN_PATH_UTF8))) {
		errno = ENOMEM;
		return NULL;
815 816
	}

817 818 819 820 821 822
	/* Convert the path to UTF-8. If the caller provided a buffer, then it
	 * is assumed to be GIT_WIN_PATH_UTF8 characters in size. If it isn't,
	 * then we may overflow. */
	if (git_win32_path_to_utf8(buffer, buffer_w) < 0)
		return NULL;

823
	git_fs_path_mkposix(buffer);
824

825
	return buffer;
826 827
}

828 829
int p_vsnprintf(char *buffer, size_t count, const char *format, va_list argptr)
{
830
#if defined(_MSC_VER)
831 832
	int len;

833 834 835 836 837 838 839 840 841 842
	if (count == 0)
		return _vscprintf(format, argptr);

	#if _MSC_VER >= 1500
	len = _vsnprintf_s(buffer, count, _TRUNCATE, format, argptr);
	#else
	len = _vsnprintf(buffer, count, format, argptr);
	#endif

	if (len < 0)
843
		return _vscprintf(format, argptr);
844 845

	return len;
846 847 848 849
#else /* MinGW */
	return vsnprintf(buffer, count, format, argptr);
#endif
}
850 851 852 853 854 855 856 857 858 859 860 861

int p_snprintf(char *buffer, size_t count, const char *format, ...)
{
	va_list va;
	int r;

	va_start(va, format);
	r = p_vsnprintf(buffer, count, format, va);
	va_end(va);

	return r;
}
862

863
/* TODO: wut? */
864 865
int p_mkstemp(char *tmp_path)
{
866
#if defined(_MSC_VER) && _MSC_VER >= 1500
867
	if (_mktemp_s(tmp_path, strlen(tmp_path) + 1) != 0)
868
		return -1;
869
#else
Vicent Marti committed
870
	if (_mktemp(tmp_path) == NULL)
871
		return -1;
Vicent Marti committed
872
#endif
873

874
	return p_open(tmp_path, O_RDWR | O_CREAT | O_EXCL, 0744); /* -V536 */
875
}
876

877
int p_access(const char *path, mode_t mode)
878
{
879
	git_win32_path buf;
880

881
	if (git_win32_path_from_utf8(buf, path) < 0)
882 883
		return -1;

884
	return _waccess(buf, mode & WIN32_MODE_MASK);
885
}
886

887 888 889 890 891 892 893 894 895 896
GIT_INLINE(int) rename_once(const wchar_t *from, const wchar_t *to)
{
	if (MoveFileExW(from, to, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED))
		return 0;

	if (last_error_retryable())
		return GIT_RETRY;

	set_errno();
	return -1;
897 898
}

899
int p_rename(const char *from, const char *to)
900
{
901
	git_win32_path wfrom, wto;
902

903 904
	if (git_win32_path_from_utf8(wfrom, from) < 0 ||
		git_win32_path_from_utf8(wto, to) < 0)
905
		return -1;
906

907
	do_with_retries(rename_once(wfrom, wto), ensure_writable(wto));
908
}
909 910 911 912

int p_recv(GIT_SOCKET socket, void *buffer, size_t length, int flags)
{
	if ((size_t)((int)length) != length)
913
		return -1; /* git_error_set will be done by caller */
914 915 916 917 918 919 920

	return recv(socket, buffer, (int)length, flags);
}

int p_send(GIT_SOCKET socket, const void *buffer, size_t length, int flags)
{
	if ((size_t)((int)length) != length)
921
		return -1; /* git_error_set will be done by caller */
922 923 924

	return send(socket, buffer, (int)length, flags);
}
Ben Straub committed
925 926 927 928 929

/**
 * Borrowed from http://old.nabble.com/Porting-localtime_r-and-gmtime_r-td15282276.html
 * On Win32, `gmtime_r` doesn't exist but `gmtime` is threadsafe, so we can use that
 */
Linquize committed
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
struct tm *
p_localtime_r (const time_t *timer, struct tm *result)
{
	struct tm *local_result;
	local_result = localtime (timer);

	if (local_result == NULL || result == NULL)
		return NULL;

	memcpy (result, local_result, sizeof (struct tm));
	return result;
}
struct tm *
p_gmtime_r (const time_t *timer, struct tm *result)
{
	struct tm *local_result;
	local_result = gmtime (timer);

	if (local_result == NULL || result == NULL)
		return NULL;

	memcpy (result, local_result, sizeof (struct tm));
	return result;
Ben Straub committed
953 954
}

955
int p_inet_pton(int af, const char *src, void *dst)
956
{
957 958 959 960
	struct sockaddr_storage sin;
	void *addr;
	int sin_len = sizeof(struct sockaddr_storage), addr_len;
	int error = 0;
961

962 963 964 965 966 967 968 969 970
	if (af == AF_INET) {
		addr = &((struct sockaddr_in *)&sin)->sin_addr;
		addr_len = sizeof(struct in_addr);
	} else if (af == AF_INET6) {
		addr = &((struct sockaddr_in6 *)&sin)->sin6_addr;
		addr_len = sizeof(struct in6_addr);
	} else {
		errno = EAFNOSUPPORT;
		return -1;
971 972
	}

973 974 975
	if ((error = WSAStringToAddressA((LPSTR)src, af, NULL, (LPSOCKADDR)&sin, &sin_len)) == 0) {
		memcpy(dst, addr, addr_len);
		return 1;
976 977
	}

978 979 980 981 982 983 984 985 986
	switch(WSAGetLastError()) {
	case WSAEINVAL:
		return 0;
	case WSAEFAULT:
		errno = ENOSPC;
		return -1;
	case WSA_NOT_ENOUGH_MEMORY:
		errno = ENOMEM;
		return -1;
987 988
	}

989 990
	errno = EINVAL;
	return -1;
991
}
992 993 994 995 996 997 998 999 1000 1001 1002 1003

ssize_t p_pread(int fd, void *data, size_t size, off64_t offset)
{
	HANDLE fh;
	DWORD rsize = 0;
	OVERLAPPED ov = {0};
	LARGE_INTEGER pos = {0};
	off64_t final_offset = 0;

	/* Fail if the final offset would have overflowed to match POSIX semantics. */
	if (!git__is_ssizet(size) || git__add_int64_overflow(&final_offset, offset, (int64_t)size)) {
		errno = EINVAL;
1004
		return -1;
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
	}

	/*
	 * Truncate large writes to the maximum allowable size: the caller
	 * needs to always call this in a loop anyways.
	 */
	if (size > INT32_MAX) {
		size = INT32_MAX;
	}

	pos.QuadPart = offset;
	ov.Offset = pos.LowPart;
	ov.OffsetHigh = pos.HighPart;
	fh = (HANDLE)_get_osfhandle(fd);

	if (ReadFile(fh, data, (DWORD)size, &rsize, &ov)) {
		return (ssize_t)rsize;
	}

	set_errno();
	return -1;
}

ssize_t p_pwrite(int fd, const void *data, size_t size, off64_t offset)
{
	HANDLE fh;
	DWORD wsize = 0;
	OVERLAPPED ov = {0};
	LARGE_INTEGER pos = {0};
	off64_t final_offset = 0;

	/* Fail if the final offset would have overflowed to match POSIX semantics. */
	if (!git__is_ssizet(size) || git__add_int64_overflow(&final_offset, offset, (int64_t)size)) {
		errno = EINVAL;
1039
		return -1;
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
	}

	/*
	 * Truncate large writes to the maximum allowable size: the caller
	 * needs to always call this in a loop anyways.
	 */
	if (size > INT32_MAX) {
		size = INT32_MAX;
	}

	pos.QuadPart = offset;
	ov.Offset = pos.LowPart;
	ov.OffsetHigh = pos.HighPart;
	fh = (HANDLE)_get_osfhandle(fd);

	if (WriteFile(fh, data, (DWORD)size, &wsize, &ov)) {
		return (ssize_t)wsize;
	}

	set_errno();
	return -1;
}