]> git.ipfire.org Git - thirdparty/git.git/blame - path.c
Move gitmkstemps to path.c
[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
HE
124
125
126/* git_mkstemp() - create tmp file honoring TMPDIR variable */
127int git_mkstemp(char *path, size_t len, const char *template)
128{
e7a7be88
JH
129 const char *tmp;
130 size_t n;
131
132 tmp = getenv("TMPDIR");
133 if (!tmp)
134 tmp = "/tmp";
135 n = snprintf(path, len, "%s/%s", tmp, template);
136 if (len <= n) {
137 errno = ENAMETOOLONG;
138 return -1;
35c3c629 139 }
f2db68ed
HE
140 return mkstemp(path);
141}
142
003b33a8
DA
143/* git_mkstemps() - create tmp file with suffix honoring TMPDIR variable. */
144int git_mkstemps(char *path, size_t len, const char *template, int suffix_len)
145{
146 const char *tmp;
147 size_t n;
148
149 tmp = getenv("TMPDIR");
150 if (!tmp)
151 tmp = "/tmp";
152 n = snprintf(path, len, "%s/%s", tmp, template);
153 if (len <= n) {
154 errno = ENAMETOOLONG;
155 return -1;
156 }
157 return mkstemps(path, suffix_len);
158}
f2db68ed 159
00787ed5
MM
160/* Adapted from libiberty's mkstemp.c. */
161
162#undef TMP_MAX
163#define TMP_MAX 16384
164
165int gitmkstemps(char *pattern, int suffix_len)
166{
167 static const char letters[] =
168 "abcdefghijklmnopqrstuvwxyz"
169 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
170 "0123456789";
171 static const int num_letters = 62;
172 uint64_t value;
173 struct timeval tv;
174 char *template;
175 size_t len;
176 int fd, count;
177
178 len = strlen(pattern);
179
180 if (len < 6 + suffix_len) {
181 errno = EINVAL;
182 return -1;
183 }
184
185 if (strncmp(&pattern[len - 6 - suffix_len], "XXXXXX", 6)) {
186 errno = EINVAL;
187 return -1;
188 }
189
190 /*
191 * Replace pattern's XXXXXX characters with randomness.
192 * Try TMP_MAX different filenames.
193 */
194 gettimeofday(&tv, NULL);
195 value = ((size_t)(tv.tv_usec << 16)) ^ tv.tv_sec ^ getpid();
196 template = &pattern[len - 6 - suffix_len];
197 for (count = 0; count < TMP_MAX; ++count) {
198 uint64_t v = value;
199 /* Fill in the random bits. */
200 template[0] = letters[v % num_letters]; v /= num_letters;
201 template[1] = letters[v % num_letters]; v /= num_letters;
202 template[2] = letters[v % num_letters]; v /= num_letters;
203 template[3] = letters[v % num_letters]; v /= num_letters;
204 template[4] = letters[v % num_letters]; v /= num_letters;
205 template[5] = letters[v % num_letters]; v /= num_letters;
206
207 fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, 0600);
208 if (fd > 0)
209 return fd;
210 /*
211 * Fatal error (EPERM, ENOSPC etc).
212 * It doesn't make sense to loop.
213 */
214 if (errno != EEXIST)
215 break;
216 /*
217 * This is a random value. It is only necessary that
218 * the next TMP_MAX values generated by adding 7777 to
219 * VALUE are different with (module 2^32).
220 */
221 value += 7777;
222 }
223 /* We return the null string if we can't find a unique file name. */
224 pattern[0] = '\0';
225 errno = EINVAL;
226 return -1;
227}
228
c847f537 229int validate_headref(const char *path)
0870ca7f
JH
230{
231 struct stat st;
232 char *buf, buffer[256];
c847f537 233 unsigned char sha1[20];
0104ca09
HO
234 int fd;
235 ssize_t len;
0870ca7f
JH
236
237 if (lstat(path, &st) < 0)
238 return -1;
239
240 /* Make sure it is a "refs/.." symlink */
241 if (S_ISLNK(st.st_mode)) {
242 len = readlink(path, buffer, sizeof(buffer)-1);
222b1673 243 if (len >= 5 && !memcmp("refs/", buffer, 5))
0870ca7f
JH
244 return 0;
245 return -1;
246 }
247
248 /*
249 * Anything else, just open it and try to see if it is a symbolic ref.
250 */
251 fd = open(path, O_RDONLY);
252 if (fd < 0)
253 return -1;
93d26e4c 254 len = read_in_full(fd, buffer, sizeof(buffer)-1);
0870ca7f
JH
255 close(fd);
256
257 /*
258 * Is it a symbolic ref?
259 */
c847f537 260 if (len < 4)
0870ca7f 261 return -1;
c847f537
JH
262 if (!memcmp("ref:", buffer, 4)) {
263 buf = buffer + 4;
264 len -= 4;
265 while (len && isspace(*buf))
266 buf++, len--;
222b1673 267 if (len >= 5 && !memcmp("refs/", buf, 5))
c847f537
JH
268 return 0;
269 }
270
271 /*
272 * Is this a detached HEAD?
273 */
274 if (!get_sha1_hex(buffer, sha1))
0870ca7f 275 return 0;
c847f537 276
0870ca7f
JH
277 return -1;
278}
279
395de250 280static struct passwd *getpw_str(const char *username, size_t len)
54f4b874 281{
d79374c7 282 struct passwd *pw;
395de250
MM
283 char *username_z = xmalloc(len + 1);
284 memcpy(username_z, username, len);
285 username_z[len] = '\0';
286 pw = getpwnam(username_z);
287 free(username_z);
288 return pw;
289}
54f4b874 290
395de250
MM
291/*
292 * Return a string with ~ and ~user expanded via getpw*. If buf != NULL,
293 * then it is a newly allocated string. Returns NULL on getpw failure or
294 * if path is NULL.
295 */
296char *expand_user_path(const char *path)
297{
298 struct strbuf user_path = STRBUF_INIT;
299 const char *first_slash = strchrnul(path, '/');
300 const char *to_copy = path;
301
302 if (path == NULL)
303 goto return_null;
304 if (path[0] == '~') {
305 const char *username = path + 1;
306 size_t username_len = first_slash - username;
df2a79f4
MM
307 if (username_len == 0) {
308 const char *home = getenv("HOME");
309 strbuf_add(&user_path, home, strlen(home));
310 } else {
311 struct passwd *pw = getpw_str(username, username_len);
312 if (!pw)
313 goto return_null;
314 strbuf_add(&user_path, pw->pw_dir, strlen(pw->pw_dir));
54f4b874 315 }
395de250 316 to_copy = first_slash;
d79374c7 317 }
395de250
MM
318 strbuf_add(&user_path, to_copy, strlen(to_copy));
319 return strbuf_detach(&user_path, NULL);
320return_null:
321 strbuf_release(&user_path);
322 return NULL;
54f4b874
AE
323}
324
d79374c7
JH
325/*
326 * First, one directory to try is determined by the following algorithm.
327 *
328 * (0) If "strict" is given, the path is used as given and no DWIM is
329 * done. Otherwise:
330 * (1) "~/path" to mean path under the running user's home directory;
331 * (2) "~user/path" to mean path under named user's home directory;
332 * (3) "relative/path" to mean cwd relative directory; or
333 * (4) "/absolute/path" to mean absolute directory.
334 *
335 * Unless "strict" is given, we try access() for existence of "%s.git/.git",
336 * "%s/.git", "%s.git", "%s" in this order. The first one that exists is
337 * what we try.
338 *
339 * Second, we try chdir() to that. Upon failure, we return NULL.
340 *
341 * Then, we try if the current directory is a valid git repository.
342 * Upon failure, we return NULL.
343 *
344 * If all goes well, we return the directory we used to chdir() (but
345 * before ~user is expanded), avoiding getcwd() resolving symbolic
346 * links. User relative paths are also returned as they are given,
347 * except DWIM suffixing.
348 */
54f4b874
AE
349char *enter_repo(char *path, int strict)
350{
d79374c7
JH
351 static char used_path[PATH_MAX];
352 static char validated_path[PATH_MAX];
353
354 if (!path)
54f4b874
AE
355 return NULL;
356
d79374c7
JH
357 if (!strict) {
358 static const char *suffix[] = {
359 ".git/.git", "/.git", ".git", "", NULL,
360 };
361 int len = strlen(path);
362 int i;
363 while ((1 < len) && (path[len-1] == '/')) {
364 path[len-1] = 0;
365 len--;
366 }
367 if (PATH_MAX <= len)
54f4b874 368 return NULL;
d79374c7 369 if (path[0] == '~') {
395de250
MM
370 char *newpath = expand_user_path(path);
371 if (!newpath || (PATH_MAX - 10 < strlen(newpath))) {
372 free(newpath);
d79374c7 373 return NULL;
395de250
MM
374 }
375 /*
376 * Copy back into the static buffer. A pity
377 * since newpath was not bounded, but other
378 * branches of the if are limited by PATH_MAX
379 * anyway.
380 */
381 strcpy(used_path, newpath); free(newpath);
d79374c7
JH
382 strcpy(validated_path, path);
383 path = used_path;
384 }
385 else if (PATH_MAX - 10 < len)
386 return NULL;
387 else {
388 path = strcpy(used_path, path);
389 strcpy(validated_path, path);
390 }
391 len = strlen(path);
392 for (i = 0; suffix[i]; i++) {
393 strcpy(path + len, suffix[i]);
394 if (!access(path, F_OK)) {
395 strcat(validated_path, suffix[i]);
396 break;
397 }
398 }
399 if (!suffix[i] || chdir(path))
0870ca7f 400 return NULL;
d79374c7 401 path = validated_path;
0870ca7f 402 }
d79374c7
JH
403 else if (chdir(path))
404 return NULL;
54f4b874 405
d79374c7 406 if (access("objects", X_OK) == 0 && access("refs", X_OK) == 0 &&
c847f537 407 validate_headref("HEAD") == 0) {
7627943a 408 setenv(GIT_DIR_ENVIRONMENT, ".", 1);
1644162a 409 check_repository_format();
d79374c7 410 return path;
54f4b874
AE
411 }
412
413 return NULL;
414}
138086a7 415
17e61b82 416int set_shared_perm(const char *path, int mode)
138086a7
JH
417{
418 struct stat st;
17e61b82 419 int tweak, shared, orig_mode;
138086a7 420
17e61b82
JH
421 if (!shared_repository) {
422 if (mode)
423 return chmod(path, mode & ~S_IFMT);
138086a7 424 return 0;
17e61b82
JH
425 }
426 if (!mode) {
427 if (lstat(path, &st) < 0)
428 return -1;
429 mode = st.st_mode;
430 orig_mode = mode;
431 } else
432 orig_mode = 0;
5a688fe4
JH
433 if (shared_repository < 0)
434 shared = -shared_repository;
435 else
436 shared = shared_repository;
437 tweak = shared;
438
439 if (!(mode & S_IWUSR))
440 tweak &= ~0222;
441 if (mode & S_IXUSR)
442 /* Copy read bits to execute bits */
443 tweak |= (tweak & 0444) >> 2;
444 if (shared_repository < 0)
445 mode = (mode & ~0777) | tweak;
446 else
8c6202d8 447 mode |= tweak;
06cbe855
HO
448
449 if (S_ISDIR(mode)) {
06cbe855 450 /* Copy read bits to execute bits */
5a688fe4
JH
451 mode |= (shared & 0444) >> 2;
452 mode |= FORCE_DIR_SET_GID;
06cbe855
HO
453 }
454
5a688fe4 455 if (((shared_repository < 0
17e61b82
JH
456 ? (orig_mode & (FORCE_DIR_SET_GID | 0777))
457 : (orig_mode & mode)) != mode) &&
458 chmod(path, (mode & ~S_IFMT)) < 0)
138086a7
JH
459 return -2;
460 return 0;
461}
e5392c51 462
044bbbcb
LT
463const char *make_relative_path(const char *abs, const char *base)
464{
465 static char buf[PATH_MAX + 1];
288123f0
JH
466 int i = 0, j = 0;
467
468 if (!base || !base[0])
044bbbcb 469 return abs;
288123f0
JH
470 while (base[i]) {
471 if (is_dir_sep(base[i])) {
472 if (!is_dir_sep(abs[j]))
473 return abs;
474 while (is_dir_sep(base[i]))
475 i++;
476 while (is_dir_sep(abs[j]))
477 j++;
478 continue;
479 } else if (abs[j] != base[i]) {
480 return abs;
481 }
482 i++;
483 j++;
484 }
485 if (
486 /* "/foo" is a prefix of "/foo" */
487 abs[j] &&
488 /* "/foo" is not a prefix of "/foobar" */
489 !is_dir_sep(base[i-1]) && !is_dir_sep(abs[j])
490 )
044bbbcb 491 return abs;
288123f0
JH
492 while (is_dir_sep(abs[j]))
493 j++;
494 if (!abs[j])
495 strcpy(buf, ".");
496 else
497 strcpy(buf, abs + j);
044bbbcb
LT
498 return buf;
499}
ae299be0
DR
500
501/*
f2a782b8 502 * It is okay if dst == src, but they should not overlap otherwise.
ae299be0 503 *
f2a782b8
JS
504 * Performs the following normalizations on src, storing the result in dst:
505 * - Ensures that components are separated by '/' (Windows only)
506 * - Squashes sequences of '/'.
ae299be0
DR
507 * - Removes "." components.
508 * - Removes ".." components, and the components the precede them.
f2a782b8
JS
509 * Returns failure (non-zero) if a ".." component appears as first path
510 * component anytime during the normalization. Otherwise, returns success (0).
ae299be0
DR
511 *
512 * Note that this function is purely textual. It does not follow symlinks,
513 * verify the existence of the path, or make any system calls.
514 */
f3cad0ad 515int normalize_path_copy(char *dst, const char *src)
ae299be0 516{
f3cad0ad 517 char *dst0;
ae299be0 518
f3cad0ad
JS
519 if (has_dos_drive_prefix(src)) {
520 *dst++ = *src++;
521 *dst++ = *src++;
ae299be0 522 }
f3cad0ad 523 dst0 = dst;
ae299be0 524
f3cad0ad 525 if (is_dir_sep(*src)) {
ae299be0 526 *dst++ = '/';
f3cad0ad
JS
527 while (is_dir_sep(*src))
528 src++;
529 }
530
531 for (;;) {
532 char c = *src;
533
534 /*
535 * A path component that begins with . could be
536 * special:
537 * (1) "." and ends -- ignore and terminate.
538 * (2) "./" -- ignore them, eat slash and continue.
539 * (3) ".." and ends -- strip one and terminate.
540 * (4) "../" -- strip one, eat slash and continue.
541 */
542 if (c == '.') {
543 if (!src[1]) {
544 /* (1) */
545 src++;
546 } else if (is_dir_sep(src[1])) {
547 /* (2) */
548 src += 2;
549 while (is_dir_sep(*src))
550 src++;
551 continue;
552 } else if (src[1] == '.') {
553 if (!src[2]) {
554 /* (3) */
555 src += 2;
556 goto up_one;
557 } else if (is_dir_sep(src[2])) {
558 /* (4) */
559 src += 3;
560 while (is_dir_sep(*src))
561 src++;
562 goto up_one;
563 }
564 }
565 }
ae299be0 566
f3cad0ad
JS
567 /* copy up to the next '/', and eat all '/' */
568 while ((c = *src++) != '\0' && !is_dir_sep(c))
569 *dst++ = c;
570 if (is_dir_sep(c)) {
571 *dst++ = '/';
572 while (is_dir_sep(c))
573 c = *src++;
574 src--;
575 } else if (!c)
576 break;
577 continue;
578
579 up_one:
580 /*
581 * dst0..dst is prefix portion, and dst[-1] is '/';
582 * go up one level.
583 */
f42302b4
JS
584 dst--; /* go to trailing '/' */
585 if (dst <= dst0)
f3cad0ad 586 return -1;
f42302b4
JS
587 /* Windows: dst[-1] cannot be backslash anymore */
588 while (dst0 < dst && dst[-1] != '/')
589 dst--;
f3cad0ad 590 }
ae299be0 591 *dst = '\0';
f3cad0ad 592 return 0;
ae299be0 593}
0454dd93
DR
594
595/*
596 * path = Canonical absolute path
597 * prefix_list = Colon-separated list of absolute paths
598 *
2860b57a 599 * Determines, for each path in prefix_list, whether the "prefix" really
0454dd93
DR
600 * is an ancestor directory of path. Returns the length of the longest
601 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
602 * is an ancestor. (Note that this means 0 is returned if prefix_list is
603 * "/".) "/foo" is not considered an ancestor of "/foobar". Directories
604 * are not considered to be their own ancestors. path must be in a
605 * canonical form: empty components, or "." or ".." components are not
606 * allowed. prefix_list may be null, which is like "".
607 */
608int longest_ancestor_length(const char *path, const char *prefix_list)
609{
610 char buf[PATH_MAX+1];
611 const char *ceil, *colon;
612 int len, max_len = -1;
613
614 if (prefix_list == NULL || !strcmp(path, "/"))
615 return -1;
616
617 for (colon = ceil = prefix_list; *colon; ceil = colon+1) {
43a7ddb5 618 for (colon = ceil; *colon && *colon != PATH_SEP; colon++);
0454dd93
DR
619 len = colon - ceil;
620 if (len == 0 || len > PATH_MAX || !is_absolute_path(ceil))
621 continue;
622 strlcpy(buf, ceil, len+1);
43a7ddb5
RS
623 if (normalize_path_copy(buf, buf) < 0)
624 continue;
625 len = strlen(buf);
626 if (len > 0 && buf[len-1] == '/')
627 buf[--len] = '\0';
0454dd93
DR
628
629 if (!strncmp(path, buf, len) &&
630 path[len] == '/' &&
631 len > max_len) {
632 max_len = len;
633 }
634 }
635
636 return max_len;
637}
4fcc86b0
JS
638
639/* strip arbitrary amount of directory separators at end of path */
640static inline int chomp_trailing_dir_sep(const char *path, int len)
641{
642 while (len && is_dir_sep(path[len - 1]))
643 len--;
644 return len;
645}
646
647/*
648 * If path ends with suffix (complete path components), returns the
649 * part before suffix (sans trailing directory separators).
650 * Otherwise returns NULL.
651 */
652char *strip_path_suffix(const char *path, const char *suffix)
653{
654 int path_len = strlen(path), suffix_len = strlen(suffix);
655
656 while (suffix_len) {
657 if (!path_len)
658 return NULL;
659
660 if (is_dir_sep(path[path_len - 1])) {
661 if (!is_dir_sep(suffix[suffix_len - 1]))
662 return NULL;
663 path_len = chomp_trailing_dir_sep(path, path_len);
664 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
665 }
666 else if (path[--path_len] != suffix[--suffix_len])
667 return NULL;
668 }
669
670 if (path_len && !is_dir_sep(path[path_len - 1]))
671 return NULL;
672 return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
673}
34b6cb8b
SP
674
675int daemon_avoid_alias(const char *p)
676{
677 int sl, ndot;
678
679 /*
680 * This resurrects the belts and suspenders paranoia check by HPA
681 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
682 * does not do getcwd() based path canonicalizations.
683 *
684 * sl becomes true immediately after seeing '/' and continues to
685 * be true as long as dots continue after that without intervening
686 * non-dot character.
687 */
688 if (!p || (*p != '/' && *p != '~'))
689 return -1;
690 sl = 1; ndot = 0;
691 p++;
692
693 while (1) {
694 char ch = *p++;
695 if (sl) {
696 if (ch == '.')
697 ndot++;
698 else if (ch == '/') {
699 if (ndot < 3)
700 /* reject //, /./ and /../ */
701 return -1;
702 ndot = 0;
703 }
704 else if (ch == 0) {
705 if (0 < ndot && ndot < 3)
706 /* reject /.$ and /..$ */
707 return -1;
708 return 0;
709 }
710 else
711 sl = ndot = 0;
712 }
713 else if (ch == 0)
714 return 0;
715 else if (ch == '/') {
716 sl = 1;
717 ndot = 0;
718 }
719 }
720}