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