fileops.c 22.2 KB
Newer Older
Vicent Marti committed
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 "common.h"
8
#include "fileops.h"
9
#include "global.h"
10
#include "strmap.h"
11
#include <ctype.h>
12 13 14
#if GIT_WIN32
#include "win32/findfile.h"
#endif
15

16
GIT__USE_STRMAP
17

18
int git_futils_mkpath2file(const char *file_path, const mode_t mode)
19
{
20
	return git_futils_mkdir(
21 22
		file_path, NULL, mode,
		GIT_MKDIR_PATH | GIT_MKDIR_SKIP_LAST | GIT_MKDIR_VERIFY_DIR);
23 24
}

25
int git_futils_mktmp(git_buf *path_out, const char *filename, mode_t mode)
Vicent Marti committed
26 27
{
	int fd;
28 29 30
	mode_t mask;

	p_umask(mask = p_umask(0));
Vicent Marti committed
31

32 33 34 35
	git_buf_sets(path_out, filename);
	git_buf_puts(path_out, "_git2_XXXXXX");

	if (git_buf_oom(path_out))
36
		return -1;
Vicent Marti committed
37

38 39
	if ((fd = p_mkstemp(path_out->ptr)) < 0) {
		giterr_set(GITERR_OS,
40
			"Failed to create temporary file '%s'", path_out->ptr);
41 42
		return -1;
	}
Vicent Marti committed
43

44 45 46 47 48 49
	if (p_chmod(path_out->ptr, (mode & ~mask))) {
		giterr_set(GITERR_OS,
			"Failed to set permissions on file '%s'", path_out->ptr);
		return -1;
	}

50
	return fd;
Vicent Marti committed
51 52
}

53
int git_futils_creat_withpath(const char *path, const mode_t dirmode, const mode_t mode)
54
{
55
	int fd;
56

57 58 59 60 61
	if (git_futils_mkpath2file(path, dirmode) < 0)
		return -1;

	fd = p_creat(path, mode);
	if (fd < 0) {
62
		giterr_set(GITERR_OS, "Failed to create file '%s'", path);
63 64 65 66
		return -1;
	}

	return fd;
67 68
}

69
int git_futils_creat_locked(const char *path, const mode_t mode)
70
{
71
	int fd = p_open(path, O_WRONLY | O_CREAT | O_TRUNC |
72
		O_EXCL | O_BINARY | O_CLOEXEC, mode);
73

74
	if (fd < 0) {
75
		giterr_set(GITERR_OS, "Failed to create locked file '%s'", path);
76
		return errno == EEXIST ? GIT_ELOCKED : -1;
77 78 79
	}

	return fd;
80 81
}

82
int git_futils_creat_locked_withpath(const char *path, const mode_t dirmode, const mode_t mode)
83
{
84 85
	if (git_futils_mkpath2file(path, dirmode) < 0)
		return -1;
86

Vicent Marti committed
87
	return git_futils_creat_locked(path, mode);
88 89
}

90 91 92
int git_futils_open_ro(const char *path)
{
	int fd = p_open(path, O_RDONLY);
93 94
	if (fd < 0)
		return git_path_set_error(errno, path, "open");
95 96 97
	return fd;
}

Vicent Marti committed
98
git_off_t git_futils_filesize(git_file fd)
99
{
100
	struct stat sb;
101 102 103 104 105

	if (p_fstat(fd, &sb)) {
		giterr_set(GITERR_OS, "Failed to stat file descriptor");
		return -1;
	}
106

107 108
	return sb.st_size;
}
109

110 111 112
mode_t git_futils_canonical_mode(mode_t raw_mode)
{
	if (S_ISREG(raw_mode))
113
		return S_IFREG | GIT_PERMS_CANONICAL(raw_mode);
114 115 116 117
	else if (S_ISLNK(raw_mode))
		return S_IFLNK;
	else if (S_ISGITLINK(raw_mode))
		return S_IFGITLINK;
118 119
	else if (S_ISDIR(raw_mode))
		return S_IFDIR;
120 121 122 123
	else
		return 0;
}

