posix_w32.c 15.1 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
#include "../posix.h"
Russell Belfer committed
8
#include "../fileops.h"
9
#include "path.h"
10
#include "path_w32.h"
11
#include "utf-conv.h"
12
#include "repository.h"
13
#include "reparse.h"
Vicent Marti committed
14
#include <errno.h>
15
#include <io.h>
16
#include <fcntl.h>
17
#include <ws2tcpip.h>
Vicent Marti committed
18

19
#ifndef FILE_NAME_NORMALIZED
20 21 22
# define FILE_NAME_NORMALIZED 0
#endif

23 24 25 26
#ifndef IO_REPARSE_TAG_SYMLINK
#define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
#endif

27 28 29 30 31 32 33 34 35
/* Options which we always provide to _wopen.
 *
 * _O_BINARY - Raw access; no translation of CR or LF characters
 * _O_NOINHERIT - Do not mark the created handle as inheritable by child processes.
 *    The Windows default is 'not inheritable', but the CRT's default (following
 *    POSIX convention) is 'inheritable'. We have no desire for our handles to be
 *    inheritable on Windows, so specify the flag to get default behavior back. */
#define STANDARD_OPEN_FLAGS (_O_BINARY | _O_NOINHERIT)

36 37 38 39 40 41
/* 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)

42 43 44
/* GetFinalPathNameByHandleW signature */
typedef DWORD(WINAPI *PFGetFinalPathNameByHandleW)(HANDLE, LPWSTR, DWORD, DWORD);

45 46 47 48 49 50 51
/**
 * Truncate or extend file.
 *
 * We now take a "git_off_t" rather than "long" because
 * files may be longer than 2Gb.
 */
int p_ftruncate(int fd, git_off_t size)
52
{
53 54 55 56 57
	if (size < 0) {
		errno = EINVAL;
		return -1;
	}

58
#if !defined(__MINGW32__) || defined(MINGW_HAS_SECURE_API)
59
	return ((_chsize_s(fd, size) == 0) ? 0 : -1);
60
#else
61
	/* TODO MINGW32 Find a replacement for _chsize() that handles big files. */
62 63 64 65 66
	if (size > INT32_MAX) {
		errno = EFBIG;
		return -1;
	}
	return _chsize(fd, (long)size);
67 68 69
#endif
}

70 71 72 73 74 75
int p_mkdir(const char *path, mode_t mode)
{
	git_win32_path buf;

	GIT_UNUSED(mode);

76
	if (git_win32_path_from_utf8(buf, path) < 0)
77 78 79 80 81
		return -1;

	return _wmkdir(buf);
}

82 83 84 85 86 87 88 89
int p_link(const char *old, const char *new)
{
	GIT_UNUSED(old);
	GIT_UNUSED(new);
	errno = ENOSYS;
	return -1;
}

Vicent Marti committed
90 91
int p_unlink(const char *path)
{
92
	git_win32_path buf;
93 94
	int error;

95
	if (git_win32_path_from_utf8(buf, path) < 0)
96 97 98 99 100 101
		return -1;

	error = _wunlink(buf);

	/* If the file could not be deleted because it was
	 * read-only, clear the bit and try again */
102
	if (error == -1 && errno == EACCES) {
103 104 105 106 107
		_wchmod(buf, 0666);
		error = _wunlink(buf);
	}

	return error;
Vicent Marti committed
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
}

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

	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;
}

133 134 135 136 137 138 139 140 141 142
#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)) {
143 144 145
		if (!buf)
			return 0;

146
		return git_win32__file_attribute_to_stat(buf, &fdata, path);
Vicent Marti committed
147 148
	}

Eduardo Bart committed
149
	errno = ENOENT;
150

151 152
	/* To match POSIX behavior, set ENOTDIR when any of the folders in the
	 * file path is a regular file, otherwise set ENOENT.
153
	 */
