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