124 125
int git_futils_readbuffer_fd(git_buf *buf, git_file fd, size_t len)
{
126
	ssize_t read_size = 0;
127
	size_t alloc_len;
128 129 130

	git_buf_clear(buf);

131 132 133 134 135
	if (!git__is_ssizet(len)) {
		giterr_set(GITERR_INVALID, "Read too large.");
		return -1;
	}

136 137
	GITERR_CHECK_ALLOC_ADD(&alloc_len, len, 1);
	if (git_buf_grow(buf, alloc_len) < 0)
138 139
		return -1;

140 141
	/* p_read loops internally to read len bytes */
	read_size = p_read(fd, buf->ptr, len);
142

Vicent Marti committed
143
	if (read_size != (ssize_t)len) {
144
		giterr_set(GITERR_OS, "Failed to read descriptor");
145
		git_buf_free(buf);
146
		return -1;
147 148
	}

149 150 151
	buf->ptr[read_size] = '\0';
	buf->size = read_size;

152 153 154 155
	return 0;
}

int git_futils_readbuffer_updated(
156
	git_buf *buf, const char *path, time_t *mtime, size_t *size, int *updated)
157 158
{
	git_file fd;
159
	struct stat st;
160
	bool changed = false;
161

162
	assert(buf && path && *path);
163

164 165
	if (updated != NULL)
		*updated = 0;
166

167 168
	if (p_stat(path, &st) < 0)
		return git_path_set_error(errno, path, "stat");
169

170 171 172 173 174 175 176

	if (S_ISDIR(st.st_mode)) {
		giterr_set(GITERR_INVALID, "requested file is a directory");
		return GIT_ENOTFOUND;
	}

	if (!git__is_sizet(st.st_size+1)) {
177 178
		giterr_set(GITERR_OS, "Invalid regular file stat for '%s'", path);
		return -1;
179
	}
180 181

	/*
182 183
	 * If we were given a time and/or a size, we only want to read the file
	 * if it has been modified.
184
	 */
185 186
	if (size && *size != (size_t)st.st_size)
		changed = true;
187
	if (mtime && *mtime != (time_t)st.st_mtime)
188 189 190 191 192
		changed = true;
	if (!size && !mtime)
		changed = true;

	if (!changed) {
193 194
		return 0;
	}
195 196 197

	if (mtime != NULL)
		*mtime = st.st_mtime;
198 199
	if (size != NULL)
		*size = (size_t)st.st_size;
200

201 202 203
	if ((fd = git_futils_open_ro(path)) < 0)
		return fd;

204
	if (git_futils_readbuffer_fd(buf, fd, (size_t)st.st_size) < 0) {
205 206
		p_close(fd);
		return -1;
207 208
	}

Vicent Marti committed
209
	p_close(fd);
210

211 212 213
	if (updated != NULL)
		*updated = 1;

214
	return 0;
215 216
}

217
int git_futils_readbuffer(git_buf *buf, const char *path)
218
{
219
	return git_futils_readbuffer_updated(buf, path, NULL, NULL, NULL);
220 221
}

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
int git_futils_writebuffer(
	const git_buf *buf,	const char *path, int flags, mode_t mode)
{
	int fd, error = 0;

	if (flags <= 0)
		flags = O_CREAT | O_TRUNC | O_WRONLY;
	if (!mode)
		mode = GIT_FILEMODE_BLOB;

	if ((fd = p_open(path, flags, mode)) < 0) {
		giterr_set(GITERR_OS, "Could not open '%s' for writing", path);
		return fd;
	}

	if ((error = p_write(fd, git_buf_cstr(buf), git_buf_len(buf))) < 0) {
		giterr_set(GITERR_OS, "Could not write to '%s'", path);
		(void)p_close(fd);
240
		return error;
241 242 243 244 245 246 247 248
	}

	if ((error = p_close(fd)) < 0)
		giterr_set(GITERR_OS, "Error while closing '%s'", path);

	return error;
}

249
int git_futils_mv_withpath(const char *from, const char *to, const mode_t dirmode)
250
{
251 252
	if (git_futils_mkpath2file(to, dirmode) < 0)
		return -1;
253

254 255 256 257 258 259
	if (p_rename(from, to) < 0) {
		giterr_set(GITERR_OS, "Failed to rename '%s' to '%s'", from, to);
		return -1;
	}

	return 0;
260 261
}

Vicent Marti committed
262
int git_futils_mmap_ro(git_map *out, git_file fd, git_off_t begin, size_t len)
263
{
Vicent Marti committed
264
	return p_mmap(out, len, GIT_PROT_READ, GIT_MAP_SHARED, fd, begin);
265 266
}

