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