fs.h 11.7 KB
Newer Older
1 2 3 4 5
/*
 * By default, use a read/write loop to copy files on POSIX systems.
 * On Linux, use sendfile by default as it's slightly faster.  On
 * macOS, we avoid fcopyfile by default because it's slightly slower.
 */
6
#undef USE_FCOPYFILE
7
#define USE_SENDFILE 1
8

Vicent Marti committed
9 10
#ifdef _WIN32

11 12 13 14 15 16
#ifdef CLAR_WIN32_LONGPATHS
# define CLAR_MAX_PATH 4096
#else
# define CLAR_MAX_PATH MAX_PATH
#endif

Vicent Marti committed
17 18 19 20 21 22 23 24 25 26 27 28
#define RM_RETRY_COUNT	5
#define RM_RETRY_DELAY	10

#ifdef __MINGW32__

/* These security-enhanced functions are not available
 * in MinGW, so just use the vanilla ones */
#define wcscpy_s(a, b, c) wcscpy((a), (c))
#define wcscat_s(a, b, c) wcscat((a), (c))

#endif /* __MINGW32__ */

Russell Belfer committed
29
static int
Vicent Marti committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
fs__dotordotdot(WCHAR *_tocheck)
{
	return _tocheck[0] == '.' &&
		(_tocheck[1] == '\0' ||
		 (_tocheck[1] == '.' && _tocheck[2] == '\0'));
}

static int
fs_rmdir_rmdir(WCHAR *_wpath)
{
	unsigned retries = 1;

	while (!RemoveDirectoryW(_wpath)) {
		/* Only retry when we have retries remaining, and the
		 * error was ERROR_DIR_NOT_EMPTY. */
		if (retries++ > RM_RETRY_COUNT ||
			ERROR_DIR_NOT_EMPTY != GetLastError())
			return -1;

		/* Give whatever has a handle to a child item some time
		 * to release it before trying again */
		Sleep(RM_RETRY_DELAY * retries * retries);
	}

	return 0;
}

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
static void translate_path(WCHAR *path, size_t path_size)
{
    size_t path_len, i;

    if (wcsncmp(path, L"\\\\?\\", 4) == 0)
	return;

    path_len = wcslen(path);
    cl_assert(path_size > path_len + 4);

    for (i = path_len; i > 0; i--) {
	WCHAR c = path[i - 1];

	if (c == L'/')
	    path[i + 3] = L'\\';
	else
	    path[i + 3] = path[i - 1];
    }

    path[0] = L'\\';
    path[1] = L'\\';
    path[2] = L'?';
    path[3] = L'\\';
    path[path_len + 4] = L'\0';
}

Vicent Marti committed
83 84 85
static void
fs_rmdir_helper(WCHAR *_wsource)
{
86
	WCHAR buffer[CLAR_MAX_PATH];
Vicent Marti committed
87 88
	HANDLE find_handle;
	WIN32_FIND_DATAW find_data;
89
	size_t buffer_prefix_len;
Vicent Marti committed
90 91

	/* Set up the buffer and capture the length */
92 93 94
	wcscpy_s(buffer, CLAR_MAX_PATH, _wsource);
	translate_path(buffer, CLAR_MAX_PATH);
	wcscat_s(buffer, CLAR_MAX_PATH, L"\\");
Vicent Marti committed
95 96 97
	buffer_prefix_len = wcslen(buffer);

	/* FindFirstFile needs a wildcard to match multiple items */
98
	wcscat_s(buffer, CLAR_MAX_PATH, L"*");
Vicent Marti committed
99 100 101 102 103 104 105 106 107
	find_handle = FindFirstFileW(buffer, &find_data);
	cl_assert(INVALID_HANDLE_VALUE != find_handle);

	do {
		/* FindFirstFile/FindNextFile gives back . and ..
		 * entries at the beginning */
		if (fs__dotordotdot(find_data.cFileName))
			continue;

108
		wcscpy_s(buffer + buffer_prefix_len, CLAR_MAX_PATH - buffer_prefix_len, find_data.cFileName);
Vicent Marti committed
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

		if (FILE_ATTRIBUTE_DIRECTORY & find_data.dwFileAttributes)
			fs_rmdir_helper(buffer);
		else {
			/* If set, the +R bit must be cleared before deleting */
			if (FILE_ATTRIBUTE_READONLY & find_data.dwFileAttributes)
				cl_assert(SetFileAttributesW(buffer, find_data.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY));

			cl_assert(DeleteFileW(buffer));
		}
	}
	while (FindNextFileW(find_handle, &find_data));

	/* Ensure that we successfully completed the enumeration */
	cl_assert(ERROR_NO_MORE_FILES == GetLastError());

	/* Close the find handle */
	FindClose(find_handle);

	/* Now that the directory is empty, remove it */
	cl_assert(0 == fs_rmdir_rmdir(_wsource));
}

