]> git.proxmox.com Git - libgit2.git/blob - src/path.c
diriter: don't double '/' on Windows
[libgit2.git] / src / path.c
1 /*
2 * Copyright (C) the libgit2 contributors. All rights reserved.
3 *
4 * This file is part of libgit2, distributed under the GNU GPL v2 with
5 * a Linking Exception. For full terms see the included COPYING file.
6 */
7 #include "common.h"
8 #include "path.h"
9 #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 #else
17 #include <dirent.h>
18 #endif
19 #include <stdio.h>
20 #include <ctype.h>
21
22 #define LOOKS_LIKE_DRIVE_PREFIX(S) (git__isalpha((S)[0]) && (S)[1] == ':')
23
24 #ifdef GIT_WIN32
25 static bool looks_like_network_computer_name(const char *path, int pos)
26 {
27 if (pos < 3)
28 return false;
29
30 if (path[0] != '/' || path[1] != '/')
31 return false;
32
33 while (pos-- > 2) {
34 if (path[pos] == '/')
35 return false;
36 }
37
38 return true;
39 }
40 #endif
41
42 /*
43 * Based on the Android implementation, BSD licensed.
44 * http://android.git.kernel.org/
45 *
46 * Copyright (C) 2008 The Android Open Source Project
47 * All rights reserved.
48 *
49 * Redistribution and use in source and binary forms, with or without
50 * modification, are permitted provided that the following conditions
51 * are met:
52 * * Redistributions of source code must retain the above copyright
53 * notice, this list of conditions and the following disclaimer.
54 * * Redistributions in binary form must reproduce the above copyright
55 * notice, this list of conditions and the following disclaimer in
56 * the documentation and/or other materials provided with the
57 * distribution.
58 *
59 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
60 * AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
61 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
62 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
63 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
64 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
65 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
66 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
67 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
68 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
69 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70 * SUCH DAMAGE.
71 */
72 int git_path_basename_r(git_buf *buffer, const char *path)
73 {
74 const char *endp, *startp;
75 int len, result;
76
77 /* Empty or NULL string gets treated as "." */
78 if (path == NULL || *path == '\0') {
79 startp = ".";
80 len = 1;
81 goto Exit;
82 }
83
84 /* Strip trailing slashes */
85 endp = path + strlen(path) - 1;
86 while (endp > path && *endp == '/')
87 endp--;
88
89 /* All slashes becomes "/" */
90 if (endp == path && *endp == '/') {
91 startp = "/";
92 len = 1;
93 goto Exit;
94 }
95
96 /* Find the start of the base */
97 startp = endp;
98 while (startp > path && *(startp - 1) != '/')
99 startp--;
100
101 /* Cast is safe because max path < max int */
102 len = (int)(endp - startp + 1);
103
104 Exit:
105 result = len;
106
107 if (buffer != NULL && git_buf_set(buffer, startp, len) < 0)
108 return -1;
109
110 return result;
111 }
112
113 /*
114 * Based on the Android implementation, BSD licensed.
115 * Check http://android.git.kernel.org/
116 */
117 int git_path_dirname_r(git_buf *buffer, const char *path)
118 {
119 const char *endp;
120 int result, len;
121
122 /* Empty or NULL string gets treated as "." */
123 if (path == NULL || *path == '\0') {
124 path = ".";
125 len = 1;
126 goto Exit;
127 }
128
129 /* Strip trailing slashes */
130 endp = path + strlen(path) - 1;
131 while (endp > path && *endp == '/')
132 endp--;
133
134 /* Find the start of the dir */
135 while (endp > path && *endp != '/')
136 endp--;
137
138 /* Either the dir is "/" or there are no slashes */
139 if (endp == path) {
140 path = (*endp == '/') ? "/" : ".";
141 len = 1;
142 goto Exit;
143 }
144
145 do {
146 endp--;
147 } while (endp > path && *endp == '/');
148
149 /* Cast is safe because max path < max int */
150 len = (int)(endp - path + 1);
151
152 #ifdef GIT_WIN32
153 /* Mimic unix behavior where '/.git' returns '/': 'C:/.git' will return
154 'C:/' here */
155
156 if (len == 2 && LOOKS_LIKE_DRIVE_PREFIX(path)) {
157 len = 3;
158 goto Exit;
159 }
160
161 /* Similarly checks if we're dealing with a network computer name
162 '//computername/.git' will return '//computername/' */
163
164 if (looks_like_network_computer_name(path, len)) {
165 len++;
166 goto Exit;
167 }
168
169 #endif
170
171 Exit:
172 result = len;
173
174 if (buffer != NULL && git_buf_set(buffer, path, len) < 0)
175 return -1;
176
177 return result;
178 }
179
180
181 char *git_path_dirname(const char *path)
182 {
183 git_buf buf = GIT_BUF_INIT;
184 char *dirname;
185
186 git_path_dirname_r(&buf, path);
187 dirname = git_buf_detach(&buf);
188 git_buf_free(&buf); /* avoid memleak if error occurs */
189
190 return dirname;
191 }
192
193 char *git_path_basename(const char *path)
194 {
195 git_buf buf = GIT_BUF_INIT;
196 char *basename;
197
198 git_path_basename_r(&buf, path);
199 basename = git_buf_detach(&buf);
200 git_buf_free(&buf); /* avoid memleak if error occurs */
201
202 return basename;
203 }
204
205 size_t git_path_basename_offset(git_buf *buffer)
206 {
207 ssize_t slash;
208
209 if (!buffer || buffer->size <= 0)
210 return 0;
211
212 slash = git_buf_rfind_next(buffer, '/');
213
214 if (slash >= 0 && buffer->ptr[slash] == '/')
215 return (size_t)(slash + 1);
216
217 return 0;
218 }
219
220 const char *git_path_topdir(const char *path)
221 {
222 size_t len;
223 ssize_t i;
224
225 assert(path);
226 len = strlen(path);
227
228 if (!len || path[len - 1] != '/')
229 return NULL;
230
231 for (i = (ssize_t)len - 2; i >= 0; --i)
232 if (path[i] == '/')
233 break;
234
235 return &path[i + 1];
236 }
237
238 int git_path_root(const char *path)
239 {
240 int offset = 0;
241
242 /* Does the root of the path look like a windows drive ? */
243 if (LOOKS_LIKE_DRIVE_PREFIX(path))
244 offset += 2;
245
246 #ifdef GIT_WIN32
247 /* Are we dealing with a windows network path? */
248 else if ((path[0] == '/' && path[1] == '/' && path[2] != '/') ||
249 (path[0] == '\\' && path[1] == '\\' && path[2] != '\\'))
250 {
251 offset += 2;
252
253 /* Skip the computer name segment */
254 while (path[offset] && path[offset] != '/' && path[offset] != '\\')
255 offset++;
256 }
257 #endif
258
259 if (path[offset] == '/' || path[offset] == '\\')
260 return offset;
261
262 return -1; /* Not a real error - signals that path is not rooted */
263 }
264
265 void git_path_trim_slashes(git_buf *path)
266 {
267 int ceiling = git_path_root(path->ptr) + 1;
268 assert(ceiling >= 0);
269
270 while (path->size > (size_t)ceiling) {
271 if (path->ptr[path->size-1] != '/')
272 break;
273
274 path->ptr[path->size-1] = '\0';
275 path->size--;
276 }
277 }
278
279 int git_path_join_unrooted(
280 git_buf *path_out, const char *path, const char *base, ssize_t *root_at)
281 {
282 ssize_t root;
283
284 assert(path && path_out);
285
286 root = (ssize_t)git_path_root(path);
287
288 if (base != NULL && root < 0) {
289 if (git_buf_joinpath(path_out, base, path) < 0)
290 return -1;
291
292 root = (ssize_t)strlen(base);
293 } else {
294 if (git_buf_sets(path_out, path) < 0)
295 return -1;
296
297 if (root < 0)
298 root = 0;
299 else if (base)
300 git_path_equal_or_prefixed(base, path, &root);
301 }
302
303 if (root_at)
304 *root_at = root;
305
306 return 0;
307 }
308
309 int git_path_prettify(git_buf *path_out, const char *path, const char *base)
310 {
311 char buf[GIT_PATH_MAX];
312
313 assert(path && path_out);
314
315 /* construct path if needed */
316 if (base != NULL && git_path_root(path) < 0) {
317 if (git_buf_joinpath(path_out, base, path) < 0)
318 return -1;
319 path = path_out->ptr;
320 }
321
322 if (p_realpath(path, buf) == NULL) {
323 /* giterr_set resets the errno when dealing with a GITERR_OS kind of error */
324 int error = (errno == ENOENT || errno == ENOTDIR) ? GIT_ENOTFOUND : -1;
325 giterr_set(GITERR_OS, "Failed to resolve path '%s'", path);
326
327 git_buf_clear(path_out);
328
329 return error;
330 }
331
332 return git_buf_sets(path_out, buf);
333 }
334
335 int git_path_prettify_dir(git_buf *path_out, const char *path, const char *base)
336 {
337 int error = git_path_prettify(path_out, path, base);
338 return (error < 0) ? error : git_path_to_dir(path_out);
339 }
340
341 int git_path_to_dir(git_buf *path)
342 {
343 if (path->asize > 0 &&
344 git_buf_len(path) > 0 &&
345 path->ptr[git_buf_len(path) - 1] != '/')
346 git_buf_putc(path, '/');
347
348 return git_buf_oom(path) ? -1 : 0;
349 }
350
351 void git_path_string_to_dir(char* path, size_t size)
352 {
353 size_t end = strlen(path);
354
355 if (end && path[end - 1] != '/' && end < size) {
356 path[end] = '/';
357 path[end + 1] = '\0';
358 }
359 }
360
361 int git__percent_decode(git_buf *decoded_out, const char *input)
362 {
363 int len, hi, lo, i;
364 assert(decoded_out && input);
365
366 len = (int)strlen(input);
367 git_buf_clear(decoded_out);
368
369 for(i = 0; i < len; i++)
370 {
371 char c = input[i];
372
373 if (c != '%')
374 goto append;
375
376 if (i >= len - 2)
377 goto append;
378
379 hi = git__fromhex(input[i + 1]);
380 lo = git__fromhex(input[i + 2]);
381
382 if (hi < 0 || lo < 0)
383 goto append;
384
385 c = (char)(hi << 4 | lo);
386 i += 2;
387
388 append:
389 if (git_buf_putc(decoded_out, c) < 0)
390 return -1;
391 }
392
393 return 0;
394 }
395
396 static int error_invalid_local_file_uri(const char *uri)
397 {
398 giterr_set(GITERR_CONFIG, "'%s' is not a valid local file URI", uri);
399 return -1;
400 }
401
402 static int local_file_url_prefixlen(const char *file_url)
403 {
404 int len = -1;
405
406 if (git__prefixcmp(file_url, "file://") == 0) {
407 if (file_url[7] == '/')
408 len = 8;
409 else if (git__prefixcmp(file_url + 7, "localhost/") == 0)
410 len = 17;
411 }
412
413 return len;
414 }
415
416 bool git_path_is_local_file_url(const char *file_url)
417 {
418 return (local_file_url_prefixlen(file_url) > 0);
419 }
420
421 int git_path_fromurl(git_buf *local_path_out, const char *file_url)
422 {
423 int offset;
424
425 assert(local_path_out && file_url);
426
427 if ((offset = local_file_url_prefixlen(file_url)) < 0 ||
428 file_url[offset] == '\0' || file_url[offset] == '/')
429 return error_invalid_local_file_uri(file_url);
430
431 #ifndef GIT_WIN32
432 offset--; /* A *nix absolute path starts with a forward slash */
433 #endif
434
435 git_buf_clear(local_path_out);
436 return git__percent_decode(local_path_out, file_url + offset);
437 }
438
439 int git_path_walk_up(
440 git_buf *path,
441 const char *ceiling,
442 int (*cb)(void *data, const char *),
443 void *data)
444 {
445 int error = 0;
446 git_buf iter;
447 ssize_t stop = 0, scan;
448 char oldc = '\0';
449
450 assert(path && cb);
451
452 if (ceiling != NULL) {
453 if (git__prefixcmp(path->ptr, ceiling) == 0)
454 stop = (ssize_t)strlen(ceiling);
455 else
456 stop = git_buf_len(path);
457 }
458 scan = git_buf_len(path);
459
460 /* empty path: yield only once */
461 if (!scan) {
462 error = cb(data, "");
463 if (error)
464 giterr_set_after_callback(error);
465 return error;
466 }
467
468 iter.ptr = path->ptr;
469 iter.size = git_buf_len(path);
470 iter.asize = path->asize;
471
472 while (scan >= stop) {
473 error = cb(data, iter.ptr);
474 iter.ptr[scan] = oldc;
475
476 if (error) {
477 giterr_set_after_callback(error);
478 break;
479 }
480
481 scan = git_buf_rfind_next(&iter, '/');
482 if (scan >= 0) {
483 scan++;
484 oldc = iter.ptr[scan];
485 iter.size = scan;
486 iter.ptr[scan] = '\0';
487 }
488 }
489
490 if (scan >= 0)
491 iter.ptr[scan] = oldc;
492
493 /* relative path: yield for the last component */
494 if (!error && stop == 0 && iter.ptr[0] != '/') {
495 error = cb(data, "");
496 if (error)
497 giterr_set_after_callback(error);
498 }
499
500 return error;
501 }
502
503 bool git_path_exists(const char *path)
504 {
505 assert(path);
506 return p_access(path, F_OK) == 0;
507 }
508
509 bool git_path_isdir(const char *path)
510 {
511 struct stat st;
512 if (p_stat(path, &st) < 0)
513 return false;
514
515 return S_ISDIR(st.st_mode) != 0;
516 }
517
518 bool git_path_isfile(const char *path)
519 {
520 struct stat st;
521
522 assert(path);
523 if (p_stat(path, &st) < 0)
524 return false;
525
526 return S_ISREG(st.st_mode) != 0;
527 }
528
529 #ifdef GIT_WIN32
530
531 bool git_path_is_empty_dir(const char *path)
532 {
533 git_win32_path filter_w;
534 bool empty = false;
535
536 if (git_win32__findfirstfile_filter(filter_w, path)) {
537 WIN32_FIND_DATAW findData;
538 HANDLE hFind = FindFirstFileW(filter_w, &findData);
539
540 /* FindFirstFile will fail if there are no children to the given
541 * path, which can happen if the given path is a file (and obviously
542 * has no children) or if the given path is an empty mount point.
543 * (Most directories have at least directory entries '.' and '..',
544 * but ridiculously another volume mounted in another drive letter's
545 * path space do not, and thus have nothing to enumerate.) If
546 * FindFirstFile fails, check if this is a directory-like thing
547 * (a mount point).
548 */
549 if (hFind == INVALID_HANDLE_VALUE)
550 return git_path_isdir(path);
551
552 /* If the find handle was created successfully, then it's a directory */
553 empty = true;
554
555 do {
556 /* Allow the enumeration to return . and .. and still be considered
557 * empty. In the special case of drive roots (i.e. C:\) where . and
558 * .. do not occur, we can still consider the path to be an empty
559 * directory if there's nothing there. */
560 if (!git_path_is_dot_or_dotdotW(findData.cFileName)) {
561 empty = false;
562 break;
563 }
564 } while (FindNextFileW(hFind, &findData));
565
566 FindClose(hFind);
567 }
568
569 return empty;
570 }
571
572 #else
573
574 static int path_found_entry(void *payload, git_buf *path)
575 {
576 GIT_UNUSED(payload);
577 return !git_path_is_dot_or_dotdot(path->ptr);
578 }
579
580 bool git_path_is_empty_dir(const char *path)
581 {
582 int error;
583 git_buf dir = GIT_BUF_INIT;
584
585 if (!git_path_isdir(path))
586 return false;
587
588 if ((error = git_buf_sets(&dir, path)) != 0)
589 giterr_clear();
590 else
591 error = git_path_direach(&dir, 0, path_found_entry, NULL);
592
593 git_buf_free(&dir);
594
595 return !error;
596 }
597
598 #endif
599
600 int git_path_set_error(int errno_value, const char *path, const char *action)
601 {
602 switch (errno_value) {
603 case ENOENT:
604 case ENOTDIR:
605 giterr_set(GITERR_OS, "Could not find '%s' to %s", path, action);
606 return GIT_ENOTFOUND;
607
608 case EINVAL:
609 case ENAMETOOLONG:
610 giterr_set(GITERR_OS, "Invalid path for filesystem '%s'", path);
611 return GIT_EINVALIDSPEC;
612
613 case EEXIST:
614 giterr_set(GITERR_OS, "Failed %s - '%s' already exists", action, path);
615 return GIT_EEXISTS;
616
617 default:
618 giterr_set(GITERR_OS, "Could not %s '%s'", action, path);
619 return -1;
620 }
621 }
622
623 int git_path_lstat(const char *path, struct stat *st)
624 {
625 if (p_lstat(path, st) == 0)
626 return 0;
627
628 return git_path_set_error(errno, path, "stat");
629 }
630
631 static bool _check_dir_contents(
632 git_buf *dir,
633 const char *sub,
634 bool (*predicate)(const char *))
635 {
636 bool result;
637 size_t dir_size = git_buf_len(dir);
638 size_t sub_size = strlen(sub);
639 size_t alloc_size;
640
641 /* leave base valid even if we could not make space for subdir */
642 if (GIT_ADD_SIZET_OVERFLOW(&alloc_size, dir_size, sub_size) ||
643 GIT_ADD_SIZET_OVERFLOW(&alloc_size, alloc_size, 2) ||
644 git_buf_try_grow(dir, alloc_size, false) < 0)
645 return false;
646
647 /* save excursion */
648 git_buf_joinpath(dir, dir->ptr, sub);
649
650 result = predicate(dir->ptr);
651
652 /* restore path */
653 git_buf_truncate(dir, dir_size);
654 return result;
655 }
656
657 bool git_path_contains(git_buf *dir, const char *item)
658 {
659 return _check_dir_contents(dir, item, &git_path_exists);
660 }
661
662 bool git_path_contains_dir(git_buf *base, const char *subdir)
663 {
664 return _check_dir_contents(base, subdir, &git_path_isdir);
665 }
666
667 bool git_path_contains_file(git_buf *base, const char *file)
668 {
669 return _check_dir_contents(base, file, &git_path_isfile);
670 }
671
672 int git_path_find_dir(git_buf *dir, const char *path, const char *base)
673 {
674 int error = git_path_join_unrooted(dir, path, base, NULL);
675
676 if (!error) {
677 char buf[GIT_PATH_MAX];
678 if (p_realpath(dir->ptr, buf) != NULL)
679 error = git_buf_sets(dir, buf);
680 }
681
682 /* call dirname if this is not a directory */
683 if (!error) /* && git_path_isdir(dir->ptr) == false) */
684 error = (git_path_dirname_r(dir, dir->ptr) < 0) ? -1 : 0;
685
686 if (!error)
687 error = git_path_to_dir(dir);
688
689 return error;
690 }
691
692 int git_path_resolve_relative(git_buf *path, size_t ceiling)
693 {
694 char *base, *to, *from, *next;
695 size_t len;
696
697 if (!path || git_buf_oom(path))
698 return -1;
699
700 if (ceiling > path->size)
701 ceiling = path->size;
702
703 /* recognize drive prefixes, etc. that should not be backed over */
704 if (ceiling == 0)
705 ceiling = git_path_root(path->ptr) + 1;
706
707 /* recognize URL prefixes that should not be backed over */
708 if (ceiling == 0) {
709 for (next = path->ptr; *next && git__isalpha(*next); ++next);
710 if (next[0] == ':' && next[1] == '/' && next[2] == '/')
711 ceiling = (next + 3) - path->ptr;
712 }
713
714 base = to = from = path->ptr + ceiling;
715
716 while (*from) {
717 for (next = from; *next && *next != '/'; ++next);
718
719 len = next - from;
720
721 if (len == 1 && from[0] == '.')
722 /* do nothing with singleton dot */;
723
724 else if (len == 2 && from[0] == '.' && from[1] == '.') {
725 /* error out if trying to up one from a hard base */
726 if (to == base && ceiling != 0) {
727 giterr_set(GITERR_INVALID,
728 "Cannot strip root component off url");
729 return -1;
730 }
731
732 /* no more path segments to strip,
733 * use '../' as a new base path */
734 if (to == base) {
735 if (*next == '/')
736 len++;
737
738 if (to != from)
739 memmove(to, from, len);
740
741 to += len;
742 /* this is now the base, can't back up from a
743 * relative prefix */
744 base = to;
745 } else {
746 /* back up a path segment */
747 while (to > base && to[-1] == '/') to--;
748 while (to > base && to[-1] != '/') to--;
749 }
750 } else {
751 if (*next == '/' && *from != '/')
752 len++;
753
754 if (to != from)
755 memmove(to, from, len);
756
757 to += len;
758 }
759
760 from += len;
761
762 while (*from == '/') from++;
763 }
764
765 *to = '\0';
766
767 path->size = to - path->ptr;
768
769 return 0;
770 }
771
772 int git_path_apply_relative(git_buf *target, const char *relpath)
773 {
774 git_buf_joinpath(target, git_buf_cstr(target), relpath);
775 return git_path_resolve_relative(target, 0);
776 }
777
778 int git_path_cmp(
779 const char *name1, size_t len1, int isdir1,
780 const char *name2, size_t len2, int isdir2,
781 int (*compare)(const char *, const char *, size_t))
782 {
783 unsigned char c1, c2;
784 size_t len = len1 < len2 ? len1 : len2;
785 int cmp;
786
787 cmp = compare(name1, name2, len);
788 if (cmp)
789 return cmp;
790
791 c1 = name1[len];
792 c2 = name2[len];
793
794 if (c1 == '\0' && isdir1)
795 c1 = '/';
796
797 if (c2 == '\0' && isdir2)
798 c2 = '/';
799
800 return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
801 }
802
803 int git_path_make_relative(git_buf *path, const char *parent)
804 {
805 const char *p, *q, *p_dirsep, *q_dirsep;
806 size_t plen = path->size, newlen, alloclen, depth = 1, i, offset;
807
808 for (p_dirsep = p = path->ptr, q_dirsep = q = parent; *p && *q; p++, q++) {
809 if (*p == '/' && *q == '/') {
810 p_dirsep = p;
811 q_dirsep = q;
812 }
813 else if (*p != *q)
814 break;
815 }
816
817 /* need at least 1 common path segment */
818 if ((p_dirsep == path->ptr || q_dirsep == parent) &&
819 (*p_dirsep != '/' || *q_dirsep != '/')) {
820 giterr_set(GITERR_INVALID,
821 "%s is not a parent of %s", parent, path->ptr);
822 return GIT_ENOTFOUND;
823 }
824
825 if (*p == '/' && !*q)
826 p++;
827 else if (!*p && *q == '/')
828 q++;
829 else if (!*p && !*q)
830 return git_buf_clear(path), 0;
831 else {
832 p = p_dirsep + 1;
833 q = q_dirsep + 1;
834 }
835
836 plen -= (p - path->ptr);
837
838 if (!*q)
839 return git_buf_set(path, p, plen);
840
841 for (; (q = strchr(q, '/')) && *(q + 1); q++)
842 depth++;
843
844 GITERR_CHECK_ALLOC_MULTIPLY(&newlen, depth, 3);
845 GITERR_CHECK_ALLOC_ADD(&newlen, newlen, plen);
846
847 GITERR_CHECK_ALLOC_ADD(&alloclen, newlen, 1);
848
849 /* save the offset as we might realllocate the pointer */
850 offset = p - path->ptr;
851 if (git_buf_try_grow(path, alloclen, 1) < 0)
852 return -1;
853 p = path->ptr + offset;
854
855 memmove(path->ptr + (depth * 3), p, plen + 1);
856
857 for (i = 0; i < depth; i++)
858 memcpy(path->ptr + (i * 3), "../", 3);
859
860 path->size = newlen;
861 return 0;
862 }
863
864 bool git_path_has_non_ascii(const char *path, size_t pathlen)
865 {
866 const uint8_t *scan = (const uint8_t *)path, *end;
867
868 for (end = scan + pathlen; scan < end; ++scan)
869 if (*scan & 0x80)
870 return true;
871
872 return false;
873 }
874
875 #ifdef GIT_USE_ICONV
876
877 int git_path_iconv_init_precompose(git_path_iconv_t *ic)
878 {
879 git_buf_init(&ic->buf, 0);
880 ic->map = iconv_open(GIT_PATH_REPO_ENCODING, GIT_PATH_NATIVE_ENCODING);
881 return 0;
882 }
883
884 void git_path_iconv_clear(git_path_iconv_t *ic)
885 {
886 if (ic) {
887 if (ic->map != (iconv_t)-1)
888 iconv_close(ic->map);
889 git_buf_free(&ic->buf);
890 }
891 }
892
893 int git_path_iconv(git_path_iconv_t *ic, const char **in, size_t *inlen)
894 {
895 char *nfd = (char*)*in, *nfc;
896 size_t nfdlen = *inlen, nfclen, wantlen = nfdlen, alloclen, rv;
897 int retry = 1;
898
899 if (!ic || ic->map == (iconv_t)-1 ||
900 !git_path_has_non_ascii(*in, *inlen))
901 return 0;
902
903 git_buf_clear(&ic->buf);
904
905 while (1) {
906 GITERR_CHECK_ALLOC_ADD(&alloclen, wantlen, 1);
907 if (git_buf_grow(&ic->buf, alloclen) < 0)
908 return -1;
909
910 nfc = ic->buf.ptr + ic->buf.size;
911 nfclen = ic->buf.asize - ic->buf.size;
912
913 rv = iconv(ic->map, &nfd, &nfdlen, &nfc, &nfclen);
914
915 ic->buf.size = (nfc - ic->buf.ptr);
916
917 if (rv != (size_t)-1)
918 break;
919
920 /* if we cannot convert the data (probably because iconv thinks
921 * it is not valid UTF-8 source data), then use original data
922 */
923 if (errno != E2BIG)
924 return 0;
925
926 /* make space for 2x the remaining data to be converted
927 * (with per retry overhead to avoid infinite loops)
928 */
929 wantlen = ic->buf.size + max(nfclen, nfdlen) * 2 + (size_t)(retry * 4);
930
931 if (retry++ > 4)
932 goto fail;
933 }
934
935 ic->buf.ptr[ic->buf.size] = '\0';
936
937 *in = ic->buf.ptr;
938 *inlen = ic->buf.size;
939
940 return 0;
941
942 fail:
943 giterr_set(GITERR_OS, "Unable to convert unicode path data");
944 return -1;
945 }
946
947 static const char *nfc_file = "\xC3\x85\x73\x74\x72\xC3\xB6\x6D.XXXXXX";
948 static const char *nfd_file = "\x41\xCC\x8A\x73\x74\x72\x6F\xCC\x88\x6D.XXXXXX";
949
950 /* Check if the platform is decomposing unicode data for us. We will
951 * emulate core Git and prefer to use precomposed unicode data internally
952 * on these platforms, composing the decomposed unicode on the fly.
953 *
954 * This mainly happens on the Mac where HDFS stores filenames as
955 * decomposed unicode. Even on VFAT and SAMBA file systems, the Mac will
956 * return decomposed unicode from readdir() even when the actual
957 * filesystem is storing precomposed unicode.
958 */
959 bool git_path_does_fs_decompose_unicode(const char *root)
960 {
961 git_buf path = GIT_BUF_INIT;
962 int fd;
963 bool found_decomposed = false;
964 char tmp[6];
965
966 /* Create a file using a precomposed path and then try to find it
967 * using the decomposed name. If the lookup fails, then we will mark
968 * that we should precompose unicode for this repository.
969 */
970 if (git_buf_joinpath(&path, root, nfc_file) < 0 ||
971 (fd = p_mkstemp(path.ptr)) < 0)
972 goto done;
973 p_close(fd);
974
975 /* record trailing digits generated by mkstemp */
976 memcpy(tmp, path.ptr + path.size - sizeof(tmp), sizeof(tmp));
977
978 /* try to look up as NFD path */
979 if (git_buf_joinpath(&path, root, nfd_file) < 0)
980 goto done;
981 memcpy(path.ptr + path.size - sizeof(tmp), tmp, sizeof(tmp));
982
983 found_decomposed = git_path_exists(path.ptr);
984
985 /* remove temporary file (using original precomposed path) */
986 if (git_buf_joinpath(&path, root, nfc_file) < 0)
987 goto done;
988 memcpy(path.ptr + path.size - sizeof(tmp), tmp, sizeof(tmp));
989
990 (void)p_unlink(path.ptr);
991
992 done:
993 git_buf_free(&path);
994 return found_decomposed;
995 }
996
997 #else
998
999 bool git_path_does_fs_decompose_unicode(const char *root)
1000 {
1001 GIT_UNUSED(root);
1002 return false;
1003 }
1004
1005 #endif
1006
1007 #if defined(__sun) || defined(__GNU__)
1008 typedef char path_dirent_data[sizeof(struct dirent) + FILENAME_MAX + 1];
1009 #else
1010 typedef struct dirent path_dirent_data;
1011 #endif
1012
1013 int git_path_direach(
1014 git_buf *path,
1015 uint32_t flags,
1016 int (*fn)(void *, git_buf *),
1017 void *arg)
1018 {
1019 int error = 0;
1020 ssize_t wd_len;
1021 DIR *dir;
1022 struct dirent *de;
1023
1024 #ifdef GIT_USE_ICONV
1025 git_path_iconv_t ic = GIT_PATH_ICONV_INIT;
1026 #endif
1027
1028 GIT_UNUSED(flags);
1029
1030 if (git_path_to_dir(path) < 0)
1031 return -1;
1032
1033 wd_len = git_buf_len(path);
1034
1035 if ((dir = opendir(path->ptr)) == NULL) {
1036 giterr_set(GITERR_OS, "Failed to open directory '%s'", path->ptr);
1037 if (errno == ENOENT)
1038 return GIT_ENOTFOUND;
1039
1040 return -1;
1041 }
1042
1043 #ifdef GIT_USE_ICONV
1044 if ((flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
1045 (void)git_path_iconv_init_precompose(&ic);
1046 #endif
1047
1048 while ((de = readdir(dir)) != NULL) {
1049 const char *de_path = de->d_name;
1050 size_t de_len = strlen(de_path);
1051
1052 if (git_path_is_dot_or_dotdot(de_path))
1053 continue;
1054
1055 #ifdef GIT_USE_ICONV
1056 if ((error = git_path_iconv(&ic, &de_path, &de_len)) < 0)
1057 break;
1058 #endif
1059
1060 if ((error = git_buf_put(path, de_path, de_len)) < 0)
1061 break;
1062
1063 giterr_clear();
1064 error = fn(arg, path);
1065
1066 git_buf_truncate(path, wd_len); /* restore path */
1067
1068 /* Only set our own error if the callback did not set one already */
1069 if (error != 0) {
1070 if (!giterr_last())
1071 giterr_set_after_callback(error);
1072
1073 break;
1074 }
1075 }
1076
1077 closedir(dir);
1078
1079 #ifdef GIT_USE_ICONV
1080 git_path_iconv_clear(&ic);
1081 #endif
1082
1083 return error;
1084 }
1085
1086 #if defined(GIT_WIN32) && !defined(__MINGW32__)
1087
1088 /* Using _FIND_FIRST_EX_LARGE_FETCH may increase performance in Windows 7
1089 * and better.
1090 */
1091 #ifndef FIND_FIRST_EX_LARGE_FETCH
1092 # define FIND_FIRST_EX_LARGE_FETCH 2
1093 #endif
1094
1095 int git_path_diriter_init(
1096 git_path_diriter *diriter,
1097 const char *path,
1098 unsigned int flags)
1099 {
1100 git_win32_path path_filter;
1101 git_buf hack = {0};
1102
1103 static int is_win7_or_later = -1;
1104 if (is_win7_or_later < 0)
1105 is_win7_or_later = git_has_win32_version(6, 1, 0);
1106
1107 assert(diriter && path);
1108
1109 memset(diriter, 0, sizeof(git_path_diriter));
1110 diriter->handle = INVALID_HANDLE_VALUE;
1111
1112 if (git_buf_puts(&diriter->path_utf8, path) < 0)
1113 return -1;
1114
1115 git_path_trim_slashes(&diriter->path_utf8);
1116
1117 if (diriter->path_utf8.size == 0) {
1118 giterr_set(GITERR_FILESYSTEM, "Could not open directory '%s'", path);
1119 return -1;
1120 }
1121
1122 if ((diriter->parent_len = git_win32_path_from_utf8(diriter->path, diriter->path_utf8.ptr)) < 0 ||
1123 !git_win32__findfirstfile_filter(path_filter, diriter->path_utf8.ptr)) {
1124 giterr_set(GITERR_OS, "Could not parse the directory path '%s'", path);
1125 return -1;
1126 }
1127
1128 diriter->handle = FindFirstFileExW(
1129 path_filter,
1130 is_win7_or_later ? FindExInfoBasic : FindExInfoStandard,
1131 &diriter->current,
1132 FindExSearchNameMatch,
1133 NULL,
1134 is_win7_or_later ? FIND_FIRST_EX_LARGE_FETCH : 0);
1135
1136 if (diriter->handle == INVALID_HANDLE_VALUE) {
1137 giterr_set(GITERR_OS, "Could not open directory '%s'", path);
1138 return -1;
1139 }
1140
1141 diriter->parent_utf8_len = diriter->path_utf8.size;
1142 diriter->flags = flags;
1143 return 0;
1144 }
1145
1146 static int diriter_update_paths(git_path_diriter *diriter)
1147 {
1148 size_t filename_len, path_len;
1149
1150 filename_len = wcslen(diriter->current.cFileName);
1151
1152 if (GIT_ADD_SIZET_OVERFLOW(&path_len, diriter->parent_len, filename_len) ||
1153 GIT_ADD_SIZET_OVERFLOW(&path_len, path_len, 2))
1154 return -1;
1155
1156 if (path_len > GIT_WIN_PATH_UTF16) {
1157 giterr_set(GITERR_FILESYSTEM,
1158 "invalid path '%.*ls\\%ls' (path too long)",
1159 diriter->parent_len, diriter->path, diriter->current.cFileName);
1160 return -1;
1161 }
1162
1163 diriter->path[diriter->parent_len] = L'\\';
1164 memcpy(&diriter->path[diriter->parent_len+1],
1165 diriter->current.cFileName, filename_len * sizeof(wchar_t));
1166 diriter->path[path_len-1] = L'\0';
1167
1168 git_buf_truncate(&diriter->path_utf8, diriter->parent_utf8_len);
1169
1170 if (diriter->parent_utf8_len > 0 &&
1171 diriter->path_utf8.ptr[diriter->parent_utf8_len-1] != '/')
1172 git_buf_putc(&diriter->path_utf8, '/');
1173
1174 git_buf_put_w(&diriter->path_utf8, diriter->current.cFileName, filename_len);
1175
1176 if (git_buf_oom(&diriter->path_utf8))
1177 return -1;
1178
1179 return 0;
1180 }
1181
1182 int git_path_diriter_next(git_path_diriter *diriter)
1183 {
1184 bool skip_dot = !(diriter->flags & GIT_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
1185
1186 do {
1187 /* Our first time through, we already have the data from
1188 * FindFirstFileW. Use it, otherwise get the next file.
1189 */
1190 if (!diriter->needs_next)
1191 diriter->needs_next = 1;
1192 else if (!FindNextFileW(diriter->handle, &diriter->current))
1193 return GIT_ITEROVER;
1194 } while (skip_dot && git_path_is_dot_or_dotdotW(diriter->current.cFileName));
1195
1196 if (diriter_update_paths(diriter) < 0)
1197 return -1;
1198
1199 return 0;
1200 }
1201
1202 int git_path_diriter_filename(
1203 const char **out,
1204 size_t *out_len,
1205 git_path_diriter *diriter)
1206 {
1207 assert(out && out_len && diriter);
1208
1209 assert(diriter->path_utf8.size > diriter->parent_utf8_len);
1210
1211 *out = &diriter->path_utf8.ptr[diriter->parent_utf8_len+1];
1212 *out_len = diriter->path_utf8.size - diriter->parent_utf8_len - 1;
1213 return 0;
1214 }
1215
1216 int git_path_diriter_fullpath(
1217 const char **out,
1218 size_t *out_len,
1219 git_path_diriter *diriter)
1220 {
1221 assert(out && out_len && diriter);
1222
1223 *out = diriter->path_utf8.ptr;
1224 *out_len = diriter->path_utf8.size;
1225 return 0;
1226 }
1227
1228 int git_path_diriter_stat(struct stat *out, git_path_diriter *diriter)
1229 {
1230 assert(out && diriter);
1231
1232 return git_win32__file_attribute_to_stat(out,
1233 (WIN32_FILE_ATTRIBUTE_DATA *)&diriter->current,
1234 diriter->path);
1235 }
1236
1237 void git_path_diriter_free(git_path_diriter *diriter)
1238 {
1239 if (diriter == NULL)
1240 return;
1241
1242 git_buf_free(&diriter->path_utf8);
1243
1244 if (diriter->handle != INVALID_HANDLE_VALUE) {
1245 FindClose(diriter->handle);
1246 diriter->handle = INVALID_HANDLE_VALUE;
1247 }
1248 }
1249
1250 #else
1251
1252 int git_path_diriter_init(
1253 git_path_diriter *diriter,
1254 const char *path,
1255 unsigned int flags)
1256 {
1257 assert(diriter && path);
1258
1259 memset(diriter, 0, sizeof(git_path_diriter));
1260
1261 if (git_buf_puts(&diriter->path, path) < 0)
1262 return -1;
1263
1264 git_path_trim_slashes(&diriter->path);
1265
1266 if (diriter->path.size == 0) {
1267 giterr_set(GITERR_FILESYSTEM, "Could not open directory '%s'", path);
1268 return -1;
1269 }
1270
1271 if ((diriter->dir = opendir(diriter->path.ptr)) == NULL) {
1272 git_buf_free(&diriter->path);
1273
1274 giterr_set(GITERR_OS, "Failed to open directory '%s'", path);
1275 return -1;
1276 }
1277
1278 #ifdef GIT_USE_ICONV
1279 if ((flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
1280 (void)git_path_iconv_init_precompose(&diriter->ic);
1281 #endif
1282
1283 diriter->parent_len = diriter->path.size;
1284 diriter->flags = flags;
1285
1286 return 0;
1287 }
1288
1289 int git_path_diriter_next(git_path_diriter *diriter)
1290 {
1291 struct dirent *de;
1292 const char *filename;
1293 size_t filename_len;
1294 bool skip_dot = !(diriter->flags & GIT_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
1295 int error = 0;
1296
1297 assert(diriter);
1298
1299 errno = 0;
1300
1301 do {
1302 if ((de = readdir(diriter->dir)) == NULL) {
1303 if (!errno)
1304 return GIT_ITEROVER;
1305
1306 giterr_set(GITERR_OS,
1307 "Could not read directory '%s'", diriter->path);
1308 return -1;
1309 }
1310 } while (skip_dot && git_path_is_dot_or_dotdot(de->d_name));
1311
1312 filename = de->d_name;
1313 filename_len = strlen(filename);
1314
1315 #ifdef GIT_USE_ICONV
1316 if ((diriter->flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0 &&
1317 (error = git_path_iconv(&diriter->ic, &filename, &filename_len)) < 0)
1318 return error;
1319 #endif
1320
1321 git_buf_truncate(&diriter->path, diriter->parent_len);
1322 git_buf_putc(&diriter->path, '/');
1323 git_buf_put(&diriter->path, filename, filename_len);
1324
1325 if (git_buf_oom(&diriter->path))
1326 return -1;
1327
1328 return error;
1329 }
1330
1331 int git_path_diriter_filename(
1332 const char **out,
1333 size_t *out_len,
1334 git_path_diriter *diriter)
1335 {
1336 assert(out && out_len && diriter);
1337
1338 assert(diriter->path.size > diriter->parent_len);
1339
1340 *out = &diriter->path.ptr[diriter->parent_len+1];
1341 *out_len = diriter->path.size - diriter->parent_len - 1;
1342 return 0;
1343 }
1344
1345 int git_path_diriter_fullpath(
1346 const char **out,
1347 size_t *out_len,
1348 git_path_diriter *diriter)
1349 {
1350 assert(out && out_len && diriter);
1351
1352 *out = diriter->path.ptr;
1353 *out_len = diriter->path.size;
1354 return 0;
1355 }
1356
1357 int git_path_diriter_stat(struct stat *out, git_path_diriter *diriter)
1358 {
1359 assert(out && diriter);
1360
1361 return git_path_lstat(diriter->path.ptr, out);
1362 }
1363
1364 void git_path_diriter_free(git_path_diriter *diriter)
1365 {
1366 if (diriter == NULL)
1367 return;
1368
1369 if (diriter->dir) {
1370 closedir(diriter->dir);
1371 diriter->dir = NULL;
1372 }
1373
1374 #ifdef GIT_USE_ICONV
1375 git_path_iconv_clear(&diriter->ic);
1376 #endif
1377
1378 git_buf_free(&diriter->path);
1379 }
1380
1381 #endif
1382
1383 int git_path_dirload(
1384 git_vector *contents,
1385 const char *path,
1386 size_t prefix_len,
1387 unsigned int flags)
1388 {
1389 git_path_diriter iter = GIT_PATH_DIRITER_INIT;
1390 const char *name;
1391 size_t name_len;
1392 char *dup;
1393 int error;
1394
1395 assert(contents && path);
1396
1397 if ((error = git_path_diriter_init(&iter, path, flags)) < 0)
1398 return error;
1399
1400 while ((error = git_path_diriter_next(&iter)) == 0) {
1401 if ((error = git_path_diriter_fullpath(&name, &name_len, &iter)) < 0)
1402 break;
1403
1404 assert(name_len > prefix_len);
1405
1406 dup = git__strndup(name + prefix_len, name_len - prefix_len);
1407 GITERR_CHECK_ALLOC(dup);
1408
1409 if ((error = git_vector_insert(contents, dup)) < 0)
1410 break;
1411 }
1412
1413 if (error == GIT_ITEROVER)
1414 error = 0;
1415
1416 git_path_diriter_free(&iter);
1417 return error;
1418 }
1419
1420 int git_path_from_url_or_path(git_buf *local_path_out, const char *url_or_path)
1421 {
1422 if (git_path_is_local_file_url(url_or_path))
1423 return git_path_fromurl(local_path_out, url_or_path);
1424 else
1425 return git_buf_sets(local_path_out, url_or_path);
1426 }
1427
1428 /* Reject paths like AUX or COM1, or those versions that end in a dot or
1429 * colon. ("AUX." or "AUX:")
1430 */
1431 GIT_INLINE(bool) verify_dospath(
1432 const char *component,
1433 size_t len,
1434 const char dospath[3],
1435 bool trailing_num)
1436 {
1437 size_t last = trailing_num ? 4 : 3;
1438
1439 if (len < last || git__strncasecmp(component, dospath, 3) != 0)
1440 return true;
1441
1442 if (trailing_num && (component[3] < '1' || component[3] > '9'))
1443 return true;
1444
1445 return (len > last &&
1446 component[last] != '.' &&
1447 component[last] != ':');
1448 }
1449
1450 static int32_t next_hfs_char(const char **in, size_t *len)
1451 {
1452 while (*len) {
1453 int32_t codepoint;
1454 int cp_len = git__utf8_iterate((const uint8_t *)(*in), (int)(*len), &codepoint);
1455 if (cp_len < 0)
1456 return -1;
1457
1458 (*in) += cp_len;
1459 (*len) -= cp_len;
1460
1461 /* these code points are ignored completely */
1462 switch (codepoint) {
1463 case 0x200c: /* ZERO WIDTH NON-JOINER */
1464 case 0x200d: /* ZERO WIDTH JOINER */
1465 case 0x200e: /* LEFT-TO-RIGHT MARK */
1466 case 0x200f: /* RIGHT-TO-LEFT MARK */
1467 case 0x202a: /* LEFT-TO-RIGHT EMBEDDING */
1468 case 0x202b: /* RIGHT-TO-LEFT EMBEDDING */
1469 case 0x202c: /* POP DIRECTIONAL FORMATTING */
1470 case 0x202d: /* LEFT-TO-RIGHT OVERRIDE */
1471 case 0x202e: /* RIGHT-TO-LEFT OVERRIDE */
1472 case 0x206a: /* INHIBIT SYMMETRIC SWAPPING */
1473 case 0x206b: /* ACTIVATE SYMMETRIC SWAPPING */
1474 case 0x206c: /* INHIBIT ARABIC FORM SHAPING */
1475 case 0x206d: /* ACTIVATE ARABIC FORM SHAPING */
1476 case 0x206e: /* NATIONAL DIGIT SHAPES */
1477 case 0x206f: /* NOMINAL DIGIT SHAPES */
1478 case 0xfeff: /* ZERO WIDTH NO-BREAK SPACE */
1479 continue;
1480 }
1481
1482 /* fold into lowercase -- this will only fold characters in
1483 * the ASCII range, which is perfectly fine, because the
1484 * git folder name can only be composed of ascii characters
1485 */
1486 return git__tolower(codepoint);
1487 }
1488 return 0; /* NULL byte -- end of string */
1489 }
1490
1491 static bool verify_dotgit_hfs(const char *path, size_t len)
1492 {
1493 if (next_hfs_char(&path, &len) != '.' ||
1494 next_hfs_char(&path, &len) != 'g' ||
1495 next_hfs_char(&path, &len) != 'i' ||
1496 next_hfs_char(&path, &len) != 't' ||
1497 next_hfs_char(&path, &len) != 0)
1498 return true;
1499
1500 return false;
1501 }
1502
1503 GIT_INLINE(bool) verify_dotgit_ntfs(git_repository *repo, const char *path, size_t len)
1504 {
1505 git_buf *reserved = git_repository__reserved_names_win32;
1506 size_t reserved_len = git_repository__reserved_names_win32_len;
1507 size_t start = 0, i;
1508
1509 if (repo)
1510 git_repository__reserved_names(&reserved, &reserved_len, repo, true);
1511
1512 for (i = 0; i < reserved_len; i++) {
1513 git_buf *r = &reserved[i];
1514
1515 if (len >= r->size &&
1516 strncasecmp(path, r->ptr, r->size) == 0) {
1517 start = r->size;
1518 break;
1519 }
1520 }
1521
1522 if (!start)
1523 return true;
1524
1525 /* Reject paths like ".git\" */
1526 if (path[start] == '\\')
1527 return false;
1528
1529 /* Reject paths like '.git ' or '.git.' */
1530 for (i = start; i < len; i++) {
1531 if (path[i] != ' ' && path[i] != '.')
1532 return true;
1533 }
1534
1535 return false;
1536 }
1537
1538 GIT_INLINE(bool) verify_char(unsigned char c, unsigned int flags)
1539 {
1540 if ((flags & GIT_PATH_REJECT_BACKSLASH) && c == '\\')
1541 return false;
1542
1543 if ((flags & GIT_PATH_REJECT_SLASH) && c == '/')
1544 return false;
1545
1546 if (flags & GIT_PATH_REJECT_NT_CHARS) {
1547 if (c < 32)
1548 return false;
1549
1550 switch (c) {
1551 case '<':
1552 case '>':
1553 case ':':
1554 case '"':
1555 case '|':
1556 case '?':
1557 case '*':
1558 return false;
1559 }
1560 }
1561
1562 return true;
1563 }
1564
1565 /*
1566 * We fundamentally don't like some paths when dealing with user-inputted
1567 * strings (in checkout or ref names): we don't want dot or dot-dot
1568 * anywhere, we want to avoid writing weird paths on Windows that can't
1569 * be handled by tools that use the non-\\?\ APIs, we don't want slashes
1570 * or double slashes at the end of paths that can make them ambiguous.
1571 *
1572 * For checkout, we don't want to recurse into ".git" either.
1573 */
1574 static bool verify_component(
1575 git_repository *repo,
1576 const char *component,
1577 size_t len,
1578 unsigned int flags)
1579 {
1580 if (len == 0)
1581 return false;
1582
1583 if ((flags & GIT_PATH_REJECT_TRAVERSAL) &&
1584 len == 1 && component[0] == '.')
1585 return false;
1586
1587 if ((flags & GIT_PATH_REJECT_TRAVERSAL) &&
1588 len == 2 && component[0] == '.' && component[1] == '.')
1589 return false;
1590
1591 if ((flags & GIT_PATH_REJECT_TRAILING_DOT) && component[len-1] == '.')
1592 return false;
1593
1594 if ((flags & GIT_PATH_REJECT_TRAILING_SPACE) && component[len-1] == ' ')
1595 return false;
1596
1597 if ((flags & GIT_PATH_REJECT_TRAILING_COLON) && component[len-1] == ':')
1598 return false;
1599
1600 if (flags & GIT_PATH_REJECT_DOS_PATHS) {
1601 if (!verify_dospath(component, len, "CON", false) ||
1602 !verify_dospath(component, len, "PRN", false) ||
1603 !verify_dospath(component, len, "AUX", false) ||
1604 !verify_dospath(component, len, "NUL", false) ||
1605 !verify_dospath(component, len, "COM", true) ||
1606 !verify_dospath(component, len, "LPT", true))
1607 return false;
1608 }
1609
1610 if (flags & GIT_PATH_REJECT_DOT_GIT_HFS &&
1611 !verify_dotgit_hfs(component, len))
1612 return false;
1613
1614 if (flags & GIT_PATH_REJECT_DOT_GIT_NTFS &&
1615 !verify_dotgit_ntfs(repo, component, len))
1616 return false;
1617
1618 if ((flags & GIT_PATH_REJECT_DOT_GIT_HFS) == 0 &&
1619 (flags & GIT_PATH_REJECT_DOT_GIT_NTFS) == 0 &&
1620 (flags & GIT_PATH_REJECT_DOT_GIT) &&
1621 len == 4 &&
1622 component[0] == '.' &&
1623 (component[1] == 'g' || component[1] == 'G') &&
1624 (component[2] == 'i' || component[2] == 'I') &&
1625 (component[3] == 't' || component[3] == 'T'))
1626 return false;
1627
1628 return true;
1629 }
1630
1631 GIT_INLINE(unsigned int) dotgit_flags(
1632 git_repository *repo,
1633 unsigned int flags)
1634 {
1635 int protectHFS = 0, protectNTFS = 0;
1636
1637 #ifdef __APPLE__
1638 protectHFS = 1;
1639 #endif
1640
1641 #ifdef GIT_WIN32
1642 protectNTFS = 1;
1643 #endif
1644
1645 if (repo && !protectHFS)
1646 git_repository__cvar(&protectHFS, repo, GIT_CVAR_PROTECTHFS);
1647 if (protectHFS)
1648 flags |= GIT_PATH_REJECT_DOT_GIT_HFS;
1649
1650 if (repo && !protectNTFS)
1651 git_repository__cvar(&protectNTFS, repo, GIT_CVAR_PROTECTNTFS);
1652 if (protectNTFS)
1653 flags |= GIT_PATH_REJECT_DOT_GIT_NTFS;
1654
1655 return flags;
1656 }
1657
1658 bool git_path_isvalid(
1659 git_repository *repo,
1660 const char *path,
1661 unsigned int flags)
1662 {
1663 const char *start, *c;
1664
1665 /* Upgrade the ".git" checks based on platform */
1666 if ((flags & GIT_PATH_REJECT_DOT_GIT))
1667 flags = dotgit_flags(repo, flags);
1668
1669 for (start = c = path; *c; c++) {
1670 if (!verify_char(*c, flags))
1671 return false;
1672
1673 if (*c == '/') {
1674 if (!verify_component(repo, start, (c - start), flags))
1675 return false;
1676
1677 start = c+1;
1678 }
1679 }
1680
1681 return verify_component(repo, start, (c - start), flags);
1682 }
1683
1684 int git_path_normalize_slashes(git_buf *out, const char *path)
1685 {
1686 int error;
1687 char *p;
1688
1689 if ((error = git_buf_puts(out, path)) < 0)
1690 return error;
1691
1692 for (p = out->ptr; *p; p++) {
1693 if (*p == '\\')
1694 *p = '/';
1695 }
1696
1697 return 0;
1698 }