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