Eduardo Bart committed
154
	if (posix_enotdir) {
155 156
		size_t path_len = wcslen(path);

157 158
		/* scan up path until we find an existing item */
		while (1) {
159 160
			DWORD attrs;

161
			/* remove last directory component */
162
			for (path_len--; path_len > 0 && !WIN32_IS_WSEP(path[path_len]); path_len--);
163

164
			if (path_len <= 0)
165 166
				break;

167 168
			path[path_len] = L'\0';
			attrs = GetFileAttributesW(path);
169

170
			if (attrs != INVALID_FILE_ATTRIBUTES) {
171
				if (!(attrs & FILE_ATTRIBUTE_DIRECTORY))
Eduardo Bart committed
172
					errno = ENOTDIR;
173
				break;
174 175 176 177
			}
		}
	}

178
	return -1;
Vicent Marti committed
179 180
}

181
static int do_lstat(const char *path, struct stat *buf, bool posixly_correct)
Vicent Marti committed
182
{
183 184 185
	git_win32_path path_w;
	int len;

186
	if ((len = git_win32_path_from_utf8(path_w, path)) < 0)
187 188 189 190 191
		return -1;

	git_win32__path_trim_end(path_w, len);

	return lstat_w(path_w, buf, posixly_correct);
192
}
Vicent Marti committed
193

194
int p_lstat(const char *filename, struct stat *buf)
195
{
196
	return do_lstat(filename, buf, false);
Vicent Marti committed
197 198
}

199
int p_lstat_posixly(const char *filename, struct stat *buf)
200
{
201
	return do_lstat(filename, buf, true);
202
}
203

204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
int p_utimes(const char *filename, const struct timeval times[2])
{
	int fd, error;

	if ((fd = p_open(filename, O_RDWR)) < 0)
		return fd;

	error = p_futimes(fd, times);

	close(fd);
	return error;
}

int p_futimes(int fd, const struct timeval times[2])
{
	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;
}

242
int p_readlink(const char *path, char *buf, size_t bufsiz)
Vicent Marti committed
243
{
244 245 246 247 248 249 250 251 252 253 254
	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. */

255
	if (git_win32_path_from_utf8(path_w, path) < 0 ||
256
		git_win32_path_readlink_w(target_w, path_w) < 0 ||
257 258
		(len = git_win32_path_to_utf8(target, target_w)) < 0)
		return -1;
259

260 261
	bufsiz = min((size_t)len, bufsiz);
	memcpy(buf, target, bufsiz);
262

263
	return (int)bufsiz;
Vicent Marti committed
264 265
}

Ben Straub committed
266 267
int p_symlink(const char *old, const char *new)
{
268 269 270 271
	/* Real symlinks on NTFS require admin privileges. Until this changes,
	 * libgit2 just creates a text file with the link target in the contents.
	 */
	return git_futils_fake_symlink(old, new);
Ben Straub committed
272 273
}

274
int p_open(const char *path, int flags, ...)
275
{
276
	git_win32_path buf;
277 278
	mode_t mode = 0;

279
	if (git_win32_path_from_utf8(buf, path) < 0)
280
		return -1;
281

282
	if (flags & O_CREAT) {
283 284 285
		va_list arg_list;

		va_start(arg_list, flags);
liyuray committed
286
		mode = (mode_t)va_arg(arg_list, int);
287 288 289
		va_end(arg_list);
	}

290
	return _wopen(buf, flags | STANDARD_OPEN_FLAGS, mode & WIN32_MODE_MASK);
291 292
}

293
int p_creat(const char *path, mode_t mode)
294
{
295
	git_win32_path buf;
296

297
	if (git_win32_path_from_utf8(buf, path) < 0)
298 299
		return -1;

300 301 302
	return _wopen(buf,
		_O_WRONLY | _O_CREAT | _O_TRUNC | STANDARD_OPEN_FLAGS,
		mode & WIN32_MODE_MASK);
303 304 305 306
}

int p_getcwd(char *buffer_out, size_t size)
{
307 308
	git_win32_path buf;
	wchar_t *cwd = _wgetcwd(buf, GIT_WIN_PATH_UTF16);
309

310
	if (!cwd)
311 312
		return -1;

313 314 315
	/* Convert the working directory back to UTF-8 */
	if (git__utf16_to_8(buffer_out, size, cwd) < 0) {
		DWORD code = GetLastError();
316

317 318 319 320
		if (code == ERROR_INSUFFICIENT_BUFFER)
			errno = ERANGE;
		else
			errno = EINVAL;
321

322 323
		return -1;
	}
324

325
	return 0;
326 327
}

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
/*
 * Returns the address of the GetFinalPathNameByHandleW function.
 * This function is available on Windows Vista and higher.
 */
