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