static int
fs_rm_wait(WCHAR *_wpath)
{
	unsigned retries = 1;
	DWORD last_error;

	do {
		if (INVALID_FILE_ATTRIBUTES == GetFileAttributesW(_wpath))
			last_error = GetLastError();
		else
			last_error = ERROR_SUCCESS;

		/* Is the item gone? */
		if (ERROR_FILE_NOT_FOUND == last_error ||
			ERROR_PATH_NOT_FOUND == last_error)
			return 0;

		Sleep(RM_RETRY_DELAY * retries * retries);	
	}
	while (retries++ <= RM_RETRY_COUNT);

	return -1;
}

static void
fs_rm(const char *_source)
{
159
	WCHAR wsource[CLAR_MAX_PATH];
Vicent Marti committed
160 161 162 163 164 165 166 167 168
	DWORD attrs;

	/* The input path is UTF-8. Convert it to wide characters
	 * for use with the Windows API */
	cl_assert(MultiByteToWideChar(CP_UTF8,
				MB_ERR_INVALID_CHARS,
				_source,
				-1, /* Indicates NULL termination */
				wsource,
169 170 171
				CLAR_MAX_PATH));

	translate_path(wsource, CLAR_MAX_PATH);
Vicent Marti committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195

	/* Does the item exist? If not, we have no work to do */
	attrs = GetFileAttributesW(wsource);

	if (INVALID_FILE_ATTRIBUTES == attrs)
		return;

	if (FILE_ATTRIBUTE_DIRECTORY & attrs)
		fs_rmdir_helper(wsource);
	else {
		/* The item is a file. Strip the +R bit */
		if (FILE_ATTRIBUTE_READONLY & attrs)
			cl_assert(SetFileAttributesW(wsource, attrs & ~FILE_ATTRIBUTE_READONLY));

		cl_assert(DeleteFileW(wsource));
	}

	/* Wait for the DeleteFile or RemoveDirectory call to complete */
	cl_assert(0 == fs_rm_wait(wsource));
}

static void
fs_copydir_helper(WCHAR *_wsource, WCHAR *_wdest)
{
196
	WCHAR buf_source[CLAR_MAX_PATH], buf_dest[CLAR_MAX_PATH];
Vicent Marti committed
197 198
	HANDLE find_handle;
	WIN32_FIND_DATAW find_data;
199
	size_t buf_source_prefix_len, buf_dest_prefix_len;
Vicent Marti committed
200

201 202 203
	wcscpy_s(buf_source, CLAR_MAX_PATH, _wsource);
	wcscat_s(buf_source, CLAR_MAX_PATH, L"\\");
	translate_path(buf_source, CLAR_MAX_PATH);
Vicent Marti committed
204 205
	buf_source_prefix_len = wcslen(buf_source);

206 207 208
	wcscpy_s(buf_dest, CLAR_MAX_PATH, _wdest);
	wcscat_s(buf_dest, CLAR_MAX_PATH, L"\\");
	translate_path(buf_dest, CLAR_MAX_PATH);
Vicent Marti committed
209 210 211
	buf_dest_prefix_len = wcslen(buf_dest);

	/* Get an enumerator for the items in the source. */
212
	wcscat_s(buf_source, CLAR_MAX_PATH, L"*");
Vicent Marti committed
213 214 215 216 217 218 219 220 221 222 223 224
	find_handle = FindFirstFileW(buf_source, &find_data);
	cl_assert(INVALID_HANDLE_VALUE != find_handle);

	/* Create the target directory. */
	cl_assert(CreateDirectoryW(_wdest, NULL));

	do {
		/* FindFirstFile/FindNextFile gives back . and ..
		 * entries at the beginning */
		if (fs__dotordotdot(find_data.cFileName))
			continue;

225 226
		wcscpy_s(buf_source + buf_source_prefix_len, CLAR_MAX_PATH - buf_source_prefix_len, find_data.cFileName);
		wcscpy_s(buf_dest + buf_dest_prefix_len, CLAR_MAX_PATH - buf_dest_prefix_len, find_data.cFileName);
Vicent Marti committed
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

		if (FILE_ATTRIBUTE_DIRECTORY & find_data.dwFileAttributes)
			fs_copydir_helper(buf_source, buf_dest);
		else
			cl_assert(CopyFileW(buf_source, buf_dest, TRUE));
	}
	while (FindNextFileW(find_handle, &find_data));

	/* Ensure that we successfully completed the enumeration */
	cl_assert(ERROR_NO_MORE_FILES == GetLastError());

	/* Close the find handle */
	FindClose(find_handle);
}