267 268
int git_futils_mmap_ro_file(git_map *out, const char *path)
{
269 270
	git_file fd = git_futils_open_ro(path);
	git_off_t len;
271
	int result;
272 273 274 275 276

	if (fd < 0)
		return fd;

	len = git_futils_filesize(fd);
277 278 279 280
	if (!git__is_sizet(len)) {
		giterr_set(GITERR_OS, "File `%s` too large to mmap", path);
		return -1;
	}
281

282
	result = git_futils_mmap_ro(out, fd, 0, (size_t)len);
283 284 285 286
	p_close(fd);
	return result;
}

Vicent Marti committed
287
void git_futils_mmap_free(git_map *out)
288
{
Vicent Marti committed
289
	p_munmap(out);
290 291
}

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
GIT_INLINE(int) validate_existing(
	const char *make_path,
	struct stat *st,
	mode_t mode,
	uint32_t flags,
	struct git_futils_mkdir_perfdata *perfdata)
{
	if ((S_ISREG(st->st_mode) && (flags & GIT_MKDIR_REMOVE_FILES)) ||
		(S_ISLNK(st->st_mode) && (flags & GIT_MKDIR_REMOVE_SYMLINKS))) {
		if (p_unlink(make_path) < 0) {
			giterr_set(GITERR_OS, "Failed to remove %s '%s'",
				S_ISLNK(st->st_mode) ? "symlink" : "file", make_path);
			return GIT_EEXISTS;
		}

		perfdata->mkdir_calls++;

		if (p_mkdir(make_path, mode) < 0) {
			giterr_set(GITERR_OS, "Failed to make directory '%s'", make_path);
			return GIT_EEXISTS;
		}
	}

	else if (S_ISLNK(st->st_mode)) {
		/* Re-stat the target, make sure it's a directory */
		perfdata->stat_calls++;

		if (p_stat(make_path, st) < 0) {
			giterr_set(GITERR_OS, "Failed to make directory '%s'", make_path);
			return GIT_EEXISTS;
		}
	}

	else if (!S_ISDIR(st->st_mode)) {
		giterr_set(GITERR_FILESYSTEM,
			"Failed to make directory '%s': directory exists", make_path);
		return GIT_EEXISTS;
	}

	return 0;
}

334
int git_futils_mkdir_ext(
335 336 337
	const char *path,
	const char *base,
	mode_t mode,
338
	uint32_t flags,
339
	struct git_futils_mkdir_options *opts)
