path.c 39 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.
 */
Vicent Marti committed
7
#include "common.h"
8 9
#include "path.h"
#include "posix.h"
10
#include "repository.h"
11
#ifdef GIT_WIN32
12
#include "win32/posix.h"
13
#include "win32/w32_buffer.h"
14
#include "win32/w32_util.h"
15
#include "win32/version.h"
16 17 18
#else
#include <dirent.h>
#endif
Vicent Marti committed
19 20 21
#include <stdio.h>
#include <ctype.h>

22 23
#define LOOKS_LIKE_DRIVE_PREFIX(S) (git__isalpha((S)[0]) && (S)[1] == ':')

24
#ifdef GIT_WIN32
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
static bool looks_like_network_computer_name(const char *path, int pos)
{
	if (pos < 3)
		return false;

	if (path[0] != '/' || path[1] != '/')
		return false;

	while (pos-- > 2) {
		if (path[pos] == '/')
			return false;
	}

	return true;
}
40
#endif
41

Vicent Marti committed
42 43
/*
 * Based on the Android implementation, BSD licensed.
44 45 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
 * http://android.git.kernel.org/
 *
 * Copyright (C) 2008 The Android Open Source Project
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in
 *   the documentation and/or other materials provided with the
 *   distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
Vicent Marti committed
71
 */
72
int git_path_basename_r(git_buf *buffer, const char *path)
Vicent Marti committed
73 74 75 76 77 78
{
	const char *endp, *startp;
	int len, result;

	/* Empty or NULL string gets treated as "." */
	if (path == NULL || *path == '\0') {
Vicent Marti committed
79 80
		startp = ".";
		len		= 1;
Vicent Marti committed
81 82 83 84 85 86 87 88 89 90 91
		goto Exit;
	}

	/* Strip trailing slashes */
	endp = path + strlen(path) - 1;
	while (endp > path && *endp == '/')
		endp--;

	/* All slashes becomes "/" */
	if (endp == path && *endp == '/') {
		startp = "/";
Vicent Marti committed
92
		len	= 1;
Vicent Marti committed
93 94 95 96 97 98 99 100
		goto Exit;
	}

	/* Find the start of the base */
	startp = endp;
	while (startp > path && *(startp - 1) != '/')
		startp--;

101 102
	/* Cast is safe because max path < max int */
	len = (int)(endp - startp + 1);
Vicent Marti committed
103 104 105 106

Exit:
	result = len;

107 108
	if (buffer != NULL && git_buf_set(buffer, startp, len) < 0)
		return -1;
109

Vicent Marti committed
110 111 112 113
	return result;
}

/*
114 115 116 117 118 119 120 121 122 123 124 125 126 127
 * Determine if the path is a Windows prefix and, if so, returns
 * its actual lentgh. If it is not a prefix, returns -1.
 */
static int win32_prefix_length(const char *path, int len)
{
#ifndef GIT_WIN32
	GIT_UNUSED(path);
	GIT_UNUSED(len);
#else
	/*
	 * Mimic unix behavior where '/.git' returns '/': 'C:/.git' will return
	 * 'C:/' here
	 */
	if (len == 2 && LOOKS_LIKE_DRIVE_PREFIX(path))
128
		return 2;
129 130 131 132 133 134

	/*
	 * Similarly checks if we're dealing with a network computer name
	 * '//computername/.git' will return '//computername/'
	 */
	if (looks_like_network_computer_name(path, len))
135
		return len;
136 137 138 139 140 141
#endif

	return -1;
}

/*
Vicent Marti committed
142 143 144
 * Based on the Android implementation, BSD licensed.
 * Check http://android.git.kernel.org/
 */
145
int git_path_dirname_r(git_buf *buffer, const char *path)
Vicent Marti committed
146
{
Vicent Marti committed
147
	const char *endp;
148
	int is_prefix = 0, len;
Vicent Marti committed
149 150 151 152 153 154 155 156 157 158 159 160 161

	/* Empty or NULL string gets treated as "." */
	if (path == NULL || *path == '\0') {
		path = ".";
		len = 1;
		goto Exit;
	}

	/* Strip trailing slashes */
	endp = path + strlen(path) - 1;
	while (endp > path && *endp == '/')
		endp--;

162 163
	if ((len = win32_prefix_length(path, endp - path + 1)) > 0) {
		is_prefix = 1;
164
		goto Exit;
165
	}
166

Vicent Marti committed
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
	/* Find the start of the dir */
	while (endp > path && *endp != '/')
		endp--;

	/* Either the dir is "/" or there are no slashes */
	if (endp == path) {
		path = (*endp == '/') ? "/" : ".";
		len = 1;
		goto Exit;
	}

	do {
		endp--;
	} while (endp > path && *endp == '/');

182 183
	if ((len = win32_prefix_length(path, endp - path + 1)) > 0) {
		is_prefix = 1;
184
		goto Exit;
185
	}
186

187 188
	/* Cast is safe because max path < max int */
	len = (int)(endp - path + 1);
Jerome Lambourg committed
189

Vicent Marti committed
190
Exit:
191 192 193 194 195 196
	if (buffer) {
		if (git_buf_set(buffer, path, len) < 0)
			return -1;
		if (is_prefix && git_buf_putc(buffer, '/') < 0)
			return -1;
	}
Vicent Marti committed
197

198
	return len;
Vicent Marti committed
199 200 201 202 203
}


char *git_path_dirname(const char *path)
{
204 205
	git_buf buf = GIT_BUF_INIT;
	char *dirname;
Vicent Marti committed
206

207 208 209
	git_path_dirname_r(&buf, path);
	dirname = git_buf_detach(&buf);
	git_buf_free(&buf); /* avoid memleak if error occurs */
Vicent Marti committed
210

211
	return dirname;
Vicent Marti committed
212 213 214 215
}

char *git_path_basename(const char *path)
{
216 217
	git_buf buf = GIT_BUF_INIT;
	char *basename;
Vicent Marti committed
218

219 220 221
	git_path_basename_r(&buf, path);
	basename = git_buf_detach(&buf);
	git_buf_free(&buf); /* avoid memleak if error occurs */
Vicent Marti committed
222

223
	return basename;
Vicent Marti committed
224 225
}

226 227 228 229 230 231 232 233 234 235 236 237 238 239
size_t git_path_basename_offset(git_buf *buffer)
{
	ssize_t slash;

	if (!buffer || buffer->size <= 0)
		return 0;

	slash = git_buf_rfind_next(buffer, '/');

	if (slash >= 0 && buffer->ptr[slash] == '/')
		return (size_t)(slash + 1);

	return 0;
}
Vicent Marti committed
240 241 242 243

const char *git_path_topdir(const char *path)
{
	size_t len;
244
	ssize_t i;
Vicent Marti committed
245 246 247 248 249 250 251

	assert(path);
	len = strlen(path);

	if (!len || path[len - 1] != '/')
		return NULL;

252
	for (i = (ssize_t)len - 2; i >= 0; --i)
Vicent Marti committed
253 254 255 256 257 258
		if (path[i] == '/')
			break;

	return &path[i + 1];
}

