Git 2.2
[git/git.git] / path.c
CommitLineData
26c8a533 1/*
3a429d3b 2 * Utilities for paths and pathnames
26c8a533
LT
3 */
4#include "cache.h"
395de250 5#include "strbuf.h"
a5ccdbe4 6#include "string-list.h"
26c8a533 7
f66450ae 8static int get_st_mode_bits(const char *path, int *mode)
0117c2f0
TB
9{
10 struct stat st;
11 if (lstat(path, &st) < 0)
12 return -1;
13 *mode = st.st_mode;
14 return 0;
15}
0117c2f0 16
26c8a533
LT
17static char bad_path[] = "/bad-path/";
18
e7676d2f
LT
19static char *get_pathname(void)
20{
21 static char pathname_array[4][PATH_MAX];
22 static int index;
23 return pathname_array[3 & ++index];
24}
25
26c8a533
LT
26static char *cleanup_path(char *path)
27{
28 /* Clean it up */
29 if (!memcmp(path, "./", 2)) {
30 path += 2;
31 while (*path == '/')
32 path++;
33 }
34 return path;
35}
36
108bebea
AR
37char *mksnpath(char *buf, size_t n, const char *fmt, ...)
38{
39 va_list args;
40 unsigned len;
41
42 va_start(args, fmt);
43 len = vsnprintf(buf, n, fmt, args);
44 va_end(args);
45 if (len >= n) {
9db56f71 46 strlcpy(buf, bad_path, n);
108bebea
AR
47 return buf;
48 }
49 return cleanup_path(buf);
50}
51
5b3b8fa2 52static char *vsnpath(char *buf, size_t n, const char *fmt, va_list args)
fe2d7776
AR
53{
54 const char *git_dir = get_git_dir();
fe2d7776
AR
55 size_t len;
56
57 len = strlen(git_dir);
58 if (n < len + 1)
59 goto bad;
60 memcpy(buf, git_dir, len);
61 if (len && !is_dir_sep(git_dir[len-1]))
62 buf[len++] = '/';
fe2d7776 63 len += vsnprintf(buf + len, n - len, fmt, args);
fe2d7776
AR
64 if (len >= n)
65 goto bad;
66 return cleanup_path(buf);
67bad:
9db56f71 68 strlcpy(buf, bad_path, n);
fe2d7776
AR
69 return buf;
70}
71
aba13e7c
AR
72char *git_snpath(char *buf, size_t n, const char *fmt, ...)
73{
66a51a9a 74 char *ret;
aba13e7c
AR
75 va_list args;
76 va_start(args, fmt);
66a51a9a 77 ret = vsnpath(buf, n, fmt, args);
aba13e7c 78 va_end(args);
66a51a9a 79 return ret;
aba13e7c
AR
80}
81
82char *git_pathdup(const char *fmt, ...)
83{
66a51a9a 84 char path[PATH_MAX], *ret;
aba13e7c
AR
85 va_list args;
86 va_start(args, fmt);
66a51a9a 87 ret = vsnpath(path, sizeof(path), fmt, args);
aba13e7c 88 va_end(args);
66a51a9a 89 return xstrdup(ret);
aba13e7c
AR
90}
91
21cf3227
HKNN
92char *mkpathdup(const char *fmt, ...)
93{
94 char *path;
95 struct strbuf sb = STRBUF_INIT;
96 va_list args;
97
98 va_start(args, fmt);
99 strbuf_vaddf(&sb, fmt, args);
100 va_end(args);
101 path = xstrdup(cleanup_path(sb.buf));
102
103 strbuf_release(&sb);
104 return path;
105}
106
26c8a533
LT
107char *mkpath(const char *fmt, ...)
108{
109 va_list args;
110 unsigned len;
e7676d2f 111 char *pathname = get_pathname();
26c8a533
LT
112
113 va_start(args, fmt);
114 len = vsnprintf(pathname, PATH_MAX, fmt, args);
115 va_end(args);
116 if (len >= PATH_MAX)
117 return bad_path;
118 return cleanup_path(pathname);
119}
120
121char *git_path(const char *fmt, ...)
122{
e7676d2f 123 char *pathname = get_pathname();
26c8a533 124 va_list args;
5c44252e 125 char *ret;
26c8a533 126
26c8a533 127 va_start(args, fmt);
5c44252e 128 ret = vsnpath(pathname, PATH_MAX, fmt, args);
26c8a533 129 va_end(args);
5c44252e 130 return ret;
26c8a533 131}
f2db68ed 132
21cf3227
HKNN
133void home_config_paths(char **global, char **xdg, char *file)
134{
135 char *xdg_home = getenv("XDG_CONFIG_HOME");
136 char *home = getenv("HOME");
137 char *to_free = NULL;
138
139 if (!home) {
140 if (global)
141 *global = NULL;
142 } else {
143 if (!xdg_home) {
144 to_free = mkpathdup("%s/.config", home);
145 xdg_home = to_free;
146 }
147 if (global)
148 *global = mkpathdup("%s/.gitconfig", home);
149 }
150
06b2d872
MM
151 if (xdg) {
152 if (!xdg_home)
153 *xdg = NULL;
154 else
155 *xdg = mkpathdup("%s/git/%s", xdg_home, file);
156 }
21cf3227
HKNN
157
158 free(to_free);
159}
160
0bad611b
HV
161char *git_path_submodule(const char *path, const char *fmt, ...)
162{
163 char *pathname = get_pathname();
164 struct strbuf buf = STRBUF_INIT;
165 const char *git_dir;
166 va_list args;
167 unsigned len;
168
169 len = strlen(path);
170 if (len > PATH_MAX-100)
171 return bad_path;
172
173 strbuf_addstr(&buf, path);
174 if (len && path[len-1] != '/')
175 strbuf_addch(&buf, '/');
176 strbuf_addstr(&buf, ".git");
177
13d6ec91 178 git_dir = read_gitfile(buf.buf);
0bad611b
HV
179 if (git_dir) {
180 strbuf_reset(&buf);
181 strbuf_addstr(&buf, git_dir);
182 }
183 strbuf_addch(&buf, '/');
184
185 if (buf.len >= PATH_MAX)
186 return bad_path;
187 memcpy(pathname, buf.buf, buf.len + 1);
188
189 strbuf_release(&buf);
190 len = strlen(pathname);
191
192 va_start(args, fmt);
193 len += vsnprintf(pathname + len, PATH_MAX - len, fmt, args);
194 va_end(args);
195 if (len >= PATH_MAX)
196 return bad_path;
197 return cleanup_path(pathname);
198}
f2db68ed 199
c847f537 200int validate_headref(const char *path)
0870ca7f
JH
201{
202 struct stat st;
203 char *buf, buffer[256];
c847f537 204 unsigned char sha1[20];
0104ca09
HO
205 int fd;
206 ssize_t len;
0870ca7f
JH
207
208 if (lstat(path, &st) < 0)
209 return -1;
210
211 /* Make sure it is a "refs/.." symlink */
212 if (S_ISLNK(st.st_mode)) {
213 len = readlink(path, buffer, sizeof(buffer)-1);
222b1673 214 if (len >= 5 && !memcmp("refs/", buffer, 5))
0870ca7f
JH
215 return 0;
216 return -1;
217 }
218
219 /*
220 * Anything else, just open it and try to see if it is a symbolic ref.
221 */
222 fd = open(path, O_RDONLY);
223 if (fd < 0)
224 return -1;
93d26e4c 225 len = read_in_full(fd, buffer, sizeof(buffer)-1);
0870ca7f
JH
226 close(fd);
227
228 /*
229 * Is it a symbolic ref?
230 */
c847f537 231 if (len < 4)
0870ca7f 232 return -1;
c847f537
JH
233 if (!memcmp("ref:", buffer, 4)) {
234 buf = buffer + 4;
235 len -= 4;
236 while (len && isspace(*buf))
237 buf++, len--;
222b1673 238 if (len >= 5 && !memcmp("refs/", buf, 5))
c847f537
JH
239 return 0;
240 }
241
242 /*
243 * Is this a detached HEAD?
244 */
245 if (!get_sha1_hex(buffer, sha1))
0870ca7f 246 return 0;
c847f537 247
0870ca7f
JH
248 return -1;
249}
250
395de250 251static struct passwd *getpw_str(const char *username, size_t len)
54f4b874 252{
d79374c7 253 struct passwd *pw;
5c0b13f8 254 char *username_z = xmemdupz(username, len);
395de250
MM
255 pw = getpwnam(username_z);
256 free(username_z);
257 return pw;
258}
54f4b874 259
395de250
MM
260/*
261 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
262 * then it is a newly allocated string. Returns NULL on getpw failure or
263 * if path is NULL.
264 */
265char *expand_user_path(const char *path)
266{
267 struct strbuf user_path = STRBUF_INIT;
395de250
MM
268 const char *to_copy = path;
269
270 if (path == NULL)
271 goto return_null;
272 if (path[0] == '~') {
53ec551c 273 const char *first_slash = strchrnul(path, '/');
395de250
MM
274 const char *username = path + 1;
275 size_t username_len = first_slash - username;
df2a79f4
MM
276 if (username_len == 0) {
277 const char *home = getenv("HOME");
79bf1490
JN
278 if (!home)
279 goto return_null;
cedc61a9 280 strbuf_addstr(&user_path, home);
df2a79f4
MM
281 } else {
282 struct passwd *pw = getpw_str(username, username_len);
283 if (!pw)
284 goto return_null;
cedc61a9 285 strbuf_addstr(&user_path, pw->pw_dir);
54f4b874 286 }
395de250 287 to_copy = first_slash;
d79374c7 288 }
cedc61a9 289 strbuf_addstr(&user_path, to_copy);
395de250
MM
290 return strbuf_detach(&user_path, NULL);
291return_null:
292 strbuf_release(&user_path);
293 return NULL;
54f4b874
AE
294}
295
d79374c7
JH
296/*
297 * First, one directory to try is determined by the following algorithm.
298 *
299 * (0) If "strict" is given, the path is used as given and no DWIM is
300 * done. Otherwise:
301 * (1) "~/path" to mean path under the running user's home directory;
302 * (2) "~user/path" to mean path under named user's home directory;
303 * (3) "relative/path" to mean cwd relative directory; or
304 * (4) "/absolute/path" to mean absolute directory.
305 *
306 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
307 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
308 * what we try.
309 *
310 * Second, we try chdir() to that. Upon failure, we return NULL.
311 *
312 * Then, we try if the current directory is a valid git repository.
313 * Upon failure, we return NULL.
314 *
315 * If all goes well, we return the directory we used to chdir() (but
316 * before ~user is expanded), avoiding getcwd() resolving symbolic
317 * links. User relative paths are also returned as they are given,
318 * except DWIM suffixing.
319 */
1c64b48e 320const char *enter_repo(const char *path, int strict)
54f4b874 321{
d79374c7
JH
322 static char used_path[PATH_MAX];
323 static char validated_path[PATH_MAX];
324
325 if (!path)
54f4b874
AE
326 return NULL;
327
d79374c7
JH
328 if (!strict) {
329 static const char *suffix[] = {
b3256eb8 330 "/.git", "", ".git/.git", ".git", NULL,
d79374c7 331 };
03106768 332 const char *gitfile;
d79374c7
JH
333 int len = strlen(path);
334 int i;
1c64b48e 335 while ((1 < len) && (path[len-1] == '/'))
d79374c7 336 len--;
1c64b48e 337
d79374c7 338 if (PATH_MAX <= len)
54f4b874 339 return NULL;
1c64b48e
EFL
340 strncpy(used_path, path, len); used_path[len] = 0 ;
341 strcpy(validated_path, used_path);
342
343 if (used_path[0] == '~') {
344 char *newpath = expand_user_path(used_path);
395de250
MM
345 if (!newpath || (PATH_MAX - 10 < strlen(newpath))) {
346 free(newpath);
d79374c7 347 return NULL;
395de250
MM
348 }
349 /*
350 * Copy back into the static buffer. A pity
351 * since newpath was not bounded, but other
352 * branches of the if are limited by PATH_MAX
353 * anyway.
354 */
355 strcpy(used_path, newpath); free(newpath);
d79374c7
JH
356 }
357 else if (PATH_MAX - 10 < len)
358 return NULL;
1c64b48e 359 len = strlen(used_path);
d79374c7 360 for (i = 0; suffix[i]; i++) {
b3256eb8 361 struct stat st;
1c64b48e 362 strcpy(used_path + len, suffix[i]);
b3256eb8
JK
363 if (!stat(used_path, &st) &&
364 (S_ISREG(st.st_mode) ||
365 (S_ISDIR(st.st_mode) && is_git_directory(used_path)))) {
d79374c7
JH
366 strcat(validated_path, suffix[i]);
367 break;
368 }
369 }
03106768
PH
370 if (!suffix[i])
371 return NULL;
372 gitfile = read_gitfile(used_path) ;
373 if (gitfile)
374 strcpy(used_path, gitfile);
375 if (chdir(used_path))
0870ca7f 376 return NULL;
d79374c7 377 path = validated_path;
0870ca7f 378 }
d79374c7
JH
379 else if (chdir(path))
380 return NULL;
54f4b874 381
d79374c7 382 if (access("objects", X_OK) == 0 && access("refs", X_OK) == 0 &&
c847f537 383 validate_headref("HEAD") == 0) {
717c3972 384 set_git_dir(".");
1644162a 385 check_repository_format();
d79374c7 386 return path;
54f4b874
AE
387 }
388
389 return NULL;
390}
138086a7 391
cbe43b84 392static int calc_shared_perm(int mode)
138086a7 393{
cbe43b84 394 int tweak;
138086a7 395
5a688fe4 396 if (shared_repository < 0)
cbe43b84 397 tweak = -shared_repository;
5a688fe4 398 else
cbe43b84 399 tweak = shared_repository;
5a688fe4
JH
400
401 if (!(mode & S_IWUSR))
402 tweak &= ~0222;
403 if (mode & S_IXUSR)
404 /* Copy read bits to execute bits */
405 tweak |= (tweak & 0444) >> 2;
406 if (shared_repository < 0)
407 mode = (mode & ~0777) | tweak;
408 else
8c6202d8 409 mode |= tweak;
06cbe855 410
cbe43b84
TB
411 return mode;
412}
413
414
415int adjust_shared_perm(const char *path)
416{
417 int old_mode, new_mode;
418
419 if (!shared_repository)
420 return 0;
421 if (get_st_mode_bits(path, &old_mode) < 0)
422 return -1;
423
424 new_mode = calc_shared_perm(old_mode);
425 if (S_ISDIR(old_mode)) {
06cbe855 426 /* Copy read bits to execute bits */
cbe43b84
TB
427 new_mode |= (new_mode & 0444) >> 2;
428 new_mode |= FORCE_DIR_SET_GID;
06cbe855
HO
429 }
430
cbe43b84
TB
431 if (((old_mode ^ new_mode) & ~S_IFMT) &&
432 chmod(path, (new_mode & ~S_IFMT)) < 0)
138086a7
JH
433 return -2;
434 return 0;
435}
e5392c51 436
7fbd4221
JX
437static int have_same_root(const char *path1, const char *path2)
438{
439 int is_abs1, is_abs2;
440
441 is_abs1 = is_absolute_path(path1);
442 is_abs2 = is_absolute_path(path2);
443 return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
444 (!is_abs1 && !is_abs2);
445}
446
e02ca72f
JX
447/*
448 * Give path as relative to prefix.
449 *
450 * The strbuf may or may not be used, so do not assume it contains the
451 * returned path.
452 */
453const char *relative_path(const char *in, const char *prefix,
454 struct strbuf *sb)
044bbbcb 455{
e02ca72f
JX
456 int in_len = in ? strlen(in) : 0;
457 int prefix_len = prefix ? strlen(prefix) : 0;
458 int in_off = 0;
459 int prefix_off = 0;
288123f0
JH
460 int i = 0, j = 0;
461
e02ca72f
JX
462 if (!in_len)
463 return "./";
464 else if (!prefix_len)
465 return in;
466
7fbd4221
JX
467 if (have_same_root(in, prefix)) {
468 /* bypass dos_drive, for "c:" is identical to "C:" */
469 if (has_dos_drive_prefix(in)) {
470 i = 2;
471 j = 2;
472 }
473 } else {
474 return in;
475 }
476
e02ca72f
JX
477 while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
478 if (is_dir_sep(prefix[i])) {
479 while (is_dir_sep(prefix[i]))
288123f0 480 i++;
e02ca72f
JX
481 while (is_dir_sep(in[j]))
482 j++;
483 prefix_off = i;
484 in_off = j;
485 } else {
486 i++;
487 j++;
488 }
489 }
490
491 if (
492 /* "prefix" seems like prefix of "in" */
493 i >= prefix_len &&
494 /*
495 * but "/foo" is not a prefix of "/foobar"
496 * (i.e. prefix not end with '/')
497 */
498 prefix_off < prefix_len) {
499 if (j >= in_len) {
500 /* in="/a/b", prefix="/a/b" */
501 in_off = in_len;
502 } else if (is_dir_sep(in[j])) {
503 /* in="/a/b/c", prefix="/a/b" */
504 while (is_dir_sep(in[j]))
288123f0 505 j++;
e02ca72f
JX
506 in_off = j;
507 } else {
508 /* in="/a/bbb/c", prefix="/a/b" */
509 i = prefix_off;
510 }
511 } else if (
512 /* "in" is short than "prefix" */
513 j >= in_len &&
514 /* "in" not end with '/' */
515 in_off < in_len) {
516 if (is_dir_sep(prefix[i])) {
517 /* in="/a/b", prefix="/a/b/c/" */
518 while (is_dir_sep(prefix[i]))
519 i++;
520 in_off = in_len;
521 }
522 }
523 in += in_off;
524 in_len -= in_off;
525
526 if (i >= prefix_len) {
527 if (!in_len)
528 return "./";
529 else
530 return in;
531 }
532
533 strbuf_reset(sb);
534 strbuf_grow(sb, in_len);
535
536 while (i < prefix_len) {
537 if (is_dir_sep(prefix[i])) {
538 strbuf_addstr(sb, "../");
539 while (is_dir_sep(prefix[i]))
540 i++;
288123f0 541 continue;
288123f0
JH
542 }
543 i++;
288123f0 544 }
e02ca72f
JX
545 if (!is_dir_sep(prefix[prefix_len - 1]))
546 strbuf_addstr(sb, "../");
547
548 strbuf_addstr(sb, in);
549
550 return sb->buf;
044bbbcb 551}
ae299be0 552
41894ae3
JX
553/*
554 * A simpler implementation of relative_path
555 *
556 * Get relative path by removing "prefix" from "in". This function
557 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
558 * to increase performance when traversing the path to work_tree.
559 */
560const char *remove_leading_path(const char *in, const char *prefix)
561{
562 static char buf[PATH_MAX + 1];
563 int i = 0, j = 0;
564
565 if (!prefix || !prefix[0])
566 return in;
567 while (prefix[i]) {
568 if (is_dir_sep(prefix[i])) {
569 if (!is_dir_sep(in[j]))
570 return in;
571 while (is_dir_sep(prefix[i]))
572 i++;
573 while (is_dir_sep(in[j]))
574 j++;
575 continue;
576 } else if (in[j] != prefix[i]) {
577 return in;
578 }
579 i++;
580 j++;
581 }
582 if (
583 /* "/foo" is a prefix of "/foo" */
584 in[j] &&
585 /* "/foo" is not a prefix of "/foobar" */
586 !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
587 )
588 return in;
589 while (is_dir_sep(in[j]))
590 j++;
591 if (!in[j])
592 strcpy(buf, ".");
593 else
594 strcpy(buf, in + j);
595 return buf;
596}
597
ae299be0 598/*
f2a782b8 599 * It is okay if dst == src, but they should not overlap otherwise.
ae299be0 600 *
f2a782b8
JS
601 * Performs the following normalizations on src, storing the result in dst:
602 * - Ensures that components are separated by '/' (Windows only)
603 * - Squashes sequences of '/'.
ae299be0
DR
604 * - Removes "." components.
605 * - Removes ".." components, and the components the precede them.
f2a782b8
JS
606 * Returns failure (non-zero) if a ".." component appears as first path
607 * component anytime during the normalization. Otherwise, returns success (0).
ae299be0
DR
608 *
609 * Note that this function is purely textual. It does not follow symlinks,
610 * verify the existence of the path, or make any system calls.
645a29c4
NTND
611 *
612 * prefix_len != NULL is for a specific case of prefix_pathspec():
613 * assume that src == dst and src[0..prefix_len-1] is already
614 * normalized, any time "../" eats up to the prefix_len part,
615 * prefix_len is reduced. In the end prefix_len is the remaining
616 * prefix that has not been overridden by user pathspec.
ae299be0 617 */
645a29c4 618int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
ae299be0 619{
f3cad0ad 620 char *dst0;
ae299be0 621
f3cad0ad
JS
622 if (has_dos_drive_prefix(src)) {
623 *dst++ = *src++;
624 *dst++ = *src++;
ae299be0 625 }
f3cad0ad 626 dst0 = dst;
ae299be0 627
f3cad0ad 628 if (is_dir_sep(*src)) {
ae299be0 629 *dst++ = '/';
f3cad0ad
JS
630 while (is_dir_sep(*src))
631 src++;
632 }
633
634 for (;;) {
635 char c = *src;
636
637 /*
638 * A path component that begins with . could be
639 * special:
640 * (1) "." and ends -- ignore and terminate.
641 * (2) "./" -- ignore them, eat slash and continue.
642 * (3) ".." and ends -- strip one and terminate.
643 * (4) "../" -- strip one, eat slash and continue.
644 */
645 if (c == '.') {
646 if (!src[1]) {
647 /* (1) */
648 src++;
649 } else if (is_dir_sep(src[1])) {
650 /* (2) */
651 src += 2;
652 while (is_dir_sep(*src))
653 src++;
654 continue;
655 } else if (src[1] == '.') {
656 if (!src[2]) {
657 /* (3) */
658 src += 2;
659 goto up_one;
660 } else if (is_dir_sep(src[2])) {
661 /* (4) */
662 src += 3;
663 while (is_dir_sep(*src))
664 src++;
665 goto up_one;
666 }
667 }
668 }
ae299be0 669
f3cad0ad
JS
670 /* copy up to the next '/', and eat all '/' */
671 while ((c = *src++) != '\0' && !is_dir_sep(c))
672 *dst++ = c;
673 if (is_dir_sep(c)) {
674 *dst++ = '/';
675 while (is_dir_sep(c))
676 c = *src++;
677 src--;
678 } else if (!c)
679 break;
680 continue;
681
682 up_one:
683 /*
684 * dst0..dst is prefix portion, and dst[-1] is '/';
685 * go up one level.
686 */
f42302b4
JS
687 dst--; /* go to trailing '/' */
688 if (dst <= dst0)
f3cad0ad 689 return -1;
f42302b4
JS
690 /* Windows: dst[-1] cannot be backslash anymore */
691 while (dst0 < dst && dst[-1] != '/')
692 dst--;
645a29c4
NTND
693 if (prefix_len && *prefix_len > dst - dst0)
694 *prefix_len = dst - dst0;
f3cad0ad 695 }
ae299be0 696 *dst = '\0';
f3cad0ad 697 return 0;
ae299be0 698}
0454dd93 699
645a29c4
NTND
700int normalize_path_copy(char *dst, const char *src)
701{
702 return normalize_path_copy_len(dst, src, NULL);
703}
704
0454dd93
DR
705/*
706 * path = Canonical absolute path
9e2326c7
MH
707 * prefixes = string_list containing normalized, absolute paths without
708 * trailing slashes (except for the root directory, which is denoted by "/").
0454dd93 709 *
9e2326c7 710 * Determines, for each path in prefixes, whether the "prefix"
0454dd93
DR
711 * is an ancestor directory of path. Returns the length of the longest
712 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
31171d9e
MH
713 * is an ancestor. (Note that this means 0 is returned if prefixes is
714 * ["/"].) "/foo" is not considered an ancestor of "/foobar". Directories
0454dd93
DR
715 * are not considered to be their own ancestors. path must be in a
716 * canonical form: empty components, or "." or ".." components are not
9e2326c7 717 * allowed.
0454dd93 718 */
31171d9e 719int longest_ancestor_length(const char *path, struct string_list *prefixes)
0454dd93 720{
a5ccdbe4 721 int i, max_len = -1;
0454dd93 722
31171d9e 723 if (!strcmp(path, "/"))
0454dd93
DR
724 return -1;
725
31171d9e
MH
726 for (i = 0; i < prefixes->nr; i++) {
727 const char *ceil = prefixes->items[i].string;
a5ccdbe4
MH
728 int len = strlen(ceil);
729
9e2326c7
MH
730 if (len == 1 && ceil[0] == '/')
731 len = 0; /* root matches anything, with length 0 */
732 else if (!strncmp(path, ceil, len) && path[len] == '/')
733 ; /* match of length len */
734 else
735 continue; /* no match */
0454dd93 736
9e2326c7 737 if (len > max_len)
0454dd93 738 max_len = len;
0454dd93
DR
739 }
740
741 return max_len;
742}
4fcc86b0
JS
743
744/* strip arbitrary amount of directory separators at end of path */
745static inline int chomp_trailing_dir_sep(const char *path, int len)
746{
747 while (len && is_dir_sep(path[len - 1]))
748 len--;
749 return len;
750}
751
752/*
753 * If path ends with suffix (complete path components), returns the
754 * part before suffix (sans trailing directory separators).
755 * Otherwise returns NULL.
756 */
757char *strip_path_suffix(const char *path, const char *suffix)
758{
759 int path_len = strlen(path), suffix_len = strlen(suffix);
760
761 while (suffix_len) {
762 if (!path_len)
763 return NULL;
764
765 if (is_dir_sep(path[path_len - 1])) {
766 if (!is_dir_sep(suffix[suffix_len - 1]))
767 return NULL;
768 path_len = chomp_trailing_dir_sep(path, path_len);
769 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
770 }
771 else if (path[--path_len] != suffix[--suffix_len])
772 return NULL;
773 }
774
775 if (path_len && !is_dir_sep(path[path_len - 1]))
776 return NULL;
777 return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
778}
34b6cb8b
SP
779
780int daemon_avoid_alias(const char *p)
781{
782 int sl, ndot;
783
784 /*
785 * This resurrects the belts and suspenders paranoia check by HPA
786 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
9517e6b8 787 * does not do getcwd() based path canonicalization.
34b6cb8b
SP
788 *
789 * sl becomes true immediately after seeing '/' and continues to
790 * be true as long as dots continue after that without intervening
791 * non-dot character.
792 */
793 if (!p || (*p != '/' && *p != '~'))
794 return -1;
795 sl = 1; ndot = 0;
796 p++;
797
798 while (1) {
799 char ch = *p++;
800 if (sl) {
801 if (ch == '.')
802 ndot++;
803 else if (ch == '/') {
804 if (ndot < 3)
805 /* reject //, /./ and /../ */
806 return -1;
807 ndot = 0;
808 }
809 else if (ch == 0) {
810 if (0 < ndot && ndot < 3)
811 /* reject /.$ and /..$ */
812 return -1;
813 return 0;
814 }
815 else
816 sl = ndot = 0;
817 }
818 else if (ch == 0)
819 return 0;
820 else if (ch == '/') {
821 sl = 1;
822 ndot = 0;
823 }
824 }
825}