340
{
341
	int error = -1;
342
	git_buf make_path = GIT_BUF_INIT;
343
	ssize_t root = 0, min_root_len, root_len;
344
	char lastch = '/', *tail;
345
	struct stat st;
346

347 348 349
	/* build path and find "root" where we should start calling mkdir */
	if (git_path_join_unrooted(&make_path, path, base, &root) < 0)
		return -1;
350

351 352
	if (make_path.size == 0) {
		giterr_set(GITERR_OS, "Attempt to create empty path");
353
		goto done;
354
	}
355

356 357 358 359 360 361 362 363 364
	/* Trim trailing slashes (except the root) */
	if ((root_len = git_path_root(make_path.ptr)) < 0)
		root_len = 0;
	else
		root_len++;

	while (make_path.size > (size_t)root_len &&
		make_path.ptr[make_path.size - 1] == '/')
		make_path.ptr[--make_path.size] = '\0';
365

366
	/* if we are not supposed to made the last element, truncate it */
367
	if ((flags & GIT_MKDIR_SKIP_LAST2) != 0) {
368
		git_path_dirname_r(&make_path, make_path.ptr);
369 370
		flags |= GIT_MKDIR_SKIP_LAST;
	}
371 372 373
	if ((flags & GIT_MKDIR_SKIP_LAST) != 0) {
		git_path_dirname_r(&make_path, make_path.ptr);
	}
374

375 376 377 378
	/* We were either given the root path (or trimmed it to
	 * the root), we don't have anything to do.
	 */
	if (make_path.size <= (size_t)root_len) {
379 380 381 382
		error = 0;
		goto done;
	}

383 384 385 386
	/* if we are not supposed to make the whole path, reset root */
	if ((flags & GIT_MKDIR_PATH) == 0)
		root = git_buf_rfind(&make_path, '/');

387 388 389 390
	/* advance root past drive name or network mount prefix */
	min_root_len = git_path_root(make_path.ptr);
	if (root < min_root_len)
		root = min_root_len;
yorah committed
391
	while (root >= 0 && make_path.ptr[root] == '/')
392 393
		++root;

394
	/* clip root to make_path length */
395 396
	if (root > (ssize_t)make_path.size)
		root = (ssize_t)make_path.size; /* i.e. NUL byte of string */
397 398
	if (root < 0)
		root = 0;
399

400 401
	/* walk down tail of path making each directory */
	for (tail = &make_path.ptr[root]; *tail; *tail = lastch) {
402
		bool mkdir_attempted = false;
403

404 405 406 407 408 409 410 411 412
		/* advance tail to include next path component */
		while (*tail == '/')
			tail++;
		while (*tail && *tail != '/')
			tail++;

		/* truncate path at next component */
		lastch = *tail;
		*tail = '\0';
413
		st.st_mode = 0;
414

415 416 417
		if (opts->dir_map && git_strmap_exists(opts->dir_map, make_path.ptr))
			continue;

418
		/* See what's going on with this path component */
419
		opts->perfdata.stat_calls++;
420

421
retry_lstat:
422
		if (p_lstat(make_path.ptr, &st) < 0) {
423 424 425
			if (mkdir_attempted || errno != ENOENT) {
				giterr_set(GITERR_OS, "Cannot access component in path '%s'", make_path.ptr);
				error = -1;
426 427 428 429
				goto done;
			}

			giterr_clear();
430 431 432 433 434 435 436 437 438
			opts->perfdata.mkdir_calls++;
			mkdir_attempted = true;
			if (p_mkdir(make_path.ptr, mode) < 0) {
				if (errno == EEXIST)
					goto retry_lstat;
				giterr_set(GITERR_OS, "Failed to make directory '%s'", make_path.ptr);
				error = -1;
				goto done;
			}
439 440 441 442 443 444 445 446
		} else {
			/* with exclusive create, existing dir is an error */
			if ((flags & GIT_MKDIR_EXCL) != 0) {
				giterr_set(GITERR_FILESYSTEM, "Failed to make directory '%s': directory exists", make_path.ptr);
				error = GIT_EEXISTS;
				goto done;
			}

447
			if ((error = validate_existing(
448
				make_path.ptr, &st, mode, flags, &opts->perfdata)) < 0)
449
					goto done;
450
		}
451

452
		/* chmod if requested and necessary */
453 454
		if (((flags & GIT_MKDIR_CHMOD_PATH) != 0 ||
			 (lastch == '\0' && (flags & GIT_MKDIR_CHMOD) != 0)) &&
455 456
			st.st_mode != mode) {

457
			opts->perfdata.chmod_calls++;
458 459 460

			if ((error = p_chmod(make_path.ptr, mode)) < 0 &&
				lastch == '\0') {
461 462
				giterr_set(GITERR_OS, "Failed to set permissions on '%s'",
					make_path.ptr);
463 464
				goto done;
			}
465
		}
466 467

		if (opts->dir_map && opts->pool) {
468 469 470 471 472 473 474
			char *cache_path;
			size_t alloc_size;

			GITERR_CHECK_ALLOC_ADD(&alloc_size, make_path.size, 1);
			if (!git__is_uint32(alloc_size))
				return -1;
			cache_path = git_pool_malloc(opts->pool, (uint32_t)alloc_size);
475 476 477 478 479 480 481 482
			GITERR_CHECK_ALLOC(cache_path);

			memcpy(cache_path, make_path.ptr, make_path.size + 1);

			git_strmap_insert(opts->dir_map, cache_path, cache_path, error);
			if (error < 0)
				goto done;
		}
483
	}
484

485 486 487
	error = 0;

	/* check that full path really is a directory if requested & needed */
488
	if ((flags & GIT_MKDIR_VERIFY_DIR) != 0 &&
489
		lastch != '\0') {
490
		opts->perfdata.stat_calls++;
491 492

		if (p_stat(make_path.ptr, &st) < 0 || !S_ISDIR(st.st_mode)) {
493 494
			giterr_set(GITERR_OS, "Path is not a directory '%s'",
				make_path.ptr);
495 496
			error = GIT_ENOTFOUND;
		}
497
	}
498

499
done:
500
	git_buf_free(&make_path);
501
	return error;
502
}
503