259 260 261 262 263
int git_path_root(const char *path)
{
	int offset = 0;

	/* Does the root of the path look like a windows drive ? */
264
	if (LOOKS_LIKE_DRIVE_PREFIX(path))
265
		offset += 2;
266

267
#ifdef GIT_WIN32
268
	/* Are we dealing with a windows network path? */
269 270
	else if ((path[0] == '/' && path[1] == '/' && path[2] != '/') ||
		(path[0] == '\\' && path[1] == '\\' && path[2] != '\\'))
271
	{
272
		offset += 2;
273

274
		/* Skip the computer name segment */
275
		while (path[offset] && path[offset] != '/' && path[offset] != '\\')
276 277
			offset++;
	}
278 279
#endif

280
	if (path[offset] == '/' || path[offset] == '\\')
281 282
		return offset;

283
	return -1;	/* Not a real error - signals that path is not rooted */
284 285
}

286 287 288 289 290 291 292 293 294 295 296 297 298 299
void git_path_trim_slashes(git_buf *path)
{
	int ceiling = git_path_root(path->ptr) + 1;
	assert(ceiling >= 0);

	while (path->size > (size_t)ceiling) {
		if (path->ptr[path->size-1] != '/')
			break;

		path->ptr[path->size-1] = '\0';
		path->size--;
	}
}

300 301 302
int git_path_join_unrooted(
	git_buf *path_out, const char *path, const char *base, ssize_t *root_at)
{
303
	ssize_t root;
304 305 306

	assert(path && path_out);

307
	root = (ssize_t)git_path_root(path);
308 309

	if (base != NULL && root < 0) {
310 311
		if (git_buf_joinpath(path_out, base, path) < 0)
			return -1;
312

313 314 315 316
		root = (ssize_t)strlen(base);
	} else {
		if (git_buf_sets(path_out, path) < 0)
			return -1;
317

318 319 320 321
		if (root < 0)
			root = 0;
		else if (base)
			git_path_equal_or_prefixed(base, path, &root);
322 323
	}

324 325 326 327
	if (root_at)
		*root_at = root;

	return 0;
328 329
}

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
void git_path_squash_slashes(git_buf *path)
{
	char *p, *q;

	if (path->size == 0)
		return;

	for (p = path->ptr, q = path->ptr; *q; p++, q++) {
		*p = *q;

		while (*q == '/' && *(q+1) == '/') {
			path->size--;
			q++;
		}
	}

	*p = '\0';
}

349
int git_path_prettify(git_buf *path_out, const char *path, const char *base)
350
{
351
	char buf[GIT_PATH_MAX];
352

353
	assert(path && path_out);
354 355 356

	/* construct path if needed */
	if (base != NULL && git_path_root(path) < 0) {
357 358
		if (git_buf_joinpath(path_out, base, path) < 0)
			return -1;
359 360 361
		path = path_out->ptr;
	}

362
	if (p_realpath(path, buf) == NULL) {
363 364
		/* giterr_set resets the errno when dealing with a GITERR_OS kind of error */
		int error = (errno == ENOENT || errno == ENOTDIR) ? GIT_ENOTFOUND : -1;
365
		giterr_set(GITERR_OS, "failed to resolve path '%s'", path);
366

367
		git_buf_clear(path_out);
368

369
		return error;
370
	}
371

372
	return git_buf_sets(path_out, buf);
373 374
}

375
int git_path_prettify_dir(git_buf *path_out, const char *path, const char *base)
376
{
377
	int error = git_path_prettify(path_out, path, base);
378
	return (error < 0) ? error : git_path_to_dir(path_out);
379
}
380

381 382 383
int git_path_to_dir(git_buf *path)
{
	if (path->asize > 0 &&
nulltoken committed
384 385
		git_buf_len(path) > 0 &&
		path->ptr[git_buf_len(path) - 1] != '/')
386
		git_buf_putc(path, '/');
387

388
	return git_buf_oom(path) ? -1 : 0;
389
}
390 391 392 393 394 395 396 397 398 399 400

void git_path_string_to_dir(char* path, size_t size)
{
	size_t end = strlen(path);

	if (end && path[end - 1] != '/' && end < size) {
		path[end] = '/';
		path[end + 1] = '\0';
	}
}

401 402
int git__percent_decode(git_buf *decoded_out, const char *input)
{
403
	int len, hi, lo, i;
404 405
	assert(decoded_out && input);

406
	len = (int)strlen(input);
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
	git_buf_clear(decoded_out);

	for(i = 0; i < len; i++)
	{
		char c = input[i];

		if (c != '%')
			goto append;

		if (i >= len - 2)
			goto append;

		hi = git__fromhex(input[i + 1]);
		lo = git__fromhex(input[i + 2]);

		if (hi < 0 || lo < 0)
			goto append;

		c = (char)(hi << 4 | lo);
		i += 2;

append:
429 430
		if (git_buf_putc(decoded_out, c) < 0)
			return -1;
431 432
	}

433 434 435 436 437 438 439
	return 0;
}

static int error_invalid_local_file_uri(const char *uri)
{
	giterr_set(GITERR_CONFIG, "'%s' is not a valid local file URI", uri);
	return -1;
440
}
nulltoken committed
441

442
static int local_file_url_prefixlen(const char *file_url)
nulltoken committed
443
{
444
	int len = -1;
nulltoken committed
445

446 447 448 449 450 451
	if (git__prefixcmp(file_url, "file://") == 0) {
		if (file_url[7] == '/')
			len = 8;
		else if (git__prefixcmp(file_url + 7, "localhost/") == 0)
			len = 17;
	}
nulltoken committed
452

453 454
	return len;
}
nulltoken committed
455

456 457 458 459
bool git_path_is_local_file_url(const char *file_url)
{
	return (local_file_url_prefixlen(file_url) > 0);
}
nulltoken committed
460

461 462 463
int git_path_fromurl(git_buf *local_path_out, const char *file_url)
{
	int offset;
nulltoken committed
464

465 466 467 468
	assert(local_path_out && file_url);

	if ((offset = local_file_url_prefixlen(file_url)) < 0 ||
		file_url[offset] == '\0' || file_url[offset] == '/')
469
		return error_invalid_local_file_uri(file_url);
nulltoken committed
470

471
#ifndef GIT_WIN32
nulltoken committed
472 473 474 475
	offset--;	/* A *nix absolute path starts with a forward slash */
#endif

	git_buf_clear(local_path_out);
476
	return git__percent_decode(local_path_out, file_url + offset);
nulltoken committed
477
}
478 479 480 481