static PFGetFinalPathNameByHandleW get_fpnbyhandle(void)
{
	static PFGetFinalPathNameByHandleW pFunc = NULL;
	PFGetFinalPathNameByHandleW toReturn = pFunc;

	if (!toReturn) {
		HMODULE hModule = GetModuleHandleW(L"kernel32");

		if (hModule)
			toReturn = (PFGetFinalPathNameByHandleW)GetProcAddress(hModule, "GetFinalPathNameByHandleW");

		pFunc = toReturn;
	}

	assert(toReturn);

	return toReturn;
}

static int getfinalpath_w(
	git_win32_path dest,
	const wchar_t *path)
{
	PFGetFinalPathNameByHandleW pgfp = get_fpnbyhandle();
	HANDLE hFile;
	DWORD dwChars;

	if (!pgfp)
		return -1;

	/* 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);

368
	if (INVALID_HANDLE_VALUE == hFile)
369 370 371 372
		return -1;

	/* Call GetFinalPathNameByHandle */
	dwChars = pgfp(hFile, dest, GIT_WIN_PATH_UTF16, FILE_NAME_NORMALIZED);
373
	CloseHandle(hFile);
374

375
	if (!dwChars || dwChars >= GIT_WIN_PATH_UTF16)
376 377 378
		return -1;

	/* The path may be delivered to us with a prefix; canonicalize */
379
	return (int)git_win32__canonicalize_path(dest, dwChars);
380 381 382 383 384 385 386 387 388 389 390 391
}

static int follow_and_lstat_link(git_win32_path path, struct stat* buf)
{
	git_win32_path target_w;

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

	return lstat_w(target_w, buf, false);
}

392 393
int p_stat(const char* path, struct stat* buf)
{
394 395
	git_win32_path path_w;
	int len;
396

397 398
	if ((len = git_win32_path_from_utf8(path_w, path)) < 0 ||
		lstat_w(path_w, buf, false) < 0)
399 400 401 402 403 404 405 406
		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;
407 408 409 410
}

int p_chdir(const char* path)
{
411
	git_win32_path buf;
412

413
	if (git_win32_path_from_utf8(buf, path) < 0)
414 415
		return -1;

416
	return _wchdir(buf);
417 418
}

419
int p_chmod(const char* path, mode_t mode)
420
{
421
	git_win32_path buf;
422

423
	if (git_win32_path_from_utf8(buf, path) < 0)
424 425
		return -1;

426
	return _wchmod(buf, mode);
427 428 429 430
}

int p_rmdir(const char* path)
{
431
	git_win32_path buf;
432 433
	int error;

434
	if (git_win32_path_from_utf8(buf, path) < 0)
435
		return -1;
436 437 438

	error = _wrmdir(buf);

439
	if (error == -1) {
440 441 442 443 444 445 446 447
		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;
448

449 450 451 452 453 454
			/* This error can be returned when trying to rmdir an extant file. */
			case ERROR_DIRECTORY:
				errno = ENOTDIR;
				break;
		}
	}
455

456
	return error;
Vicent Marti committed
457 458
}

459
char *p_realpath(const char *orig_path, char *buffer)
460
{
461
	git_win32_path orig_path_w, buffer_w;
462

463
	if (git_win32_path_from_utf8(orig_path_w, orig_path) < 0)
464
		return NULL;
465

466 467 468 469 470 471 472 473
	/* 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;
474

475 476
		return NULL;
	}
477

478
	/* The path must exist. */
479
	if (GetFileAttributesW(buffer_w) == INVALID_FILE_ATTRIBUTES) {
480
		errno = ENOENT;
481
		return NULL;
482
	}
483

484 485 486
	if (!buffer && !(buffer = git__malloc(GIT_WIN_PATH_UTF8))) {
		errno = ENOMEM;
		return NULL;
487 488
	}

489 490 491 492 493 494
	/* 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;

495
	git_path_mkposix(buffer);
496

497
	return buffer;
498 499
}

500 501
int p_vsnprintf(char *buffer, size_t count, const char *format, va_list argptr)
{
502
#if defined(_MSC_VER)
503 504
	int len;

505 506 507 508 509 510 511 512 513 514
	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)
515
		return _vscprintf(format, argptr);
516 517

	return len;
518 519 520 521
#else /* MinGW */
	return vsnprintf(buffer, count, format, argptr);
#endif
}
522 523 524 525 526 527 528 529 530 531 532 533

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;
}
534