504 505 506 507 508 509
int git_futils_mkdir(
	const char *path,
	const char *base,
	mode_t mode,
	uint32_t flags)
{
510 511
	struct git_futils_mkdir_options options = {0};
	return git_futils_mkdir_ext(path, base, mode, flags, &options);
512 513
}

514 515 516
int git_futils_mkdir_r(const char *path, const char *base, const mode_t mode)
{
	return git_futils_mkdir(path, base, mode, GIT_MKDIR_PATH);
517 518
}

519
typedef struct {
520
	const char *base;
521
	size_t baselen;
522
	uint32_t flags;
523
	int depth;
524 525
} futils__rmdir_data;

526 527
#define FUTILS_MAX_DEPTH 100

528
static int futils__error_cannot_rmdir(const char *path, const char *filemsg)
529
{
530 531 532 533 534
	if (filemsg)
		giterr_set(GITERR_OS, "Could not remove directory. File '%s' %s",
				   path, filemsg);
	else
		giterr_set(GITERR_OS, "Could not remove directory '%s'", path);
535

536 537
	return -1;
}
538

539 540 541 542 543 544 545 546 547 548
static int futils__rm_first_parent(git_buf *path, const char *ceiling)
{
	int error = GIT_ENOTFOUND;
	struct stat st;

	while (error == GIT_ENOTFOUND) {
		git_buf_rtruncate_at_char(path, '/');

		if (!path->size || git__prefixcmp(path->ptr, ceiling) != 0)
			error = 0;
549
		else if (p_lstat_posixly(path->ptr, &st) == 0) {
550 551 552 553 554 555 556 557 558 559 560 561 562 563
			if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))
				error = p_unlink(path->ptr);
			else if (!S_ISDIR(st.st_mode))
				error = -1; /* fail to remove non-regular file */
		} else if (errno != ENOTDIR)
			error = -1;
	}

	if (error)
		futils__error_cannot_rmdir(path->ptr, "cannot remove parent");

	return error;
}

564 565
static int futils__rmdir_recurs_foreach(void *opaque, git_buf *path)
{
566
	int error = 0;
567
	futils__rmdir_data *data = opaque;
568
	struct stat st;
569

570 571 572
	if (data->depth > FUTILS_MAX_DEPTH)
		error = futils__error_cannot_rmdir(
			path->ptr, "directory nesting too deep");
573

574
	else if ((error = p_lstat_posixly(path->ptr, &st)) < 0) {
575
		if (errno == ENOENT)
576
			error = 0;
577 578 579
		else if (errno == ENOTDIR) {
			/* asked to remove a/b/c/d/e and a/b is a normal file */
			if ((data->flags & GIT_RMDIR_REMOVE_BLOCKERS) != 0)
580
				error = futils__rm_first_parent(path, data->base);
581 582 583 584 585
			else
				futils__error_cannot_rmdir(
					path->ptr, "parent is not directory");
		}
		else
586
			error = git_path_set_error(errno, path->ptr, "rmdir");
587 588 589
	}

	else if (S_ISDIR(st.st_mode)) {
590 591
		data->depth++;

592
		error = git_path_direach(path, 0, futils__rmdir_recurs_foreach, data);
593 594 595

		data->depth--;

596
		if (error < 0)
597
			return error;
598

599
		if (data->depth == 0 && (data->flags & GIT_RMDIR_SKIP_ROOT) != 0)
600
			return error;
601

602
		if ((error = p_rmdir(path->ptr)) < 0) {
603
			if ((data->flags & GIT_RMDIR_SKIP_NONEMPTY) != 0 &&
604
				(errno == ENOTEMPTY || errno == EEXIST || errno == EBUSY))
605
				error = 0;
606
			else
607
				error = git_path_set_error(errno, path->ptr, "rmdir");
608
		}
609 610
	}

611
	else if ((data->flags & GIT_RMDIR_REMOVE_FILES) != 0) {
612 613
		if (p_unlink(path->ptr) < 0)
			error = git_path_set_error(errno, path->ptr, "remove");
614 615
	}

616
	else if ((data->flags & GIT_RMDIR_SKIP_NONEMPTY) == 0)
617
		error = futils__error_cannot_rmdir(path->ptr, "still present");
618

619
	return error;
620 621
}