int git_path_walk_up(
	git_buf *path,
	const char *ceiling,
482
	int (*cb)(void *data, const char *),
483 484
	void *data)
{
485
	int error = 0;
486 487 488 489 490 491 492
	git_buf iter;
	ssize_t stop = 0, scan;
	char oldc = '\0';

	assert(path && cb);

	if (ceiling != NULL) {
493
		if (git__prefixcmp(path->ptr, ceiling) == 0)
494 495
			stop = (ssize_t)strlen(ceiling);
		else
nulltoken committed
496
			stop = git_buf_len(path);
497
	}
nulltoken committed
498
	scan = git_buf_len(path);
499

500 501 502 503 504 505 506 507
	/* empty path: yield only once */
	if (!scan) {
		error = cb(data, "");
		if (error)
			giterr_set_after_callback(error);
		return error;
	}

508
	iter.ptr = path->ptr;
nulltoken committed
509
	iter.size = git_buf_len(path);
510
	iter.asize = path->asize;
511 512

	while (scan >= stop) {
513
		error = cb(data, iter.ptr);
514
		iter.ptr[scan] = oldc;
515 516

		if (error) {
517
			giterr_set_after_callback(error);
518
			break;
519
		}
520

521 522 523 524 525 526 527 528 529
		scan = git_buf_rfind_next(&iter, '/');
		if (scan >= 0) {
			scan++;
			oldc = iter.ptr[scan];
			iter.size = scan;
			iter.ptr[scan] = '\0';
		}
	}

530 531
	if (scan >= 0)
		iter.ptr[scan] = oldc;
532

533 534 535 536 537 538 539
	/* relative path: yield for the last component */
	if (!error && stop == 0 && iter.ptr[0] != '/') {
		error = cb(data, "");
		if (error)
			giterr_set_after_callback(error);
	}

540 541
	return error;
}
542

543
bool git_path_exists(const char *path)
544 545
{
	assert(path);
546
	return p_access(path, F_OK) == 0;
547 548
}

549
bool git_path_isdir(const char *path)
550 551
{
	struct stat st;
552 553
	if (p_stat(path, &st) < 0)
		return false;
554

555
	return S_ISDIR(st.st_mode) != 0;
556 557
}

558
bool git_path_isfile(const char *path)
559 560 561 562
{
	struct stat st;

	assert(path);
563 564
	if (p_stat(path, &st) < 0)
		return false;
565

566
	return S_ISREG(st.st_mode) != 0;
567 568
}

569 570 571 572 573 574 575 576 577 578 579
bool git_path_islink(const char *path)
{
	struct stat st;

	assert(path);
	if (p_lstat(path, &st) < 0)
		return false;

	return S_ISLNK(st.st_mode) != 0;
}

Ben Straub committed
580 581 582 583
#ifdef GIT_WIN32

bool git_path_is_empty_dir(const char *path)
{
584 585 586 587 588 589 590
	git_win32_path filter_w;
	bool empty = false;

	if (git_win32__findfirstfile_filter(filter_w, path)) {
		WIN32_FIND_DATAW findData;
		HANDLE hFind = FindFirstFileW(filter_w, &findData);

591 592 593 594 595 596 597 598 599 600 601 602
		/* FindFirstFile will fail if there are no children to the given
		 * path, which can happen if the given path is a file (and obviously
		 * has no children) or if the given path is an empty mount point.
		 * (Most directories have at least directory entries '.' and '..',
		 * but ridiculously another volume mounted in another drive letter's
		 * path space do not, and thus have nothing to enumerate.)  If
		 * FindFirstFile fails, check if this is a directory-like thing
		 * (a mount point).
		 */
		if (hFind == INVALID_HANDLE_VALUE)
			return git_path_isdir(path);

603
		/* If the find handle was created successfully, then it's a directory */
604 605 606 607 608 609 610 611 612 613 614 615 616 617
		empty = true;

		do {
			/* Allow the enumeration to return . and .. and still be considered
			 * empty. In the special case of drive roots (i.e. C:\) where . and
			 * .. do not occur, we can still consider the path to be an empty
			 * directory if there's nothing there. */
			if (!git_path_is_dot_or_dotdotW(findData.cFileName)) {
				empty = false;
				break;
			}
		} while (FindNextFileW(hFind, &findData));

		FindClose(hFind);
618
	}
619

620
	return empty;
Ben Straub committed
621 622 623 624
}

#else

625
static int path_found_entry(void *payload, git_buf *path)
Ben Straub committed
626
{
627 628 629
	GIT_UNUSED(payload);
	return !git_path_is_dot_or_dotdot(path->ptr);
}
Ben Straub committed
630

631 632 633 634
bool git_path_is_empty_dir(const char *path)
{
	int error;
	git_buf dir = GIT_BUF_INIT;
Ben Straub committed
635

636
	if (!git_path_isdir(path))
Ben Straub committed
637 638
		return false;

639 640 641
	if ((error = git_buf_sets(&dir, path)) != 0)
		giterr_clear();
	else
642
		error = git_path_direach(&dir, 0, path_found_entry, NULL);
Ben Straub committed
643

644 645 646
	git_buf_free(&dir);

	return !error;
Ben Straub committed
647
}
648

Ben Straub committed
649 650
#endif

651
int git_path_set_error(int errno_value, const char *path, const char *action)
652
{
653 654 655
	switch (errno_value) {
	case ENOENT:
	case ENOTDIR:
656
		giterr_set(GITERR_OS, "could not find '%s' to %s", path, action);
657 658 659 660
		return GIT_ENOTFOUND;

	case EINVAL:
	case ENAMETOOLONG:
661
		giterr_set(GITERR_OS, "invalid path for filesystem '%s'", path);
662 663 664
		return GIT_EINVALIDSPEC;

	case EEXIST:
665
		giterr_set(GITERR_OS, "failed %s - '%s' already exists", action, path);
666
		return GIT_EEXISTS;
667

668
	case EACCES:
669
		giterr_set(GITERR_OS, "failed %s - '%s' is locked", action, path);
670 671
		return GIT_ELOCKED;

672
	default:
673
		giterr_set(GITERR_OS, "could not %s '%s'", action, path);
674
		return -1;
675
	}
676 677 678 679 680 681
}

int git_path_lstat(const char *path, struct stat *st)
{
	if (p_lstat(path, st) == 0)
		return 0;
682

683
	return git_path_set_error(errno, path, "stat");
684 685
}

686
static bool _check_dir_contents(
687 688
	git_buf *dir,
	const char *sub,
689
	bool (*predicate)(const char *))
690
{
691
	bool result;
nulltoken committed
692
	size_t dir_size = git_buf_len(dir);
693
	size_t sub_size = strlen(sub);
694
	size_t alloc_size;
695

696
	/* leave base valid even if we could not make space for subdir */
697 698
	if (GIT_ADD_SIZET_OVERFLOW(&alloc_size, dir_size, sub_size) ||
		GIT_ADD_SIZET_OVERFLOW(&alloc_size, alloc_size, 2) ||
699
		git_buf_try_grow(dir, alloc_size, false) < 0)
700 701 702
		return false;

	/* save excursion */
703 704
	if (git_buf_joinpath(dir, dir->ptr, sub) < 0)
		return false;
705

706
	result = predicate(dir->ptr);
707

708 709
	/* restore path */
	git_buf_truncate(dir, dir_size);
710
	return result;
711 712
}

