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"
14#include "strbuf.h"
15
16static char bad_path[] = "/bad-path/";
17
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
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
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) {
45 strlcpy(buf, bad_path, n);
46 return buf;
47 }
48 return cleanup_path(buf);
49}
50
51static char *git_vsnpath(char *buf, size_t n, const char *fmt, va_list args)
52{
53 const char *git_dir = get_git_dir();
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++] = '/';
62 len += vsnprintf(buf + len, n - len, fmt, args);
63 if (len >= n)
64 goto bad;
65 return cleanup_path(buf);
66bad:
67 strlcpy(buf, bad_path, n);
68 return buf;
69}
70
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
90char *mkpath(const char *fmt, ...)
91{
92 va_list args;
93 unsigned len;
94 char *pathname = get_pathname();
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{
106 const char *git_dir = get_git_dir();
107 char *pathname = get_pathname();
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}
124
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
142 git_dir = read_gitfile(buf.buf);
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}
163
164int validate_headref(const char *path)
165{
166 struct stat st;
167 char *buf, buffer[256];
168 unsigned char sha1[20];
169 int fd;
170 ssize_t len;
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);
178 if (len >= 5 && !memcmp("refs/", buffer, 5))
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;
189 len = read_in_full(fd, buffer, sizeof(buffer)-1);
190 close(fd);
191
192 /*
193 * Is it a symbolic ref?
194 */
195 if (len < 4)
196 return -1;
197 if (!memcmp("ref:", buffer, 4)) {
198 buf = buffer + 4;
199 len -= 4;
200 while (len && isspace(*buf))
201 buf++, len--;
202 if (len >= 5 && !memcmp("refs/", buf, 5))
203 return 0;
204 }
205
206 /*
207 * Is this a detached HEAD?
208 */
209 if (!get_sha1_hex(buffer, sha1))
210 return 0;
211
212 return -1;
213}
214
215static struct passwd *getpw_str(const char *username, size_t len)
216{
217 struct passwd *pw;
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}
225
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;
242 if (username_len == 0) {
243 const char *home = getenv("HOME");
244 if (!home)
245 goto return_null;
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));
252 }
253 to_copy = first_slash;
254 }
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;
260}
261
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 */
286const char *enter_repo(const char *path, int strict)
287{
288 static char used_path[PATH_MAX];
289 static char validated_path[PATH_MAX];
290
291 if (!path)
292 return NULL;
293
294 if (!strict) {
295 static const char *suffix[] = {
296 ".git/.git", "/.git", ".git", "", NULL,
297 };
298 int len = strlen(path);
299 int i;
300 while ((1 < len) && (path[len-1] == '/'))
301 len--;
302
303 if (PATH_MAX <= len)
304 return NULL;
305 strncpy(used_path, path, len); used_path[len] = 0 ;
306 strcpy(validated_path, used_path);
307
308 if (used_path[0] == '~') {
309 char *newpath = expand_user_path(used_path);
310 if (!newpath || (PATH_MAX - 10 < strlen(newpath))) {
311 free(newpath);
312 return NULL;
313 }
314 /*
315 * Copy back into the static buffer. A pity
316 * since newpath was not bounded, but other
317 * branches of the if are limited by PATH_MAX
318 * anyway.
319 */
320 strcpy(used_path, newpath); free(newpath);
321 }
322 else if (PATH_MAX - 10 < len)
323 return NULL;
324 len = strlen(used_path);
325 for (i = 0; suffix[i]; i++) {
326 strcpy(used_path + len, suffix[i]);
327 if (!access(used_path, F_OK)) {
328 strcat(validated_path, suffix[i]);
329 break;
330 }
331 }
332 if (!suffix[i] || chdir(used_path))
333 return NULL;
334 path = validated_path;
335 }
336 else if (chdir(path))
337 return NULL;
338
339 if (access("objects", X_OK) == 0 && access("refs", X_OK) == 0 &&
340 validate_headref("HEAD") == 0) {
341 set_git_dir(".");
342 check_repository_format();
343 return path;
344 }
345
346 return NULL;
347}
348
349int set_shared_perm(const char *path, int mode)
350{
351 struct stat st;
352 int tweak, shared, orig_mode;
353
354 if (!shared_repository) {
355 if (mode)
356 return chmod(path, mode & ~S_IFMT);
357 return 0;
358 }
359 if (!mode) {
360 if (lstat(path, &st) < 0)
361 return -1;
362 mode = st.st_mode;
363 orig_mode = mode;
364 } else
365 orig_mode = 0;
366 if (shared_repository < 0)
367 shared = -shared_repository;
368 else
369 shared = shared_repository;
370 tweak = shared;
371
372 if (!(mode & S_IWUSR))
373 tweak &= ~0222;
374 if (mode & S_IXUSR)
375 /* Copy read bits to execute bits */
376 tweak |= (tweak & 0444) >> 2;
377 if (shared_repository < 0)
378 mode = (mode & ~0777) | tweak;
379 else
380 mode |= tweak;
381
382 if (S_ISDIR(mode)) {
383 /* Copy read bits to execute bits */
384 mode |= (shared & 0444) >> 2;
385 mode |= FORCE_DIR_SET_GID;
386 }
387
388 if (((shared_repository < 0
389 ? (orig_mode & (FORCE_DIR_SET_GID | 0777))
390 : (orig_mode & mode)) != mode) &&
391 chmod(path, (mode & ~S_IFMT)) < 0)
392 return -2;
393 return 0;
394}
395
396const char *relative_path(const char *abs, const char *base)
397{
398 static char buf[PATH_MAX + 1];
399 int i = 0, j = 0;
400
401 if (!base || !base[0])
402 return abs;
403 while (base[i]) {
404 if (is_dir_sep(base[i])) {
405 if (!is_dir_sep(abs[j]))
406 return abs;
407 while (is_dir_sep(base[i]))
408 i++;
409 while (is_dir_sep(abs[j]))
410 j++;
411 continue;
412 } else if (abs[j] != base[i]) {
413 return abs;
414 }
415 i++;
416 j++;
417 }
418 if (
419 /* "/foo" is a prefix of "/foo" */
420 abs[j] &&
421 /* "/foo" is not a prefix of "/foobar" */
422 !is_dir_sep(base[i-1]) && !is_dir_sep(abs[j])
423 )
424 return abs;
425 while (is_dir_sep(abs[j]))
426 j++;
427 if (!abs[j])
428 strcpy(buf, ".");
429 else
430 strcpy(buf, abs + j);
431 return buf;
432}
433
434/*
435 * It is okay if dst == src, but they should not overlap otherwise.
436 *
437 * Performs the following normalizations on src, storing the result in dst:
438 * - Ensures that components are separated by '/' (Windows only)
439 * - Squashes sequences of '/'.
440 * - Removes "." components.
441 * - Removes ".." components, and the components the precede them.
442 * Returns failure (non-zero) if a ".." component appears as first path
443 * component anytime during the normalization. Otherwise, returns success (0).
444 *
445 * Note that this function is purely textual. It does not follow symlinks,
446 * verify the existence of the path, or make any system calls.
447 */
448int normalize_path_copy(char *dst, const char *src)
449{
450 char *dst0;
451
452 if (has_dos_drive_prefix(src)) {
453 *dst++ = *src++;
454 *dst++ = *src++;
455 }
456 dst0 = dst;
457
458 if (is_dir_sep(*src)) {
459 *dst++ = '/';
460 while (is_dir_sep(*src))
461 src++;
462 }
463
464 for (;;) {
465 char c = *src;
466
467 /*
468 * A path component that begins with . could be
469 * special:
470 * (1) "." and ends -- ignore and terminate.
471 * (2) "./" -- ignore them, eat slash and continue.
472 * (3) ".." and ends -- strip one and terminate.
473 * (4) "../" -- strip one, eat slash and continue.
474 */
475 if (c == '.') {
476 if (!src[1]) {
477 /* (1) */
478 src++;
479 } else if (is_dir_sep(src[1])) {
480 /* (2) */
481 src += 2;
482 while (is_dir_sep(*src))
483 src++;
484 continue;
485 } else if (src[1] == '.') {
486 if (!src[2]) {
487 /* (3) */
488 src += 2;
489 goto up_one;
490 } else if (is_dir_sep(src[2])) {
491 /* (4) */
492 src += 3;
493 while (is_dir_sep(*src))
494 src++;
495 goto up_one;
496 }
497 }
498 }
499
500 /* copy up to the next '/', and eat all '/' */
501 while ((c = *src++) != '\0' && !is_dir_sep(c))
502 *dst++ = c;
503 if (is_dir_sep(c)) {
504 *dst++ = '/';
505 while (is_dir_sep(c))
506 c = *src++;
507 src--;
508 } else if (!c)
509 break;
510 continue;
511
512 up_one:
513 /*
514 * dst0..dst is prefix portion, and dst[-1] is '/';
515 * go up one level.
516 */
517 dst--; /* go to trailing '/' */
518 if (dst <= dst0)
519 return -1;
520 /* Windows: dst[-1] cannot be backslash anymore */
521 while (dst0 < dst && dst[-1] != '/')
522 dst--;
523 }
524 *dst = '\0';
525 return 0;
526}
527
528/*
529 * path = Canonical absolute path
530 * prefix_list = Colon-separated list of absolute paths
531 *
532 * Determines, for each path in prefix_list, whether the "prefix" really
533 * is an ancestor directory of path. Returns the length of the longest
534 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
535 * is an ancestor. (Note that this means 0 is returned if prefix_list is
536 * "/".) "/foo" is not considered an ancestor of "/foobar". Directories
537 * are not considered to be their own ancestors. path must be in a
538 * canonical form: empty components, or "." or ".." components are not
539 * allowed. prefix_list may be null, which is like "".
540 */
541int longest_ancestor_length(const char *path, const char *prefix_list)
542{
543 char buf[PATH_MAX+1];
544 const char *ceil, *colon;
545 int len, max_len = -1;
546
547 if (prefix_list == NULL || !strcmp(path, "/"))
548 return -1;
549
550 for (colon = ceil = prefix_list; *colon; ceil = colon+1) {
551 for (colon = ceil; *colon && *colon != PATH_SEP; colon++);
552 len = colon - ceil;
553 if (len == 0 || len > PATH_MAX || !is_absolute_path(ceil))
554 continue;
555 strlcpy(buf, ceil, len+1);
556 if (normalize_path_copy(buf, buf) < 0)
557 continue;
558 len = strlen(buf);
559 if (len > 0 && buf[len-1] == '/')
560 buf[--len] = '\0';
561
562 if (!strncmp(path, buf, len) &&
563 path[len] == '/' &&
564 len > max_len) {
565 max_len = len;
566 }
567 }
568
569 return max_len;
570}
571
572/* strip arbitrary amount of directory separators at end of path */
573static inline int chomp_trailing_dir_sep(const char *path, int len)
574{
575 while (len && is_dir_sep(path[len - 1]))
576 len--;
577 return len;
578}
579
580/*
581 * If path ends with suffix (complete path components), returns the
582 * part before suffix (sans trailing directory separators).
583 * Otherwise returns NULL.
584 */
585char *strip_path_suffix(const char *path, const char *suffix)
586{
587 int path_len = strlen(path), suffix_len = strlen(suffix);
588
589 while (suffix_len) {
590 if (!path_len)
591 return NULL;
592
593 if (is_dir_sep(path[path_len - 1])) {
594 if (!is_dir_sep(suffix[suffix_len - 1]))
595 return NULL;
596 path_len = chomp_trailing_dir_sep(path, path_len);
597 suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
598 }
599 else if (path[--path_len] != suffix[--suffix_len])
600 return NULL;
601 }
602
603 if (path_len && !is_dir_sep(path[path_len - 1]))
604 return NULL;
605 return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
606}
607
608int daemon_avoid_alias(const char *p)
609{
610 int sl, ndot;
611
612 /*
613 * This resurrects the belts and suspenders paranoia check by HPA
614 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
615 * does not do getcwd() based path canonicalization.
616 *
617 * sl becomes true immediately after seeing '/' and continues to
618 * be true as long as dots continue after that without intervening
619 * non-dot character.
620 */
621 if (!p || (*p != '/' && *p != '~'))
622 return -1;
623 sl = 1; ndot = 0;
624 p++;
625
626 while (1) {
627 char ch = *p++;
628 if (sl) {
629 if (ch == '.')
630 ndot++;
631 else if (ch == '/') {
632 if (ndot < 3)
633 /* reject //, /./ and /../ */
634 return -1;
635 ndot = 0;
636 }
637 else if (ch == 0) {
638 if (0 < ndot && ndot < 3)
639 /* reject /.$ and /..$ */
640 return -1;
641 return 0;
642 }
643 else
644 sl = ndot = 0;
645 }
646 else if (ch == 0)
647 return 0;
648 else if (ch == '/') {
649 sl = 1;
650 ndot = 0;
651 }
652 }
653}
654
655int offset_1st_component(const char *path)
656{
657 if (has_dos_drive_prefix(path))
658 return 2 + is_dir_sep(path[2]);
659 return is_dir_sep(path[0]);
660}