622
static int futils__rmdir_empty_parent(void *opaque, const char *path)
623
{
624
	futils__rmdir_data *data = opaque;
625
	int error = 0;
626

627
	if (strlen(path) <= data->baselen)
628
		error = GIT_ITEROVER;
629

630
	else if (p_rmdir(path) < 0) {
631 632 633
		int en = errno;

		if (en == ENOENT || en == ENOTDIR) {
634
			/* do nothing */
635
		} else if (en == ENOTEMPTY || en == EEXIST || en == EBUSY) {
636 637
			error = GIT_ITEROVER;
		} else {
638
			error = git_path_set_error(errno, path, "rmdir");
639 640 641
		}
	}

642
	return error;
643 644
}

645
int git_futils_rmdir_r(
646
	const char *path, const char *base, uint32_t flags)
647
{
648
	int error;
649
	git_buf fullpath = GIT_BUF_INIT;
650
	futils__rmdir_data data;
651 652 653 654 655

	/* build path and find "root" where we should start calling mkdir */
	if (git_path_join_unrooted(&fullpath, path, base, NULL) < 0)
		return -1;

656
	memset(&data, 0, sizeof(data));
657 658 659
	data.base    = base ? base : "";
	data.baselen = base ? strlen(base) : 0;
	data.flags   = flags;
660 661 662 663

	error = futils__rmdir_recurs_foreach(&data, &fullpath);

	/* remove now-empty parents if requested */
664
	if (!error && (flags & GIT_RMDIR_EMPTY_PARENTS) != 0)
665 666 667
		error = git_path_walk_up(
			&fullpath, base, futils__rmdir_empty_parent, &data);

668 669
	if (error == GIT_ITEROVER) {
		giterr_clear();
670
		error = 0;
671
	}
672 673

	git_buf_free(&fullpath);
674 675

	return error;
676 677
}

678 679 680 681 682 683 684 685 686 687
int git_futils_fake_symlink(const char *old, const char *new)
{
	int retcode = GIT_ERROR;
	int fd = git_futils_creat_withpath(new, 0755, 0644);
	if (fd >= 0) {
		retcode = p_write(fd, old, strlen(old));
		p_close(fd);
	}
	return retcode;
}
688

689
static int cp_by_fd(int ifd, int ofd, bool close_fd_when_done)
690 691
{
	int error = 0;
692
	char buffer[FILEIO_BUFSIZE];
693 694 695 696 697 698 699 700 701 702 703 704 705
	ssize_t len = 0;

	while (!error && (len = p_read(ifd, buffer, sizeof(buffer))) > 0)
		/* p_write() does not have the same semantics as write().  It loops
		 * internally and will return 0 when it has completed writing.
		 */
		error = p_write(ofd, buffer, len);

	if (len < 0) {
		giterr_set(GITERR_OS, "Read error while copying file");
		error = (int)len;
	}

706 707 708
	if (error < 0)
		giterr_set(GITERR_OS, "write error while copying file");

709
	if (close_fd_when_done) {
710 711 712 713 714 715 716
		p_close(ifd);
		p_close(ofd);
	}

	return error;
}

717
int git_futils_cp(const char *from, const char *to, mode_t filemode)
718 719 720 721 722 723 724 725
{
	int ifd, ofd;

	if ((ifd = git_futils_open_ro(from)) < 0)
		return ifd;

	if ((ofd = p_open(to, O_WRONLY | O_CREAT | O_EXCL, filemode)) < 0) {
		p_close(ifd);
726
		return git_path_set_error(errno, to, "open for writing");
727 728
	}

729
	return cp_by_fd(ifd, ofd, true);
730 731
}