713
bool git_path_contains(git_buf *dir, const char *item)
714
{
715
	return _check_dir_contents(dir, item, &git_path_exists);
716 717
}

718
bool git_path_contains_dir(git_buf *base, const char *subdir)
719
{
720
	return _check_dir_contents(base, subdir, &git_path_isdir);
721 722
}

723
bool git_path_contains_file(git_buf *base, const char *file)
724
{
725
	return _check_dir_contents(base, file, &git_path_isfile);
726 727 728 729
}

int git_path_find_dir(git_buf *dir, const char *path, const char *base)
{
730
	int error = git_path_join_unrooted(dir, path, base, NULL);
731

732
	if (!error) {
733 734 735 736 737 738
		char buf[GIT_PATH_MAX];
		if (p_realpath(dir->ptr, buf) != NULL)
			error = git_buf_sets(dir, buf);
	}

	/* call dirname if this is not a directory */
739
	if (!error) /* && git_path_isdir(dir->ptr) == false) */
740
		error = (git_path_dirname_r(dir, dir->ptr) < 0) ? -1 : 0;
741

742
	if (!error)
743 744 745 746 747
		error = git_path_to_dir(dir);

	return error;
}

748 749 750 751 752
int git_path_resolve_relative(git_buf *path, size_t ceiling)
{
	char *base, *to, *from, *next;
	size_t len;

753
	GITERR_CHECK_ALLOC_BUF(path);
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779

	if (ceiling > path->size)
		ceiling = path->size;

	/* recognize drive prefixes, etc. that should not be backed over */
	if (ceiling == 0)
		ceiling = git_path_root(path->ptr) + 1;

	/* recognize URL prefixes that should not be backed over */
	if (ceiling == 0) {
		for (next = path->ptr; *next && git__isalpha(*next); ++next);
		if (next[0] == ':' && next[1] == '/' && next[2] == '/')
			ceiling = (next + 3) - path->ptr;
	}

	base = to = from = path->ptr + ceiling;

	while (*from) {
		for (next = from; *next && *next != '/'; ++next);

		len = next - from;

		if (len == 1 && from[0] == '.')
			/* do nothing with singleton dot */;

		else if (len == 2 && from[0] == '.' && from[1] == '.') {
780 781 782
			/* error out if trying to up one from a hard base */
			if (to == base && ceiling != 0) {
				giterr_set(GITERR_INVALID,
783
					"cannot strip root component off url");
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
				return -1;
			}

			/* no more path segments to strip,
			 * use '../' as a new base path */
			if (to == base) {
				if (*next == '/')
					len++;

				if (to != from)
					memmove(to, from, len);

				to += len;
				/* this is now the base, can't back up from a
				 * relative prefix */
				base = to;
			} else {
				/* back up a path segment */
				while (to > base && to[-1] == '/') to--;
				while (to > base && to[-1] != '/') to--;
			}
		} else {
			if (*next == '/' && *from != '/')
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
				len++;

			if (to != from)
				memmove(to, from, len);

			to += len;
		}

		from += len;

		while (*from == '/') from++;
	}

	*to = '\0';

	path->size = to - path->ptr;

	return 0;
}

int git_path_apply_relative(git_buf *target, const char *relpath)
{
829 830
	return git_buf_joinpath(target, git_buf_cstr(target), relpath) ||
	    git_path_resolve_relative(target, 0);
831 832
}

833 834
int git_path_cmp(
	const char *name1, size_t len1, int isdir1,
835 836
	const char *name2, size_t len2, int isdir2,
	int (*compare)(const char *, const char *, size_t))
837
{
838
	unsigned char c1, c2;
839
	size_t len = len1 < len2 ? len1 : len2;
840 841
	int cmp;

842
	cmp = compare(name1, name2, len);
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
	if (cmp)
		return cmp;

	c1 = name1[len];
	c2 = name2[len];

	if (c1 == '\0' && isdir1)
		c1 = '/';

	if (c2 == '\0' && isdir2)
		c2 = '/';

	return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
}

858 859 860 861 862 863 864 865 866 867 868 869 870 871
size_t git_path_common_dirlen(const char *one, const char *two)
{
	const char *p, *q, *dirsep = NULL;

	for (p = one, q = two; *p && *q; p++, q++) {
		if (*p == '/' && *q == '/')
			dirsep = p;
		else if (*p != *q)
			break;
	}

	return dirsep ? (dirsep - one) + 1 : 0;
}

872 873 874
int git_path_make_relative(git_buf *path, const char *parent)
{
	const char *p, *q, *p_dirsep, *q_dirsep;
875
	size_t plen = path->size, newlen, alloclen, depth = 1, i, offset;
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912

	for (p_dirsep = p = path->ptr, q_dirsep = q = parent; *p && *q; p++, q++) {
		if (*p == '/' && *q == '/') {
			p_dirsep = p;
			q_dirsep = q;
		}
		else if (*p != *q)
			break;
	}

	/* need at least 1 common path segment */
	if ((p_dirsep == path->ptr || q_dirsep == parent) &&
		(*p_dirsep != '/' || *q_dirsep != '/')) {
		giterr_set(GITERR_INVALID,
			"%s is not a parent of %s", parent, path->ptr);
		return GIT_ENOTFOUND;
	}

	if (*p == '/' && !*q)
		p++;
	else if (!*p && *q == '/')
		q++;
	else if (!*p && !*q)
		return git_buf_clear(path), 0;
	else {
		p = p_dirsep + 1;
		q = q_dirsep + 1;
	}

	plen -= (p - path->ptr);

	if (!*q)
		return git_buf_set(path, p, plen);

	for (; (q = strchr(q, '/')) && *(q + 1); q++)
		depth++;

913 914 915 916
	GITERR_CHECK_ALLOC_MULTIPLY(&newlen, depth, 3);
	GITERR_CHECK_ALLOC_ADD(&newlen, newlen, plen);

	GITERR_CHECK_ALLOC_ADD(&alloclen, newlen, 1);
917

Erdur committed
918 919
	/* save the offset as we might realllocate the pointer */
	offset = p - path->ptr;
920
	if (git_buf_try_grow(path, alloclen, 1) < 0)
921
		return -1;
Erdur committed
922
	p = path->ptr + offset;
923 924 925 926 927 928 929 930 931 932

	memmove(path->ptr + (depth * 3), p, plen + 1);

	for (i = 0; i < depth; i++)
		memcpy(path->ptr + (i * 3), "../", 3);

	path->size = newlen;
	return 0;
}

933
bool git_path_has_non_ascii(const char *path, size_t pathlen)
934 935 936 937 938 939 940 941 942 943
{
	const uint8_t *scan = (const uint8_t *)path, *end;

	for (end = scan + pathlen; scan < end; ++scan)
		if (*scan & 0x80)
			return true;

	return false;
}

944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
#ifdef GIT_USE_ICONV