static void
fs_copy(const char *_source, const char *_dest)
{
245
	WCHAR wsource[CLAR_MAX_PATH], wdest[CLAR_MAX_PATH];
Vicent Marti committed
246 247 248
	DWORD source_attrs, dest_attrs;
	HANDLE find_handle;
	WIN32_FIND_DATAW find_data;
Russell Belfer committed
249

Vicent Marti committed
250 251 252 253 254 255 256
	/* The input paths are UTF-8. Convert them to wide characters
	 * for use with the Windows API. */
	cl_assert(MultiByteToWideChar(CP_UTF8,
				MB_ERR_INVALID_CHARS,
				_source,
				-1,
				wsource,
257
				CLAR_MAX_PATH));
Vicent Marti committed
258 259 260 261 262 263

	cl_assert(MultiByteToWideChar(CP_UTF8,
				MB_ERR_INVALID_CHARS,
				_dest,
				-1,
				wdest,
264 265 266 267
				CLAR_MAX_PATH));

	translate_path(wsource, CLAR_MAX_PATH);
	translate_path(wdest, CLAR_MAX_PATH);
Vicent Marti committed
268 269 270 271 272 273 274 275 276 277 278 279 280

	/* Check the source for existence */
	source_attrs = GetFileAttributesW(wsource);
	cl_assert(INVALID_FILE_ATTRIBUTES != source_attrs);

	/* Check the target for existence */
	dest_attrs = GetFileAttributesW(wdest);

	if (INVALID_FILE_ATTRIBUTES != dest_attrs) {
		/* Target exists; append last path part of source to target.
		 * Use FindFirstFile to parse the path */
		find_handle = FindFirstFileW(wsource, &find_data);
		cl_assert(INVALID_HANDLE_VALUE != find_handle);
281 282
		wcscat_s(wdest, CLAR_MAX_PATH, L"\\");
		wcscat_s(wdest, CLAR_MAX_PATH, find_data.cFileName);
Vicent Marti committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
		FindClose(find_handle);

		/* Check the new target for existence */
		cl_assert(INVALID_FILE_ATTRIBUTES == GetFileAttributesW(wdest));
	}

	if (FILE_ATTRIBUTE_DIRECTORY & source_attrs)
		fs_copydir_helper(wsource, wdest);
	else
		cl_assert(CopyFileW(wsource, wdest, TRUE));
}

void
cl_fs_cleanup(void)
{
	fs_rm(fixture_path(_clar_path, "*"));
}

#else
Russell Belfer committed
302 303 304

#include <errno.h>
#include <string.h>
305 306 307 308 309 310 311
#include <limits.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

312 313 314 315
#if defined(__linux__)
# include <sys/sendfile.h>
#endif

Philipp committed
316
#if defined(__APPLE__)
317 318
# include <copyfile.h>
#endif
Russell Belfer committed
319

320 321 322 323 324 325 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
static void basename_r(const char **out, int *out_len, const char *in)
{
	size_t in_len = strlen(in), start_pos;

	for (in_len = strlen(in); in_len; in_len--) {
		if (in[in_len - 1] != '/')
			break;
	}

	for (start_pos = in_len; start_pos; start_pos--) {
		if (in[start_pos - 1] == '/')
			break;
	}

	cl_assert(in_len - start_pos < INT_MAX);

	if (in_len - start_pos > 0) {
		*out = &in[start_pos];
		*out_len = (in_len - start_pos);
	} else {
		*out = "/";
		*out_len = 1;
	}
}

static char *joinpath(const char *dir, const char *base, int base_len)
{
	char *out;
	int len;

	if (base_len == -1) {
		size_t bl = strlen(base);

		cl_assert(bl < INT_MAX);
		base_len = (int)bl;
	}

	len = strlen(dir) + base_len + 2;
	cl_assert(len > 0);

	cl_assert(out = malloc(len));
	cl_assert(snprintf(out, len, "%s/%.*s", dir, base_len, base) < len);

	return out;
}