732
static int cp_link(const char *from, const char *to, size_t link_size)
733 734 735
{
	int error = 0;
	ssize_t read_len;
736
	char *link_data;
737
	size_t alloc_size;
738

739 740
	GITERR_CHECK_ALLOC_ADD(&alloc_size, link_size, 1);
	link_data = git__malloc(alloc_size);
741 742
	GITERR_CHECK_ALLOC(link_data);

743 744
	read_len = p_readlink(from, link_data, link_size);
	if (read_len != (ssize_t)link_size) {
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
		giterr_set(GITERR_OS, "Failed to read symlink data for '%s'", from);
		error = -1;
	}
	else {
		link_data[read_len] = '\0';

		if (p_symlink(link_data, to) < 0) {
			giterr_set(GITERR_OS, "Could not symlink '%s' as '%s'",
				link_data, to);
			error = -1;
		}
	}

	git__free(link_data);
	return error;
}

typedef struct {
	const char *to_root;
	git_buf to;
	ssize_t from_prefix;
	uint32_t flags;
	uint32_t mkdir_flags;
	mode_t dirmode;
} cp_r_info;

771 772 773 774 775 776 777 778 779 780
#define GIT_CPDIR__MKDIR_DONE_FOR_TO_ROOT (1u << 10)

static int _cp_r_mkdir(cp_r_info *info, git_buf *from)
{
	int error = 0;

	/* create root directory the first time we need to create a directory */
	if ((info->flags & GIT_CPDIR__MKDIR_DONE_FOR_TO_ROOT) == 0) {
		error = git_futils_mkdir(
			info->to_root, NULL, info->dirmode,
781
			(info->flags & GIT_CPDIR_CHMOD_DIRS) ? GIT_MKDIR_CHMOD : 0);
782 783 784 785 786 787 788 789 790 791 792 793 794

		info->flags |= GIT_CPDIR__MKDIR_DONE_FOR_TO_ROOT;
	}

	/* create directory with root as base to prevent excess chmods */
	if (!error)
		error = git_futils_mkdir(
			from->ptr + info->from_prefix, info->to_root,
			info->dirmode, info->mkdir_flags);

	return error;
}

795 796
static int _cp_r_callback(void *ref, git_buf *from)
{
797
	int error = 0;
798 799 800 801 802 803 804 805
	cp_r_info *info = ref;
	struct stat from_st, to_st;
	bool exists = false;

	if ((info->flags & GIT_CPDIR_COPY_DOTFILES) == 0 &&
		from->ptr[git_path_basename_offset(from)] == '.')
		return 0;

806 807
	if ((error = git_buf_joinpath(
			&info->to, info->to_root, from->ptr + info->from_prefix)) < 0)
808
		return error;
809

810
	if (!(error = git_path_lstat(info->to.ptr, &to_st)))
811
		exists = true;
812
	else if (error != GIT_ENOTFOUND)
813
		return error;
814 815 816 817
	else {
		giterr_clear();
		error = 0;
	}
818

819
	if ((error = git_path_lstat(from->ptr, &from_st)) < 0)
820
		return error;
821 822 823 824 825

	if (S_ISDIR(from_st.st_mode)) {
		mode_t oldmode = info->dirmode;

		/* if we are not chmod'ing, then overwrite dirmode */
826
		if ((info->flags & GIT_CPDIR_CHMOD_DIRS) == 0)
827 828 829 830
			info->dirmode = from_st.st_mode;

		/* make directory now if CREATE_EMPTY_DIRS is requested and needed */
		if (!exists && (info->flags & GIT_CPDIR_CREATE_EMPTY_DIRS) != 0)
831
			error = _cp_r_mkdir(info, from);
832 833

		/* recurse onto target directory */
834
		if (!error && (!exists || S_ISDIR(to_st.st_mode)))
835
			error = git_path_direach(from, 0, _cp_r_callback, info);
836 837 838 839

		if (oldmode != 0)
			info->dirmode = oldmode;

840
		return error;
841 842 843 844 845 846 847 848 849
	}

	if (exists) {
		if ((info->flags & GIT_CPDIR_OVERWRITE) == 0)
			return 0;

		if (p_unlink(info->to.ptr) < 0) {
			giterr_set(GITERR_OS, "Cannot overwrite existing file '%s'",
				info->to.ptr);
850
			return GIT_EEXISTS;
851 852 853 854 855 856 857 858 859 860 861
		}
	}

	/* Done if this isn't a regular file or a symlink */
	if (!S_ISREG(from_st.st_mode) &&
		(!S_ISLNK(from_st.st_mode) ||
		 (info->flags & GIT_CPDIR_COPY_SYMLINKS) == 0))
		return 0;

	/* Make container directory on demand if needed */
	if ((info->flags & GIT_CPDIR_CREATE_EMPTY_DIRS) == 0 &&
862
		(error = _cp_r_mkdir(info, from)) < 0)
863
		return error;
864 865

	/* make symlink or regular file */
866
	if (info->flags & GIT_CPDIR_LINK_FILES) {
867 868
		if ((error = p_link(from->ptr, info->to.ptr)) < 0)
			giterr_set(GITERR_OS, "failed to link '%s'", from->ptr);
869
	} else if (S_ISLNK(from_st.st_mode)) {
870
		error = cp_link(from->ptr, info->to.ptr, (size_t)from_st.st_size);
871
	} else {
872 873
		mode_t usemode = from_st.st_mode;

874
		if ((info->flags & GIT_CPDIR_SIMPLE_TO_MODE) != 0)
875
			usemode = GIT_PERMS_FOR_WRITE(usemode);
876 877 878 879

		error = git_futils_cp(from->ptr, info->to.ptr, usemode);
	}

880
	return error;
881 882 883 884 885 886 887 888 889 890 891 892
}