535
/* TODO: wut? */
536 537
int p_mkstemp(char *tmp_path)
{
538
#if defined(_MSC_VER) && _MSC_VER >= 1500
539
	if (_mktemp_s(tmp_path, strlen(tmp_path) + 1) != 0)
540
		return -1;
541
#else
Vicent Marti committed
542
	if (_mktemp(tmp_path) == NULL)
543
		return -1;
Vicent Marti committed
544
#endif
545

546
	return p_open(tmp_path, O_RDWR | O_CREAT | O_EXCL, 0744); //-V536
547
}
548

549
int p_access(const char* path, mode_t mode)
550
{
551
	git_win32_path buf;
552

553
	if (git_win32_path_from_utf8(buf, path) < 0)
554 555
		return -1;

556
	return _waccess(buf, mode & WIN32_MODE_MASK);
557
}
558

559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
static int ensure_writable(wchar_t *fpath)
{
	DWORD attrs;

	attrs = GetFileAttributesW(fpath);
	if (attrs == INVALID_FILE_ATTRIBUTES) {
		if (GetLastError() == ERROR_FILE_NOT_FOUND)
			return 0;

		giterr_set(GITERR_OS, "failed to get attributes");
		return -1;
	}

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

	attrs &= ~FILE_ATTRIBUTE_READONLY;
	if (!SetFileAttributesW(fpath, attrs)) {
		giterr_set(GITERR_OS, "failed to set attributes");
		return -1;
	}

	return 0;
}

584
int p_rename(const char *from, const char *to)
585
{
586 587
	git_win32_path wfrom;
	git_win32_path wto;
588 589 590
	int rename_tries;
	int rename_succeeded;
	int error;
591

592 593
	if (git_win32_path_from_utf8(wfrom, from) < 0 ||
		git_win32_path_from_utf8(wto, to) < 0)
594
		return -1;
595

596 597 598 599
	/* wait up to 50ms if file is locked by another thread or process */
	rename_tries = 0;
	rename_succeeded = 0;
	while (rename_tries < 10) {
600 601
		if (ensure_writable(wto) == 0 &&
		    MoveFileExW(wfrom, wto, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED) != 0) {
602 603 604 605 606 607 608 609 610 611 612 613 614
			rename_succeeded = 1;
			break;
		}
		
		error = GetLastError();
		if (error == ERROR_SHARING_VIOLATION || error == ERROR_ACCESS_DENIED) {
			Sleep(5);
			rename_tries++;
		} else
			break;
	}
	
	return rename_succeeded ? 0 : -1;
615
}
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631

int p_recv(GIT_SOCKET socket, void *buffer, size_t length, int flags)
{
	if ((size_t)((int)length) != length)
		return -1; /* giterr_set will be done by caller */

	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)
		return -1; /* giterr_set will be done by caller */

	return send(socket, buffer, (int)length, flags);
}
Ben Straub committed
632 633 634 635 636

/**
 * 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
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
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
660 661
}

662
int p_inet_pton(int af, const char *src, void *dst)
663
{
664 665 666 667
	struct sockaddr_storage sin;
	void *addr;
	int sin_len = sizeof(struct sockaddr_storage), addr_len;
	int error = 0;
668

669 670 671 672 673 674 675 676 677
	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;
678 679
	}

680 681 682
	if ((error = WSAStringToAddressA((LPSTR)src, af, NULL, (LPSOCKADDR)&sin, &sin_len)) == 0) {
		memcpy(dst, addr, addr_len);
		return 1;
683 684
	}

685 686 687 688 689 690 691 692 693
	switch(WSAGetLastError()) {
	case WSAEINVAL:
		return 0;
	case WSAEFAULT:
		errno = ENOSPC;
		return -1;
	case WSA_NOT_ENOUGH_MEMORY:
		errno = ENOMEM;
		return -1;
694 695
	}

696 697
	errno = EINVAL;
	return -1;
698
}