Vicent Marti committed
366
static void
367
fs_copydir_helper(const char *source, const char *dest, int dest_mode)
Vicent Marti committed
368
{
369 370
	DIR *source_dir;
	struct dirent *d;
Vicent Marti committed
371

372
	mkdir(dest, dest_mode);
Vicent Marti committed
373

374 375 376
	cl_assert_(source_dir = opendir(source), "Could not open source dir");
	while ((d = (errno = 0, readdir(source_dir))) != NULL) {
		char *child;
Vicent Marti committed
377

378 379
		if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
			continue;
Vicent Marti committed
380

381 382 383 384 385 386 387 388 389 390 391
		child = joinpath(source, d->d_name, -1);
		fs_copy(child, dest);
		free(child);
	}

	cl_assert_(errno == 0, "Failed to iterate source dir");

	closedir(source_dir);
}

static void
392
fs_copyfile_helper(const char *source, size_t source_len, const char *dest, int dest_mode)
393 394 395 396
{
	int in, out;

	cl_must_pass((in = open(source, O_RDONLY)));
397
	cl_must_pass((out = open(dest, O_WRONLY|O_CREAT|O_TRUNC, dest_mode)));
398

399
#if USE_FCOPYFILE && defined(__APPLE__)
400
	((void)(source_len)); /* unused */
401
	cl_must_pass(fcopyfile(in, out, 0, COPYFILE_DATA));
402 403 404 405 406 407 408 409 410
#elif USE_SENDFILE && defined(__linux__)
	{
		ssize_t ret = 0;

		while (source_len && (ret = sendfile(out, in, NULL, source_len)) > 0) {
			source_len -= (size_t)ret;
		}
		cl_assert(ret >= 0);
	}
411 412 413 414 415
#else
	{
		char buf[131072];
		ssize_t ret;

416 417
		((void)(source_len)); /* unused */

418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
		while ((ret = read(in, buf, sizeof(buf))) > 0) {
			size_t len = (size_t)ret;

			while (len && (ret = write(out, buf, len)) > 0) {
				cl_assert(ret <= (ssize_t)len);
				len -= ret;
			}
			cl_assert(ret >= 0);
		}
		cl_assert(ret == 0);
	}
#endif

	close(in);
	close(out);
}

static void
fs_copy(const char *source, const char *_dest)
{
	char *dbuf = NULL;
439
	const char *dest = NULL;
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
	struct stat source_st, dest_st;

	cl_must_pass_(lstat(source, &source_st), "Failed to stat copy source");

	if (lstat(_dest, &dest_st) == 0) {
		const char *base;
		int base_len;

		/* Target exists and is directory; append basename */
		cl_assert(S_ISDIR(dest_st.st_mode));

		basename_r(&base, &base_len, source);
		cl_assert(base_len < INT_MAX);

		dbuf = joinpath(_dest, base, base_len);
		dest = dbuf;
	} else if (errno != ENOENT) {
		cl_fail("Cannot copy; cannot stat destination");
	} else {
		dest = _dest;
	}

	if (S_ISDIR(source_st.st_mode)) {
		fs_copydir_helper(source, dest, source_st.st_mode);
	} else {
465
		fs_copyfile_helper(source, source_st.st_size, dest, source_st.st_mode);
466
	}
Vicent Marti committed
467

468
	free(dbuf);
Vicent Marti committed
469 470 471
}

static void
472
fs_rmdir_helper(const char *path)
Vicent Marti committed
473
{
474 475 476 477 478 479
	DIR *dir;
	struct dirent *d;

	cl_assert_(dir = opendir(path), "Could not open dir");
	while ((d = (errno = 0, readdir(dir))) != NULL) {
		char *child;
Vicent Marti committed
480

481 482
		if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
			continue;
Vicent Marti committed
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
		child = joinpath(path, d->d_name, -1);
		fs_rm(child);
		free(child);
	}

	cl_assert_(errno == 0, "Failed to iterate source dir");
	closedir(dir);

	cl_must_pass_(rmdir(path), "Could not remove directory");
}

static void
fs_rm(const char *path)
{
	struct stat st;

	if (lstat(path, &st)) {
		if (errno == ENOENT)
			return;

		cl_fail("Cannot copy; cannot stat destination");
	}

	if (S_ISDIR(st.st_mode)) {
		fs_rmdir_helper(path);
	} else {
		cl_must_pass(unlink(path));
	}
Vicent Marti committed
512 513 514 515 516 517 518 519 520
}

void
cl_fs_cleanup(void)
{
	clar_unsandbox();
	clar_sandbox();
}
#endif