int git_path_iconv_init_precompose(git_path_iconv_t *ic)
{
	git_buf_init(&ic->buf, 0);
	ic->map = iconv_open(GIT_PATH_REPO_ENCODING, GIT_PATH_NATIVE_ENCODING);
	return 0;
}

void git_path_iconv_clear(git_path_iconv_t *ic)
{
	if (ic) {
		if (ic->map != (iconv_t)-1)
			iconv_close(ic->map);
		git_buf_free(&ic->buf);
	}
}

962
int git_path_iconv(git_path_iconv_t *ic, const char **in, size_t *inlen)
963
{
964
	char *nfd = (char*)*in, *nfc;
965
	size_t nfdlen = *inlen, nfclen, wantlen = nfdlen, alloclen, rv;
966 967
	int retry = 1;

968 969
	if (!ic || ic->map == (iconv_t)-1 ||
		!git_path_has_non_ascii(*in, *inlen))
970 971
		return 0;

Russell Belfer committed
972
	git_buf_clear(&ic->buf);
973

974
	while (1) {
975 976
		GITERR_CHECK_ALLOC_ADD(&alloclen, wantlen, 1);
		if (git_buf_grow(&ic->buf, alloclen) < 0)
977 978
			return -1;

979 980
		nfc    = ic->buf.ptr   + ic->buf.size;
		nfclen = ic->buf.asize - ic->buf.size;
981

982
		rv = iconv(ic->map, &nfd, &nfdlen, &nfc, &nfclen);
983

984
		ic->buf.size = (nfc - ic->buf.ptr);
985 986 987 988

		if (rv != (size_t)-1)
			break;

989 990 991
		/* if we cannot convert the data (probably because iconv thinks
		 * it is not valid UTF-8 source data), then use original data
		 */
992
		if (errno != E2BIG)
993
			return 0;
994 995 996 997

		/* make space for 2x the remaining data to be converted
		 * (with per retry overhead to avoid infinite loops)
		 */
998
		wantlen = ic->buf.size + max(nfclen, nfdlen) * 2 + (size_t)(retry * 4);
999 1000

		if (retry++ > 4)
1001
			goto fail;
1002 1003
	}

1004
	ic->buf.ptr[ic->buf.size] = '\0';
1005

1006 1007
	*in    = ic->buf.ptr;
	*inlen = ic->buf.size;
1008 1009

	return 0;
1010 1011

fail:
1012
	giterr_set(GITERR_OS, "unable to convert unicode path data");
1013
	return -1;
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 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
static const char *nfc_file = "\xC3\x85\x73\x74\x72\xC3\xB6\x6D.XXXXXX";
static const char *nfd_file = "\x41\xCC\x8A\x73\x74\x72\x6F\xCC\x88\x6D.XXXXXX";

/* Check if the platform is decomposing unicode data for us.  We will
 * emulate core Git and prefer to use precomposed unicode data internally
 * on these platforms, composing the decomposed unicode on the fly.
 *
 * This mainly happens on the Mac where HDFS stores filenames as
 * decomposed unicode.  Even on VFAT and SAMBA file systems, the Mac will
 * return decomposed unicode from readdir() even when the actual
 * filesystem is storing precomposed unicode.
 */
bool git_path_does_fs_decompose_unicode(const char *root)
{
	git_buf path = GIT_BUF_INIT;
	int fd;
	bool found_decomposed = false;
	char tmp[6];

	/* Create a file using a precomposed path and then try to find it
	 * using the decomposed name.  If the lookup fails, then we will mark
	 * that we should precompose unicode for this repository.
	 */
	if (git_buf_joinpath(&path, root, nfc_file) < 0 ||
		(fd = p_mkstemp(path.ptr)) < 0)
		goto done;
	p_close(fd);

	/* record trailing digits generated by mkstemp */
	memcpy(tmp, path.ptr + path.size - sizeof(tmp), sizeof(tmp));

	/* try to look up as NFD path */
	if (git_buf_joinpath(&path, root, nfd_file) < 0)
		goto done;
	memcpy(path.ptr + path.size - sizeof(tmp), tmp, sizeof(tmp));

	found_decomposed = git_path_exists(path.ptr);

	/* remove temporary file (using original precomposed path) */
	if (git_buf_joinpath(&path, root, nfc_file) < 0)
		goto done;
	memcpy(path.ptr + path.size - sizeof(tmp), tmp, sizeof(tmp));

	(void)p_unlink(path.ptr);

done:
	git_buf_free(&path);
	return found_decomposed;
}

#else

bool git_path_does_fs_decompose_unicode(const char *root)
{
	GIT_UNUSED(root);
	return false;
}

1074 1075 1076 1077 1078 1079 1080 1081
#endif

#if defined(__sun) || defined(__GNU__)
typedef char path_dirent_data[sizeof(struct dirent) + FILENAME_MAX + 1];
#else
typedef struct dirent path_dirent_data;
#endif

1082 1083
int git_path_direach(
	git_buf *path,
1084
	uint32_t flags,
1085 1086 1087
	int (*fn)(void *, git_buf *),
	void *arg)
{
1088
	int error = 0;
1089 1090
	ssize_t wd_len;
	DIR *dir;
1091
	struct dirent *de;
1092 1093

#ifdef GIT_USE_ICONV
1094
	git_path_iconv_t ic = GIT_PATH_ICONV_INIT;
1095
#endif
1096

1097 1098
	GIT_UNUSED(flags);

1099
	if (git_path_to_dir(path) < 0)
1100
		return -1;
1101

nulltoken committed
1102
	wd_len = git_buf_len(path);
1103

1104
	if ((dir = opendir(path->ptr)) == NULL) {
1105
		giterr_set(GITERR_OS, "failed to open directory '%s'", path->ptr);
1106 1107 1108
		if (errno == ENOENT)
			return GIT_ENOTFOUND;

1109 1110
		return -1;
	}
1111

1112
#ifdef GIT_USE_ICONV
1113
	if ((flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
1114
		(void)git_path_iconv_init_precompose(&ic);
1115
#endif
1116

1117
	while ((de = readdir(dir)) != NULL) {
1118
		const char *de_path = de->d_name;
1119
		size_t de_len = strlen(de_path);
1120

1121
		if (git_path_is_dot_or_dotdot(de_path))
1122 1123
			continue;

1124 1125 1126 1127
#ifdef GIT_USE_ICONV
		if ((error = git_path_iconv(&ic, &de_path, &de_len)) < 0)
			break;
#endif
1128

1129
		if ((error = git_buf_put(path, de_path, de_len)) < 0)
1130 1131
			break;

1132
		giterr_clear();
1133
		error = fn(arg, path);
1134 1135 1136

		git_buf_truncate(path, wd_len); /* restore path */

1137
		/* Only set our own error if the callback did not set one already */
1138 1139 1140 1141
		if (error != 0) {
			if (!giterr_last())
				giterr_set_after_callback(error);

1142
			break;
1143
		}
1144 1145 1146
	}

	closedir(dir);
1147 1148

#ifdef GIT_USE_ICONV
1149
	git_path_iconv_clear(&ic);
1150
#endif
1151 1152

	return error;
1153
}
1154

1155 1156 1157
#if defined(GIT_WIN32) && !defined(__MINGW32__)

/* Using _FIND_FIRST_EX_LARGE_FETCH may increase performance in Windows 7
1158
 * and better.
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
 */
#ifndef FIND_FIRST_EX_LARGE_FETCH
# define FIND_FIRST_EX_LARGE_FETCH 2
#endif

int git_path_diriter_init(
	git_path_diriter *diriter,
	const char *path,
	unsigned int flags)
{
	git_win32_path path_filter;

1171 1172 1173 1174
	static int is_win7_or_later = -1;
	if (is_win7_or_later < 0)
		is_win7_or_later = git_has_win32_version(6, 1, 0);

1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
	assert(diriter && path);

	memset(diriter, 0, sizeof(git_path_diriter));
	diriter->handle = INVALID_HANDLE_VALUE;

	if (git_buf_puts(&diriter->path_utf8, path) < 0)
		return -1;

	git_path_trim_slashes(&diriter->path_utf8);

	if (diriter->path_utf8.size == 0) {
1186
		giterr_set(GITERR_FILESYSTEM, "could not open directory '%s'", path);
1187 1188 1189 1190 1191
		return -1;
	}

	if ((diriter->parent_len = git_win32_path_from_utf8(diriter->path, diriter->path_utf8.ptr)) < 0 ||
			!git_win32__findfirstfile_filter(path_filter, diriter->path_utf8.ptr)) {
1192
		giterr_set(GITERR_OS, "could not parse the directory path '%s'", path);
1193 1194 1195 1196 1197
		return -1;
	}

	diriter->handle = FindFirstFileExW(
		path_filter,
1198
		is_win7_or_later ? FindExInfoBasic : FindExInfoStandard,
1199 1200 1201
		&diriter->current,
		FindExSearchNameMatch,
		NULL,
1202
		is_win7_or_later ? FIND_FIRST_EX_LARGE_FETCH : 0);
1203 1204

	if (diriter->handle == INVALID_HANDLE_VALUE) {
1205
		giterr_set(GITERR_OS, "could not open directory '%s'", path);
1206 1207 1208 1209 1210 1211 1212 1213
		return -1;
	}

	diriter->parent_utf8_len = diriter->path_utf8.size;
	diriter->flags = flags;
	return 0;
}

1214
static int diriter_update_paths(git_path_diriter *diriter)
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
{
	size_t filename_len, path_len;

	filename_len = wcslen(diriter->current.cFileName);

	if (GIT_ADD_SIZET_OVERFLOW(&path_len, diriter->parent_len, filename_len) ||
		GIT_ADD_SIZET_OVERFLOW(&path_len, path_len, 2))
		return -1;

	if (path_len > GIT_WIN_PATH_UTF16) {
		giterr_set(GITERR_FILESYSTEM,
			"invalid path '%.*ls\\%ls' (path too long)",
			diriter->parent_len, diriter->path, diriter->current.cFileName);
		return -1;
	}

	diriter->path[diriter->parent_len] = L'\\';
	memcpy(&diriter->path[diriter->parent_len+1],
		diriter->current.cFileName, filename_len * sizeof(wchar_t));
	diriter->path[path_len-1] = L'\0';

	git_buf_truncate(&diriter->path_utf8, diriter->parent_utf8_len);
1237 1238 1239 1240 1241

	if (diriter->parent_utf8_len > 0 &&
		diriter->path_utf8.ptr[diriter->parent_utf8_len-1] != '/')
		git_buf_putc(&diriter->path_utf8, '/');

1242
	git_buf_put_w(&diriter->path_utf8, diriter->current.cFileName, filename_len);
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263

	if (git_buf_oom(&diriter->path_utf8))
		return -1;

	return 0;
}

int git_path_diriter_next(git_path_diriter *diriter)
{
	bool skip_dot = !(diriter->flags & GIT_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);

	do {
		/* Our first time through, we already have the data from
		 * FindFirstFileW.  Use it, otherwise get the next file.
		 */
		if (!diriter->needs_next)
			diriter->needs_next = 1;
		else if (!FindNextFileW(diriter->handle, &diriter->current))
			return GIT_ITEROVER;
	} while (skip_dot && git_path_is_dot_or_dotdotW(diriter->current.cFileName));

1264
	if (diriter_update_paths(diriter) < 0)
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
		return -1;

	return 0;
}

int git_path_diriter_filename(
	const char **out,
	size_t *out_len,
	git_path_diriter *diriter)
{
	assert(out && out_len && diriter);

	assert(diriter->path_utf8.size > diriter->parent_utf8_len);

	*out = &diriter->path_utf8.ptr[diriter->parent_utf8_len+1];
	*out_len = diriter->path_utf8.size - diriter->parent_utf8_len - 1;
	return 0;
}

int git_path_diriter_fullpath(
	const char **out,
	size_t *out_len,
	git_path_diriter *diriter)
{
	assert(out && out_len && diriter);

	*out = diriter->path_utf8.ptr;
	*out_len = diriter->path_utf8.size;
	return 0;
}

int git_path_diriter_stat(struct stat *out, git_path_diriter *diriter)
{
	assert(out && diriter);

	return git_win32__file_attribute_to_stat(out,
		(WIN32_FILE_ATTRIBUTE_DATA *)&diriter->current,
		diriter->path);
}

void git_path_diriter_free(git_path_diriter *diriter)
{
	if (diriter == NULL)
		return;

1310 1311
	git_buf_free(&diriter->path_utf8);

1312 1313 1314 1315 1316 1317 1318 1319
	if (diriter->handle != INVALID_HANDLE_VALUE) {
		FindClose(diriter->handle);
		diriter->handle = INVALID_HANDLE_VALUE;
	}
}

#else

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
int git_path_diriter_init(
	git_path_diriter *diriter,
	const char *path,
	unsigned int flags)
{
	assert(diriter && path);

	memset(diriter, 0, sizeof(git_path_diriter));

	if (git_buf_puts(&diriter->path, path) < 0)
		return -1;

	git_path_trim_slashes(&diriter->path);

1334
	if (diriter->path.size == 0) {
1335
		giterr_set(GITERR_FILESYSTEM, "could not open directory '%s'", path);
1336 1337 1338
		return -1;
	}

1339 1340 1341
	if ((diriter->dir = opendir(diriter->path.ptr)) == NULL) {
		git_buf_free(&diriter->path);

1342
		giterr_set(GITERR_OS, "failed to open directory '%s'", path);
1343 1344 1345 1346 1347
		return -1;
	}

#ifdef GIT_USE_ICONV
	if ((flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
1348
		(void)git_path_iconv_init_precompose(&diriter->ic);
1349 1350 1351 1352 1353 1354 1355 1356
#endif

	diriter->parent_len = diriter->path.size;
	diriter->flags = flags;

	return 0;
}

1357
int git_path_diriter_next(git_path_diriter *diriter)
1358 1359 1360 1361 1362 1363 1364
{
	struct dirent *de;
	const char *filename;
	size_t filename_len;
	bool skip_dot = !(diriter->flags & GIT_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
	int error = 0;

1365
	assert(diriter);
1366 1367 1368 1369 1370 1371 1372 1373 1374

	errno = 0;

	do {
		if ((de = readdir(diriter->dir)) == NULL) {
			if (!errno)
				return GIT_ITEROVER;

			giterr_set(GITERR_OS,
1375
				"could not read directory '%s'", diriter->path.ptr);
1376 1377 1378 1379 1380 1381 1382 1383
			return -1;
		}
	} while (skip_dot && git_path_is_dot_or_dotdot(de->d_name));

	filename = de->d_name;
	filename_len = strlen(filename);

#ifdef GIT_USE_ICONV
1384
	if ((diriter->flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0 &&
1385
		(error = git_path_iconv(&diriter->ic, &filename, &filename_len)) < 0)
1386 1387 1388 1389
		return error;
#endif

	git_buf_truncate(&diriter->path, diriter->parent_len);
1390 1391 1392 1393 1394

	if (diriter->parent_len > 0 &&
		diriter->path.ptr[diriter->parent_len-1] != '/')
		git_buf_putc(&diriter->path, '/');

1395 1396 1397 1398 1399 1400 1401 1402
	git_buf_put(&diriter->path, filename, filename_len);

	if (git_buf_oom(&diriter->path))
		return -1;

	return error;
}

1403 1404 1405 1406 1407 1408 1409
int git_path_diriter_filename(
	const char **out,
	size_t *out_len,
	git_path_diriter *diriter)
{
	assert(out && out_len && diriter);

1410 1411
	assert(diriter->path.size > diriter->parent_len);

1412 1413 1414 1415 1416
	*out = &diriter->path.ptr[diriter->parent_len+1];
	*out_len = diriter->path.size - diriter->parent_len - 1;
	return 0;
}

1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
int git_path_diriter_fullpath(
	const char **out,
	size_t *out_len,
	git_path_diriter *diriter)
{
	assert(out && out_len && diriter);

	*out = diriter->path.ptr;
	*out_len = diriter->path.size;
	return 0;
}

int git_path_diriter_stat(struct stat *out, git_path_diriter *diriter)
{
	assert(out && diriter);

	return git_path_lstat(diriter->path.ptr, out);
}

void git_path_diriter_free(git_path_diriter *diriter)
{
	if (diriter == NULL)
		return;

1441 1442 1443 1444
	if (diriter->dir) {
		closedir(diriter->dir);
		diriter->dir = NULL;
	}
1445 1446 1447 1448 1449 1450 1451 1452

#ifdef GIT_USE_ICONV
	git_path_iconv_clear(&diriter->ic);
#endif

	git_buf_free(&diriter->path);
}

1453 1454
#endif

1455 1456 1457 1458
int git_path_dirload(
	git_vector *contents,
	const char *path,
	size_t prefix_len,
1459
	uint32_t flags)
1460
{
1461
	git_path_diriter iter = GIT_PATH_DIRITER_INIT;
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
	const char *name;
	size_t name_len;
	char *dup;
	int error;

	assert(contents && path);

	if ((error = git_path_diriter_init(&iter, path, flags)) < 0)
		return error;

1472
	while ((error = git_path_diriter_next(&iter)) == 0) {
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
		if ((error = git_path_diriter_fullpath(&name, &name_len, &iter)) < 0)
			break;

		assert(name_len > prefix_len);

		dup = git__strndup(name + prefix_len, name_len - prefix_len);
		GITERR_CHECK_ALLOC(dup);

		if ((error = git_vector_insert(contents, dup)) < 0)
			break;
	}

	if (error == GIT_ITEROVER)
		error = 0;

	git_path_diriter_free(&iter);
	return error;
}

1492 1493
int git_path_from_url_or_path(git_buf *local_path_out, const char *url_or_path)
{
1494 1495 1496 1497
	if (git_path_is_local_file_url(url_or_path))
		return git_path_fromurl(local_path_out, url_or_path);
	else
		return git_buf_sets(local_path_out, url_or_path);
1498
}
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513

/* Reject paths like AUX or COM1, or those versions that end in a dot or
 * colon.  ("AUX." or "AUX:")
 */
GIT_INLINE(bool) verify_dospath(
	const char *component,
	size_t len,
	const char dospath[3],
	bool trailing_num)
{
	size_t last = trailing_num ? 4 : 3;

	if (len < last || git__strncasecmp(component, dospath, 3) != 0)
		return true;

1514
	if (trailing_num && (component[3] < '1' || component[3] > '9'))
1515 1516 1517 1518 1519 1520 1521
		return true;

	return (len > last &&
		component[last] != '.' &&
		component[last] != ':');
}

1522
static int32_t next_hfs_char(const char **in, size_t *len)
1523
{
1524 1525 1526 1527 1528
	while (*len) {
		int32_t codepoint;
		int cp_len = git__utf8_iterate((const uint8_t *)(*in), (int)(*len), &codepoint);
		if (cp_len < 0)
			return -1;
1529

1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
		(*in) += cp_len;
		(*len) -= cp_len;

		/* these code points are ignored completely */
		switch (codepoint) {
		case 0x200c: /* ZERO WIDTH NON-JOINER */
		case 0x200d: /* ZERO WIDTH JOINER */
		case 0x200e: /* LEFT-TO-RIGHT MARK */
		case 0x200f: /* RIGHT-TO-LEFT MARK */
		case 0x202a: /* LEFT-TO-RIGHT EMBEDDING */
		case 0x202b: /* RIGHT-TO-LEFT EMBEDDING */
		case 0x202c: /* POP DIRECTIONAL FORMATTING */
		case 0x202d: /* LEFT-TO-RIGHT OVERRIDE */
		case 0x202e: /* RIGHT-TO-LEFT OVERRIDE */
		case 0x206a: /* INHIBIT SYMMETRIC SWAPPING */
		case 0x206b: /* ACTIVATE SYMMETRIC SWAPPING */
		case 0x206c: /* INHIBIT ARABIC FORM SHAPING */
		case 0x206d: /* ACTIVATE ARABIC FORM SHAPING */
		case 0x206e: /* NATIONAL DIGIT SHAPES */
		case 0x206f: /* NOMINAL DIGIT SHAPES */
		case 0xfeff: /* ZERO WIDTH NO-BREAK SPACE */
			continue;
1552 1553
		}

1554 1555 1556 1557
		/* fold into lowercase -- this will only fold characters in
		 * the ASCII range, which is perfectly fine, because the
		 * git folder name can only be composed of ascii characters
		 */
1558
		return git__tolower(codepoint);
1559
	}
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
	return 0; /* NULL byte -- end of string */
}

static bool verify_dotgit_hfs(const char *path, size_t len)
{
	if (next_hfs_char(&path, &len) != '.' ||
		next_hfs_char(&path, &len) != 'g' ||
		next_hfs_char(&path, &len) != 'i' ||
		next_hfs_char(&path, &len) != 't' ||
		next_hfs_char(&path, &len) != 0)
		return true;
1571

1572
	return false;
1573 1574
}

1575 1576
GIT_INLINE(bool) verify_dotgit_ntfs(git_repository *repo, const char *path, size_t len)
{
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
	git_buf *reserved = git_repository__reserved_names_win32;
	size_t reserved_len = git_repository__reserved_names_win32_len;
	size_t start = 0, i;

	if (repo)
		git_repository__reserved_names(&reserved, &reserved_len, repo, true);

	for (i = 0; i < reserved_len; i++) {
		git_buf *r = &reserved[i];

		if (len >= r->size &&
			strncasecmp(path, r->ptr, r->size) == 0) {
			start = r->size;
			break;
		}
	}

	if (!start)
1595 1596
		return true;

1597
	/* Reject paths like ".git\" */
1598 1599 1600
	if (path[start] == '\\')
		return false;

1601
	/* Reject paths like '.git ' or '.git.' */
1602 1603 1604 1605 1606 1607 1608 1609
	for (i = start; i < len; i++) {
		if (path[i] != ' ' && path[i] != '.')
			return true;
	}

	return false;
}

1610 1611 1612 1613 1614
GIT_INLINE(bool) verify_char(unsigned char c, unsigned int flags)
{
	if ((flags & GIT_PATH_REJECT_BACKSLASH) && c == '\\')
		return false;

1615 1616 1617
	if ((flags & GIT_PATH_REJECT_SLASH) && c == '/')
		return false;

1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
	if (flags & GIT_PATH_REJECT_NT_CHARS) {
		if (c < 32)
			return false;

		switch (c) {
		case '<':
		case '>':
		case ':':
		case '"':
		case '|':
		case '?':
		case '*':
			return false;
		}
	}

	return true;
}

/*
 * We fundamentally don't like some paths when dealing with user-inputted
 * strings (in checkout or ref names): we don't want dot or dot-dot
 * anywhere, we want to avoid writing weird paths on Windows that can't
 * be handled by tools that use the non-\\?\ APIs, we don't want slashes
 * or double slashes at the end of paths that can make them ambiguous.
 *
 * For checkout, we don't want to recurse into ".git" either.
 */
static bool verify_component(
	git_repository *repo,
	const char *component,
	size_t len,
	unsigned int flags)
{
	if (len == 0)
		return false;

	if ((flags & GIT_PATH_REJECT_TRAVERSAL) &&
		len == 1 && component[0] == '.')
		return false;

	if ((flags & GIT_PATH_REJECT_TRAVERSAL) &&
		len == 2 && component[0] == '.' && component[1] == '.')
		return false;

	if ((flags & GIT_PATH_REJECT_TRAILING_DOT) && component[len-1] == '.')
		return false;

	if ((flags & GIT_PATH_REJECT_TRAILING_SPACE) && component[len-1] == ' ')
		return false;

	if ((flags & GIT_PATH_REJECT_TRAILING_COLON) && component[len-1] == ':')
		return false;

	if (flags & GIT_PATH_REJECT_DOS_PATHS) {
		if (!verify_dospath(component, len, "CON", false) ||
			!verify_dospath(component, len, "PRN", false) ||
			!verify_dospath(component, len, "AUX", false) ||
			!verify_dospath(component, len, "NUL", false) ||
			!verify_dospath(component, len, "COM", true)  ||
			!verify_dospath(component, len, "LPT", true))
			return false;
	}

1682 1683 1684 1685
	if (flags & GIT_PATH_REJECT_DOT_GIT_HFS &&
		!verify_dotgit_hfs(component, len))
		return false;

1686 1687 1688 1689
	if (flags & GIT_PATH_REJECT_DOT_GIT_NTFS &&
		!verify_dotgit_ntfs(repo, component, len))
		return false;

1690 1691 1692
	/* don't bother rerunning the `.git` test if we ran the HFS or NTFS
	 * specific tests, they would have already rejected `.git`.
	 */
1693 1694
	if ((flags & GIT_PATH_REJECT_DOT_GIT_HFS) == 0 &&
		(flags & GIT_PATH_REJECT_DOT_GIT_NTFS) == 0 &&
1695
		(flags & GIT_PATH_REJECT_DOT_GIT_LITERAL) &&
1696 1697 1698 1699 1700 1701 1702
		len == 4 &&
		component[0] == '.' &&
		(component[1] == 'g' || component[1] == 'G') &&
		(component[2] == 'i' || component[2] == 'I') &&
		(component[3] == 't' || component[3] == 'T'))
		return false;

1703 1704 1705
	return true;
}

1706 1707 1708 1709 1710
GIT_INLINE(unsigned int) dotgit_flags(
	git_repository *repo,
	unsigned int flags)
{
	int protectHFS = 0, protectNTFS = 0;
1711
	int error = 0;
1712

1713 1714
	flags |= GIT_PATH_REJECT_DOT_GIT_LITERAL;

1715 1716 1717 1718 1719 1720 1721 1722 1723
#ifdef __APPLE__
	protectHFS = 1;
#endif

#ifdef GIT_WIN32
	protectNTFS = 1;
#endif

	if (repo && !protectHFS)
1724 1725
		error = git_repository__cvar(&protectHFS, repo, GIT_CVAR_PROTECTHFS);
	if (!error && protectHFS)
1726 1727 1728
		flags |= GIT_PATH_REJECT_DOT_GIT_HFS;

	if (repo && !protectNTFS)
1729 1730
		error = git_repository__cvar(&protectNTFS, repo, GIT_CVAR_PROTECTNTFS);
	if (!error && protectNTFS)
1731 1732 1733 1734 1735
		flags |= GIT_PATH_REJECT_DOT_GIT_NTFS;

	return flags;
}

1736 1737 1738 1739 1740 1741 1742
bool git_path_isvalid(
	git_repository *repo,
	const char *path,
	unsigned int flags)
{
	const char *start, *c;

1743 1744 1745 1746
	/* Upgrade the ".git" checks based on platform */
	if ((flags & GIT_PATH_REJECT_DOT_GIT))
		flags = dotgit_flags(repo, flags);

1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
	for (start = c = path; *c; c++) {
		if (!verify_char(*c, flags))
			return false;

		if (*c == '/') {
			if (!verify_component(repo, start, (c - start), flags))
				return false;

			start = c+1;
		}
	}

	return verify_component(repo, start, (c - start), flags);
}
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776

int git_path_normalize_slashes(git_buf *out, const char *path)
{
	int error;
	char *p;

	if ((error = git_buf_puts(out, path)) < 0)
		return error;

	for (p = out->ptr; *p; p++) {
		if (*p == '\\')
			*p = '/';
	}

	return 0;
}