int git_futils_cp_r(
	const char *from,
	const char *to,
	uint32_t flags,
	mode_t dirmode)
{
	int error;
	git_buf path = GIT_BUF_INIT;
	cp_r_info info;

893
	if (git_buf_joinpath(&path, from, "") < 0) /* ensure trailing slash */
894 895
		return -1;

896
	memset(&info, 0, sizeof(info));
897 898 899 900 901 902 903 904
	info.to_root = to;
	info.flags   = flags;
	info.dirmode = dirmode;
	info.from_prefix = path.size;
	git_buf_init(&info.to, 0);

	/* precalculate mkdir flags */
	if ((flags & GIT_CPDIR_CREATE_EMPTY_DIRS) == 0) {
905 906 907
		/* if not creating empty dirs, then use mkdir to create the path on
		 * demand right before files are copied.
		 */
908
		info.mkdir_flags = GIT_MKDIR_PATH | GIT_MKDIR_SKIP_LAST;
909
		if ((flags & GIT_CPDIR_CHMOD_DIRS) != 0)
910 911
			info.mkdir_flags |= GIT_MKDIR_CHMOD_PATH;
	} else {
912
		/* otherwise, we will do simple mkdir as directories are encountered */
913
		info.mkdir_flags =
914
			((flags & GIT_CPDIR_CHMOD_DIRS) != 0) ? GIT_MKDIR_CHMOD : 0;
915 916 917 918 919
	}

	error = _cp_r_callback(&info, &path);

	git_buf_free(&path);
Russell Belfer committed
920
	git_buf_free(&info.to);
921 922 923

	return error;
}
924

Vicent Marti committed
925 926
int git_futils_filestamp_check(
	git_futils_filestamp *stamp, const char *path)
927 928 929
{
	struct stat st;

930 931
	/* if the stamp is NULL, then always reload */
	if (stamp == NULL)
932 933
		return 1;

934
	if (p_stat(path, &st) < 0)
935 936
		return GIT_ENOTFOUND;

937 938 939
	if (stamp->mtime == (git_time_t)st.st_mtime &&
		stamp->size  == (git_off_t)st.st_size   &&
		stamp->ino   == (unsigned int)st.st_ino)
940 941
		return 0;

942 943 944
	stamp->mtime = (git_time_t)st.st_mtime;
	stamp->size  = (git_off_t)st.st_size;
	stamp->ino   = (unsigned int)st.st_ino;
945 946 947 948

	return 1;
}

Vicent Marti committed
949 950
void git_futils_filestamp_set(
	git_futils_filestamp *target, const git_futils_filestamp *source)
951 952 953 954 955 956 957 958
{
	assert(target);

	if (source)
		memcpy(target, source, sizeof(*target));
	else
		memset(target, 0, sizeof(*target));
}
959 960 961 962 963 964 965 966 967 968 969 970 971


void git_futils_filestamp_set_from_stat(
	git_futils_filestamp *stamp, struct stat *st)
{
	if (st) {
		stamp->mtime = (git_time_t)st->st_mtime;
		stamp->size  = (git_off_t)st->st_size;
		stamp->ino   = (unsigned int)st->st_ino;
	} else {
		memset(stamp, 0, sizeof(*stamp));
	}
}