validate_headref: NUL-terminate HEAD buffer
[git] / path.c
1 /*
2  * Utilities for paths and pathnames
3  */
4 #include "cache.h"
5 #include "repository.h"
6 #include "strbuf.h"
7 #include "string-list.h"
8 #include "dir.h"
9 #include "worktree.h"
10 #include "submodule-config.h"
11 #include "path.h"
12
13 static int get_st_mode_bits(const char *path, int *mode)
14 {
15         struct stat st;
16         if (lstat(path, &st) < 0)
17                 return -1;
18         *mode = st.st_mode;
19         return 0;
20 }
21
22 static char bad_path[] = "/bad-path/";
23
24 static struct strbuf *get_pathname(void)
25 {
26         static struct strbuf pathname_array[4] = {
27                 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
28         };
29         static int index;
30         struct strbuf *sb = &pathname_array[index];
31         index = (index + 1) % ARRAY_SIZE(pathname_array);
32         strbuf_reset(sb);
33         return sb;
34 }
35
36 static char *cleanup_path(char *path)
37 {
38         /* Clean it up */
39         if (!memcmp(path, "./", 2)) {
40                 path += 2;
41                 while (*path == '/')
42                         path++;
43         }
44         return path;
45 }
46
47 static void strbuf_cleanup_path(struct strbuf *sb)
48 {
49         char *path = cleanup_path(sb->buf);
50         if (path > sb->buf)
51                 strbuf_remove(sb, 0, path - sb->buf);
52 }
53
54 char *mksnpath(char *buf, size_t n, const char *fmt, ...)
55 {
56         va_list args;
57         unsigned len;
58
59         va_start(args, fmt);
60         len = vsnprintf(buf, n, fmt, args);
61         va_end(args);
62         if (len >= n) {
63                 strlcpy(buf, bad_path, n);
64                 return buf;
65         }
66         return cleanup_path(buf);
67 }
68
69 static int dir_prefix(const char *buf, const char *dir)
70 {
71         int len = strlen(dir);
72         return !strncmp(buf, dir, len) &&
73                 (is_dir_sep(buf[len]) || buf[len] == '\0');
74 }
75
76 /* $buf =~ m|$dir/+$file| but without regex */
77 static int is_dir_file(const char *buf, const char *dir, const char *file)
78 {
79         int len = strlen(dir);
80         if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
81                 return 0;
82         while (is_dir_sep(buf[len]))
83                 len++;
84         return !strcmp(buf + len, file);
85 }
86
87 static void replace_dir(struct strbuf *buf, int len, const char *newdir)
88 {
89         int newlen = strlen(newdir);
90         int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
91                 !is_dir_sep(newdir[newlen - 1]);
92         if (need_sep)
93                 len--;   /* keep one char, to be replaced with '/'  */
94         strbuf_splice(buf, 0, len, newdir, newlen);
95         if (need_sep)
96                 buf->buf[newlen] = '/';
97 }
98
99 struct common_dir {
100         /* Not considered garbage for report_linked_checkout_garbage */
101         unsigned ignore_garbage:1;
102         unsigned is_dir:1;
103         /* Not common even though its parent is */
104         unsigned exclude:1;
105         const char *dirname;
106 };
107
108 static struct common_dir common_list[] = {
109         { 0, 1, 0, "branches" },
110         { 0, 1, 0, "hooks" },
111         { 0, 1, 0, "info" },
112         { 0, 0, 1, "info/sparse-checkout" },
113         { 1, 1, 0, "logs" },
114         { 1, 1, 1, "logs/HEAD" },
115         { 0, 1, 1, "logs/refs/bisect" },
116         { 0, 1, 0, "lost-found" },
117         { 0, 1, 0, "objects" },
118         { 0, 1, 0, "refs" },
119         { 0, 1, 1, "refs/bisect" },
120         { 0, 1, 0, "remotes" },
121         { 0, 1, 0, "worktrees" },
122         { 0, 1, 0, "rr-cache" },
123         { 0, 1, 0, "svn" },
124         { 0, 0, 0, "config" },
125         { 1, 0, 0, "gc.pid" },
126         { 0, 0, 0, "packed-refs" },
127         { 0, 0, 0, "shallow" },
128         { 0, 0, 0, NULL }
129 };
130
131 /*
132  * A compressed trie.  A trie node consists of zero or more characters that
133  * are common to all elements with this prefix, optionally followed by some
134  * children.  If value is not NULL, the trie node is a terminal node.
135  *
136  * For example, consider the following set of strings:
137  * abc
138  * def
139  * definite
140  * definition
141  *
142  * The trie would look like:
143  * root: len = 0, children a and d non-NULL, value = NULL.
144  *    a: len = 2, contents = bc, value = (data for "abc")
145  *    d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
146  *       i: len = 3, contents = nit, children e and i non-NULL, value = NULL
147  *           e: len = 0, children all NULL, value = (data for "definite")
148  *           i: len = 2, contents = on, children all NULL,
149  *              value = (data for "definition")
150  */
151 struct trie {
152         struct trie *children[256];
153         int len;
154         char *contents;
155         void *value;
156 };
157
158 static struct trie *make_trie_node(const char *key, void *value)
159 {
160         struct trie *new_node = xcalloc(1, sizeof(*new_node));
161         new_node->len = strlen(key);
162         if (new_node->len) {
163                 new_node->contents = xmalloc(new_node->len);
164                 memcpy(new_node->contents, key, new_node->len);
165         }
166         new_node->value = value;
167         return new_node;
168 }
169
170 /*
171  * Add a key/value pair to a trie.  The key is assumed to be \0-terminated.
172  * If there was an existing value for this key, return it.
173  */
174 static void *add_to_trie(struct trie *root, const char *key, void *value)
175 {
176         struct trie *child;
177         void *old;
178         int i;
179
180         if (!*key) {
181                 /* we have reached the end of the key */
182                 old = root->value;
183                 root->value = value;
184                 return old;
185         }
186
187         for (i = 0; i < root->len; i++) {
188                 if (root->contents[i] == key[i])
189                         continue;
190
191                 /*
192                  * Split this node: child will contain this node's
193                  * existing children.
194                  */
195                 child = malloc(sizeof(*child));
196                 memcpy(child->children, root->children, sizeof(root->children));
197
198                 child->len = root->len - i - 1;
199                 if (child->len) {
200                         child->contents = xstrndup(root->contents + i + 1,
201                                                    child->len);
202                 }
203                 child->value = root->value;
204                 root->value = NULL;
205                 root->len = i;
206
207                 memset(root->children, 0, sizeof(root->children));
208                 root->children[(unsigned char)root->contents[i]] = child;
209
210                 /* This is the newly-added child. */
211                 root->children[(unsigned char)key[i]] =
212                         make_trie_node(key + i + 1, value);
213                 return NULL;
214         }
215
216         /* We have matched the entire compressed section */
217         if (key[i]) {
218                 child = root->children[(unsigned char)key[root->len]];
219                 if (child) {
220                         return add_to_trie(child, key + root->len + 1, value);
221                 } else {
222                         child = make_trie_node(key + root->len + 1, value);
223                         root->children[(unsigned char)key[root->len]] = child;
224                         return NULL;
225                 }
226         }
227
228         old = root->value;
229         root->value = value;
230         return old;
231 }
232
233 typedef int (*match_fn)(const char *unmatched, void *data, void *baton);
234
235 /*
236  * Search a trie for some key.  Find the longest /-or-\0-terminated
237  * prefix of the key for which the trie contains a value.  Call fn
238  * with the unmatched portion of the key and the found value, and
239  * return its return value.  If there is no such prefix, return -1.
240  *
241  * The key is partially normalized: consecutive slashes are skipped.
242  *
243  * For example, consider the trie containing only [refs,
244  * refs/worktree] (both with values).
245  *
246  * | key             | unmatched  | val from node | return value |
247  * |-----------------|------------|---------------|--------------|
248  * | a               | not called | n/a           | -1           |
249  * | refs            | \0         | refs          | as per fn    |
250  * | refs/           | /          | refs          | as per fn    |
251  * | refs/w          | /w         | refs          | as per fn    |
252  * | refs/worktree   | \0         | refs/worktree | as per fn    |
253  * | refs/worktree/  | /          | refs/worktree | as per fn    |
254  * | refs/worktree/a | /a         | refs/worktree | as per fn    |
255  * |-----------------|------------|---------------|--------------|
256  *
257  */
258 static int trie_find(struct trie *root, const char *key, match_fn fn,
259                      void *baton)
260 {
261         int i;
262         int result;
263         struct trie *child;
264
265         if (!*key) {
266                 /* we have reached the end of the key */
267                 if (root->value && !root->len)
268                         return fn(key, root->value, baton);
269                 else
270                         return -1;
271         }
272
273         for (i = 0; i < root->len; i++) {
274                 /* Partial path normalization: skip consecutive slashes. */
275                 if (key[i] == '/' && key[i+1] == '/') {
276                         key++;
277                         continue;
278                 }
279                 if (root->contents[i] != key[i])
280                         return -1;
281         }
282
283         /* Matched the entire compressed section */
284         key += i;
285         if (!*key)
286                 /* End of key */
287                 return fn(key, root->value, baton);
288
289         /* Partial path normalization: skip consecutive slashes */
290         while (key[0] == '/' && key[1] == '/')
291                 key++;
292
293         child = root->children[(unsigned char)*key];
294         if (child)
295                 result = trie_find(child, key + 1, fn, baton);
296         else
297                 result = -1;
298
299         if (result >= 0 || (*key != '/' && *key != 0))
300                 return result;
301         if (root->value)
302                 return fn(key, root->value, baton);
303         else
304                 return -1;
305 }
306
307 static struct trie common_trie;
308 static int common_trie_done_setup;
309
310 static void init_common_trie(void)
311 {
312         struct common_dir *p;
313
314         if (common_trie_done_setup)
315                 return;
316
317         for (p = common_list; p->dirname; p++)
318                 add_to_trie(&common_trie, p->dirname, p);
319
320         common_trie_done_setup = 1;
321 }
322
323 /*
324  * Helper function for update_common_dir: returns 1 if the dir
325  * prefix is common.
326  */
327 static int check_common(const char *unmatched, void *value, void *baton)
328 {
329         struct common_dir *dir = value;
330
331         if (!dir)
332                 return 0;
333
334         if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
335                 return !dir->exclude;
336
337         if (!dir->is_dir && unmatched[0] == 0)
338                 return !dir->exclude;
339
340         return 0;
341 }
342
343 static void update_common_dir(struct strbuf *buf, int git_dir_len,
344                               const char *common_dir)
345 {
346         char *base = buf->buf + git_dir_len;
347         init_common_trie();
348         if (trie_find(&common_trie, base, check_common, NULL) > 0)
349                 replace_dir(buf, git_dir_len, common_dir);
350 }
351
352 void report_linked_checkout_garbage(void)
353 {
354         struct strbuf sb = STRBUF_INIT;
355         const struct common_dir *p;
356         int len;
357
358         if (!the_repository->different_commondir)
359                 return;
360         strbuf_addf(&sb, "%s/", get_git_dir());
361         len = sb.len;
362         for (p = common_list; p->dirname; p++) {
363                 const char *path = p->dirname;
364                 if (p->ignore_garbage)
365                         continue;
366                 strbuf_setlen(&sb, len);
367                 strbuf_addstr(&sb, path);
368                 if (file_exists(sb.buf))
369                         report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
370         }
371         strbuf_release(&sb);
372 }
373
374 static void adjust_git_path(const struct repository *repo,
375                             struct strbuf *buf, int git_dir_len)
376 {
377         const char *base = buf->buf + git_dir_len;
378         if (is_dir_file(base, "info", "grafts"))
379                 strbuf_splice(buf, 0, buf->len,
380                               repo->graft_file, strlen(repo->graft_file));
381         else if (!strcmp(base, "index"))
382                 strbuf_splice(buf, 0, buf->len,
383                               repo->index_file, strlen(repo->index_file));
384         else if (dir_prefix(base, "objects"))
385                 replace_dir(buf, git_dir_len + 7, repo->objectdir);
386         else if (git_hooks_path && dir_prefix(base, "hooks"))
387                 replace_dir(buf, git_dir_len + 5, git_hooks_path);
388         else if (repo->different_commondir)
389                 update_common_dir(buf, git_dir_len, repo->commondir);
390 }
391
392 static void strbuf_worktree_gitdir(struct strbuf *buf,
393                                    const struct repository *repo,
394                                    const struct worktree *wt)
395 {
396         if (!wt)
397                 strbuf_addstr(buf, repo->gitdir);
398         else if (!wt->id)
399                 strbuf_addstr(buf, repo->commondir);
400         else
401                 strbuf_git_common_path(buf, repo, "worktrees/%s", wt->id);
402 }
403
404 static void do_git_path(const struct repository *repo,
405                         const struct worktree *wt, struct strbuf *buf,
406                         const char *fmt, va_list args)
407 {
408         int gitdir_len;
409         strbuf_worktree_gitdir(buf, repo, wt);
410         if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
411                 strbuf_addch(buf, '/');
412         gitdir_len = buf->len;
413         strbuf_vaddf(buf, fmt, args);
414         if (!wt)
415                 adjust_git_path(repo, buf, gitdir_len);
416         strbuf_cleanup_path(buf);
417 }
418
419 char *repo_git_path(const struct repository *repo,
420                     const char *fmt, ...)
421 {
422         struct strbuf path = STRBUF_INIT;
423         va_list args;
424         va_start(args, fmt);
425         do_git_path(repo, NULL, &path, fmt, args);
426         va_end(args);
427         return strbuf_detach(&path, NULL);
428 }
429
430 void strbuf_repo_git_path(struct strbuf *sb,
431                           const struct repository *repo,
432                           const char *fmt, ...)
433 {
434         va_list args;
435         va_start(args, fmt);
436         do_git_path(repo, NULL, sb, fmt, args);
437         va_end(args);
438 }
439
440 char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
441 {
442         va_list args;
443         strbuf_reset(buf);
444         va_start(args, fmt);
445         do_git_path(the_repository, NULL, buf, fmt, args);
446         va_end(args);
447         return buf->buf;
448 }
449
450 void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
451 {
452         va_list args;
453         va_start(args, fmt);
454         do_git_path(the_repository, NULL, sb, fmt, args);
455         va_end(args);
456 }
457
458 const char *git_path(const char *fmt, ...)
459 {
460         struct strbuf *pathname = get_pathname();
461         va_list args;
462         va_start(args, fmt);
463         do_git_path(the_repository, NULL, pathname, fmt, args);
464         va_end(args);
465         return pathname->buf;
466 }
467
468 char *git_pathdup(const char *fmt, ...)
469 {
470         struct strbuf path = STRBUF_INIT;
471         va_list args;
472         va_start(args, fmt);
473         do_git_path(the_repository, NULL, &path, fmt, args);
474         va_end(args);
475         return strbuf_detach(&path, NULL);
476 }
477
478 char *mkpathdup(const char *fmt, ...)
479 {
480         struct strbuf sb = STRBUF_INIT;
481         va_list args;
482         va_start(args, fmt);
483         strbuf_vaddf(&sb, fmt, args);
484         va_end(args);
485         strbuf_cleanup_path(&sb);
486         return strbuf_detach(&sb, NULL);
487 }
488
489 const char *mkpath(const char *fmt, ...)
490 {
491         va_list args;
492         struct strbuf *pathname = get_pathname();
493         va_start(args, fmt);
494         strbuf_vaddf(pathname, fmt, args);
495         va_end(args);
496         return cleanup_path(pathname->buf);
497 }
498
499 const char *worktree_git_path(const struct worktree *wt, const char *fmt, ...)
500 {
501         struct strbuf *pathname = get_pathname();
502         va_list args;
503         va_start(args, fmt);
504         do_git_path(the_repository, wt, pathname, fmt, args);
505         va_end(args);
506         return pathname->buf;
507 }
508
509 static void do_worktree_path(const struct repository *repo,
510                              struct strbuf *buf,
511                              const char *fmt, va_list args)
512 {
513         strbuf_addstr(buf, repo->worktree);
514         if(buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
515                 strbuf_addch(buf, '/');
516
517         strbuf_vaddf(buf, fmt, args);
518         strbuf_cleanup_path(buf);
519 }
520
521 char *repo_worktree_path(const struct repository *repo, const char *fmt, ...)
522 {
523         struct strbuf path = STRBUF_INIT;
524         va_list args;
525
526         if (!repo->worktree)
527                 return NULL;
528
529         va_start(args, fmt);
530         do_worktree_path(repo, &path, fmt, args);
531         va_end(args);
532
533         return strbuf_detach(&path, NULL);
534 }
535
536 void strbuf_repo_worktree_path(struct strbuf *sb,
537                                const struct repository *repo,
538                                const char *fmt, ...)
539 {
540         va_list args;
541
542         if (!repo->worktree)
543                 return;
544
545         va_start(args, fmt);
546         do_worktree_path(repo, sb, fmt, args);
547         va_end(args);
548 }
549
550 /* Returns 0 on success, negative on failure. */
551 static int do_submodule_path(struct strbuf *buf, const char *path,
552                              const char *fmt, va_list args)
553 {
554         struct strbuf git_submodule_common_dir = STRBUF_INIT;
555         struct strbuf git_submodule_dir = STRBUF_INIT;
556         int ret;
557
558         ret = submodule_to_gitdir(&git_submodule_dir, path);
559         if (ret)
560                 goto cleanup;
561
562         strbuf_complete(&git_submodule_dir, '/');
563         strbuf_addbuf(buf, &git_submodule_dir);
564         strbuf_vaddf(buf, fmt, args);
565
566         if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
567                 update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
568
569         strbuf_cleanup_path(buf);
570
571 cleanup:
572         strbuf_release(&git_submodule_dir);
573         strbuf_release(&git_submodule_common_dir);
574         return ret;
575 }
576
577 char *git_pathdup_submodule(const char *path, const char *fmt, ...)
578 {
579         int err;
580         va_list args;
581         struct strbuf buf = STRBUF_INIT;
582         va_start(args, fmt);
583         err = do_submodule_path(&buf, path, fmt, args);
584         va_end(args);
585         if (err) {
586                 strbuf_release(&buf);
587                 return NULL;
588         }
589         return strbuf_detach(&buf, NULL);
590 }
591
592 int strbuf_git_path_submodule(struct strbuf *buf, const char *path,
593                               const char *fmt, ...)
594 {
595         int err;
596         va_list args;
597         va_start(args, fmt);
598         err = do_submodule_path(buf, path, fmt, args);
599         va_end(args);
600
601         return err;
602 }
603
604 static void do_git_common_path(const struct repository *repo,
605                                struct strbuf *buf,
606                                const char *fmt,
607                                va_list args)
608 {
609         strbuf_addstr(buf, repo->commondir);
610         if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
611                 strbuf_addch(buf, '/');
612         strbuf_vaddf(buf, fmt, args);
613         strbuf_cleanup_path(buf);
614 }
615
616 const char *git_common_path(const char *fmt, ...)
617 {
618         struct strbuf *pathname = get_pathname();
619         va_list args;
620         va_start(args, fmt);
621         do_git_common_path(the_repository, pathname, fmt, args);
622         va_end(args);
623         return pathname->buf;
624 }
625
626 void strbuf_git_common_path(struct strbuf *sb,
627                             const struct repository *repo,
628                             const char *fmt, ...)
629 {
630         va_list args;
631         va_start(args, fmt);
632         do_git_common_path(repo, sb, fmt, args);
633         va_end(args);
634 }
635
636 int validate_headref(const char *path)
637 {
638         struct stat st;
639         char *buf, buffer[256];
640         unsigned char sha1[20];
641         int fd;
642         ssize_t len;
643
644         if (lstat(path, &st) < 0)
645                 return -1;
646
647         /* Make sure it is a "refs/.." symlink */
648         if (S_ISLNK(st.st_mode)) {
649                 len = readlink(path, buffer, sizeof(buffer)-1);
650                 if (len >= 5 && !memcmp("refs/", buffer, 5))
651                         return 0;
652                 return -1;
653         }
654
655         /*
656          * Anything else, just open it and try to see if it is a symbolic ref.
657          */
658         fd = open(path, O_RDONLY);
659         if (fd < 0)
660                 return -1;
661         len = read_in_full(fd, buffer, sizeof(buffer)-1);
662         close(fd);
663
664         if (len < 0)
665                 return -1;
666         buffer[len] = '\0';
667
668         /*
669          * Is it a symbolic ref?
670          */
671         if (len < 4)
672                 return -1;
673         if (!memcmp("ref:", buffer, 4)) {
674                 buf = buffer + 4;
675                 len -= 4;
676                 while (len && isspace(*buf))
677                         buf++, len--;
678                 if (len >= 5 && !memcmp("refs/", buf, 5))
679                         return 0;
680         }
681
682         /*
683          * Is this a detached HEAD?
684          */
685         if (!get_sha1_hex(buffer, sha1))
686                 return 0;
687
688         return -1;
689 }
690
691 static struct passwd *getpw_str(const char *username, size_t len)
692 {
693         struct passwd *pw;
694         char *username_z = xmemdupz(username, len);
695         pw = getpwnam(username_z);
696         free(username_z);
697         return pw;
698 }
699
700 /*
701  * Return a string with ~ and ~user expanded via getpw*.  If buf != NULL,
702  * then it is a newly allocated string. Returns NULL on getpw failure or
703  * if path is NULL.
704  *
705  * If real_home is true, real_path($HOME) is used in the expansion.
706  */
707 char *expand_user_path(const char *path, int real_home)
708 {
709         struct strbuf user_path = STRBUF_INIT;
710         const char *to_copy = path;
711
712         if (path == NULL)
713                 goto return_null;
714         if (path[0] == '~') {
715                 const char *first_slash = strchrnul(path, '/');
716                 const char *username = path + 1;
717                 size_t username_len = first_slash - username;
718                 if (username_len == 0) {
719                         const char *home = getenv("HOME");
720                         if (!home)
721                                 goto return_null;
722                         if (real_home)
723                                 strbuf_addstr(&user_path, real_path(home));
724                         else
725                                 strbuf_addstr(&user_path, home);
726 #ifdef GIT_WINDOWS_NATIVE
727                         convert_slashes(user_path.buf);
728 #endif
729                 } else {
730                         struct passwd *pw = getpw_str(username, username_len);
731                         if (!pw)
732                                 goto return_null;
733                         strbuf_addstr(&user_path, pw->pw_dir);
734                 }
735                 to_copy = first_slash;
736         }
737         strbuf_addstr(&user_path, to_copy);
738         return strbuf_detach(&user_path, NULL);
739 return_null:
740         strbuf_release(&user_path);
741         return NULL;
742 }
743
744 /*
745  * First, one directory to try is determined by the following algorithm.
746  *
747  * (0) If "strict" is given, the path is used as given and no DWIM is
748  *     done. Otherwise:
749  * (1) "~/path" to mean path under the running user's home directory;
750  * (2) "~user/path" to mean path under named user's home directory;
751  * (3) "relative/path" to mean cwd relative directory; or
752  * (4) "/absolute/path" to mean absolute directory.
753  *
754  * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
755  * in this order. We select the first one that is a valid git repository, and
756  * chdir() to it. If none match, or we fail to chdir, we return NULL.
757  *
758  * If all goes well, we return the directory we used to chdir() (but
759  * before ~user is expanded), avoiding getcwd() resolving symbolic
760  * links.  User relative paths are also returned as they are given,
761  * except DWIM suffixing.
762  */
763 const char *enter_repo(const char *path, int strict)
764 {
765         static struct strbuf validated_path = STRBUF_INIT;
766         static struct strbuf used_path = STRBUF_INIT;
767
768         if (!path)
769                 return NULL;
770
771         if (!strict) {
772                 static const char *suffix[] = {
773                         "/.git", "", ".git/.git", ".git", NULL,
774                 };
775                 const char *gitfile;
776                 int len = strlen(path);
777                 int i;
778                 while ((1 < len) && (path[len-1] == '/'))
779                         len--;
780
781                 /*
782                  * We can handle arbitrary-sized buffers, but this remains as a
783                  * sanity check on untrusted input.
784                  */
785                 if (PATH_MAX <= len)
786                         return NULL;
787
788                 strbuf_reset(&used_path);
789                 strbuf_reset(&validated_path);
790                 strbuf_add(&used_path, path, len);
791                 strbuf_add(&validated_path, path, len);
792
793                 if (used_path.buf[0] == '~') {
794                         char *newpath = expand_user_path(used_path.buf, 0);
795                         if (!newpath)
796                                 return NULL;
797                         strbuf_attach(&used_path, newpath, strlen(newpath),
798                                       strlen(newpath));
799                 }
800                 for (i = 0; suffix[i]; i++) {
801                         struct stat st;
802                         size_t baselen = used_path.len;
803                         strbuf_addstr(&used_path, suffix[i]);
804                         if (!stat(used_path.buf, &st) &&
805                             (S_ISREG(st.st_mode) ||
806                             (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
807                                 strbuf_addstr(&validated_path, suffix[i]);
808                                 break;
809                         }
810                         strbuf_setlen(&used_path, baselen);
811                 }
812                 if (!suffix[i])
813                         return NULL;
814                 gitfile = read_gitfile(used_path.buf);
815                 if (gitfile) {
816                         strbuf_reset(&used_path);
817                         strbuf_addstr(&used_path, gitfile);
818                 }
819                 if (chdir(used_path.buf))
820                         return NULL;
821                 path = validated_path.buf;
822         }
823         else {
824                 const char *gitfile = read_gitfile(path);
825                 if (gitfile)
826                         path = gitfile;
827                 if (chdir(path))
828                         return NULL;
829         }
830
831         if (is_git_directory(".")) {
832                 set_git_dir(".");
833                 check_repository_format();
834                 return path;
835         }
836
837         return NULL;
838 }
839
840 static int calc_shared_perm(int mode)
841 {
842         int tweak;
843
844         if (get_shared_repository() < 0)
845                 tweak = -get_shared_repository();
846         else
847                 tweak = get_shared_repository();
848
849         if (!(mode & S_IWUSR))
850                 tweak &= ~0222;
851         if (mode & S_IXUSR)
852                 /* Copy read bits to execute bits */
853                 tweak |= (tweak & 0444) >> 2;
854         if (get_shared_repository() < 0)
855                 mode = (mode & ~0777) | tweak;
856         else
857                 mode |= tweak;
858
859         return mode;
860 }
861
862
863 int adjust_shared_perm(const char *path)
864 {
865         int old_mode, new_mode;
866
867         if (!get_shared_repository())
868                 return 0;
869         if (get_st_mode_bits(path, &old_mode) < 0)
870                 return -1;
871
872         new_mode = calc_shared_perm(old_mode);
873         if (S_ISDIR(old_mode)) {
874                 /* Copy read bits to execute bits */
875                 new_mode |= (new_mode & 0444) >> 2;
876                 new_mode |= FORCE_DIR_SET_GID;
877         }
878
879         if (((old_mode ^ new_mode) & ~S_IFMT) &&
880                         chmod(path, (new_mode & ~S_IFMT)) < 0)
881                 return -2;
882         return 0;
883 }
884
885 void safe_create_dir(const char *dir, int share)
886 {
887         if (mkdir(dir, 0777) < 0) {
888                 if (errno != EEXIST) {
889                         perror(dir);
890                         exit(1);
891                 }
892         }
893         else if (share && adjust_shared_perm(dir))
894                 die(_("Could not make %s writable by group"), dir);
895 }
896
897 static int have_same_root(const char *path1, const char *path2)
898 {
899         int is_abs1, is_abs2;
900
901         is_abs1 = is_absolute_path(path1);
902         is_abs2 = is_absolute_path(path2);
903         return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
904                (!is_abs1 && !is_abs2);
905 }
906
907 /*
908  * Give path as relative to prefix.
909  *
910  * The strbuf may or may not be used, so do not assume it contains the
911  * returned path.
912  */
913 const char *relative_path(const char *in, const char *prefix,
914                           struct strbuf *sb)
915 {
916         int in_len = in ? strlen(in) : 0;
917         int prefix_len = prefix ? strlen(prefix) : 0;
918         int in_off = 0;
919         int prefix_off = 0;
920         int i = 0, j = 0;
921
922         if (!in_len)
923                 return "./";
924         else if (!prefix_len)
925                 return in;
926
927         if (have_same_root(in, prefix))
928                 /* bypass dos_drive, for "c:" is identical to "C:" */
929                 i = j = has_dos_drive_prefix(in);
930         else {
931                 return in;
932         }
933
934         while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
935                 if (is_dir_sep(prefix[i])) {
936                         while (is_dir_sep(prefix[i]))
937                                 i++;
938                         while (is_dir_sep(in[j]))
939                                 j++;
940                         prefix_off = i;
941                         in_off = j;
942                 } else {
943                         i++;
944                         j++;
945                 }
946         }
947
948         if (
949             /* "prefix" seems like prefix of "in" */
950             i >= prefix_len &&
951             /*
952              * but "/foo" is not a prefix of "/foobar"
953              * (i.e. prefix not end with '/')
954              */
955             prefix_off < prefix_len) {
956                 if (j >= in_len) {
957                         /* in="/a/b", prefix="/a/b" */
958                         in_off = in_len;
959                 } else if (is_dir_sep(in[j])) {
960                         /* in="/a/b/c", prefix="/a/b" */
961                         while (is_dir_sep(in[j]))
962                                 j++;
963                         in_off = j;
964                 } else {
965                         /* in="/a/bbb/c", prefix="/a/b" */
966                         i = prefix_off;
967                 }
968         } else if (
969                    /* "in" is short than "prefix" */
970                    j >= in_len &&
971                    /* "in" not end with '/' */
972                    in_off < in_len) {
973                 if (is_dir_sep(prefix[i])) {
974                         /* in="/a/b", prefix="/a/b/c/" */
975                         while (is_dir_sep(prefix[i]))
976                                 i++;
977                         in_off = in_len;
978                 }
979         }
980         in += in_off;
981         in_len -= in_off;
982
983         if (i >= prefix_len) {
984                 if (!in_len)
985                         return "./";
986                 else
987                         return in;
988         }
989
990         strbuf_reset(sb);
991         strbuf_grow(sb, in_len);
992
993         while (i < prefix_len) {
994                 if (is_dir_sep(prefix[i])) {
995                         strbuf_addstr(sb, "../");
996                         while (is_dir_sep(prefix[i]))
997                                 i++;
998                         continue;
999                 }
1000                 i++;
1001         }
1002         if (!is_dir_sep(prefix[prefix_len - 1]))
1003                 strbuf_addstr(sb, "../");
1004
1005         strbuf_addstr(sb, in);
1006
1007         return sb->buf;
1008 }
1009
1010 /*
1011  * A simpler implementation of relative_path
1012  *
1013  * Get relative path by removing "prefix" from "in". This function
1014  * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
1015  * to increase performance when traversing the path to work_tree.
1016  */
1017 const char *remove_leading_path(const char *in, const char *prefix)
1018 {
1019         static struct strbuf buf = STRBUF_INIT;
1020         int i = 0, j = 0;
1021
1022         if (!prefix || !prefix[0])
1023                 return in;
1024         while (prefix[i]) {
1025                 if (is_dir_sep(prefix[i])) {
1026                         if (!is_dir_sep(in[j]))
1027                                 return in;
1028                         while (is_dir_sep(prefix[i]))
1029                                 i++;
1030                         while (is_dir_sep(in[j]))
1031                                 j++;
1032                         continue;
1033                 } else if (in[j] != prefix[i]) {
1034                         return in;
1035                 }
1036                 i++;
1037                 j++;
1038         }
1039         if (
1040             /* "/foo" is a prefix of "/foo" */
1041             in[j] &&
1042             /* "/foo" is not a prefix of "/foobar" */
1043             !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
1044            )
1045                 return in;
1046         while (is_dir_sep(in[j]))
1047                 j++;
1048
1049         strbuf_reset(&buf);
1050         if (!in[j])
1051                 strbuf_addstr(&buf, ".");
1052         else
1053                 strbuf_addstr(&buf, in + j);
1054         return buf.buf;
1055 }
1056
1057 /*
1058  * It is okay if dst == src, but they should not overlap otherwise.
1059  *
1060  * Performs the following normalizations on src, storing the result in dst:
1061  * - Ensures that components are separated by '/' (Windows only)
1062  * - Squashes sequences of '/' except "//server/share" on Windows
1063  * - Removes "." components.
1064  * - Removes ".." components, and the components the precede them.
1065  * Returns failure (non-zero) if a ".." component appears as first path
1066  * component anytime during the normalization. Otherwise, returns success (0).
1067  *
1068  * Note that this function is purely textual.  It does not follow symlinks,
1069  * verify the existence of the path, or make any system calls.
1070  *
1071  * prefix_len != NULL is for a specific case of prefix_pathspec():
1072  * assume that src == dst and src[0..prefix_len-1] is already
1073  * normalized, any time "../" eats up to the prefix_len part,
1074  * prefix_len is reduced. In the end prefix_len is the remaining
1075  * prefix that has not been overridden by user pathspec.
1076  *
1077  * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1078  * For everything but the root folder itself, the normalized path should not
1079  * end with a '/', then the callers need to be fixed up accordingly.
1080  *
1081  */
1082 int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
1083 {
1084         char *dst0;
1085         const char *end;
1086
1087         /*
1088          * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1089          */
1090         end = src + offset_1st_component(src);
1091         while (src < end) {
1092                 char c = *src++;
1093                 if (is_dir_sep(c))
1094                         c = '/';
1095                 *dst++ = c;
1096         }
1097         dst0 = dst;
1098
1099         while (is_dir_sep(*src))
1100                 src++;
1101
1102         for (;;) {
1103                 char c = *src;
1104
1105                 /*
1106                  * A path component that begins with . could be
1107                  * special:
1108                  * (1) "." and ends   -- ignore and terminate.
1109                  * (2) "./"           -- ignore them, eat slash and continue.
1110                  * (3) ".." and ends  -- strip one and terminate.
1111                  * (4) "../"          -- strip one, eat slash and continue.
1112                  */
1113                 if (c == '.') {
1114                         if (!src[1]) {
1115                                 /* (1) */
1116                                 src++;
1117                         } else if (is_dir_sep(src[1])) {
1118                                 /* (2) */
1119                                 src += 2;
1120                                 while (is_dir_sep(*src))
1121                                         src++;
1122                                 continue;
1123                         } else if (src[1] == '.') {
1124                                 if (!src[2]) {
1125                                         /* (3) */
1126                                         src += 2;
1127                                         goto up_one;
1128                                 } else if (is_dir_sep(src[2])) {
1129                                         /* (4) */
1130                                         src += 3;
1131                                         while (is_dir_sep(*src))
1132                                                 src++;
1133                                         goto up_one;
1134                                 }
1135                         }
1136                 }
1137
1138                 /* copy up to the next '/', and eat all '/' */
1139                 while ((c = *src++) != '\0' && !is_dir_sep(c))
1140                         *dst++ = c;
1141                 if (is_dir_sep(c)) {
1142                         *dst++ = '/';
1143                         while (is_dir_sep(c))
1144                                 c = *src++;
1145                         src--;
1146                 } else if (!c)
1147                         break;
1148                 continue;
1149
1150         up_one:
1151                 /*
1152                  * dst0..dst is prefix portion, and dst[-1] is '/';
1153                  * go up one level.
1154                  */
1155                 dst--;  /* go to trailing '/' */
1156                 if (dst <= dst0)
1157                         return -1;
1158                 /* Windows: dst[-1] cannot be backslash anymore */
1159                 while (dst0 < dst && dst[-1] != '/')
1160                         dst--;
1161                 if (prefix_len && *prefix_len > dst - dst0)
1162                         *prefix_len = dst - dst0;
1163         }
1164         *dst = '\0';
1165         return 0;
1166 }
1167
1168 int normalize_path_copy(char *dst, const char *src)
1169 {
1170         return normalize_path_copy_len(dst, src, NULL);
1171 }
1172
1173 /*
1174  * path = Canonical absolute path
1175  * prefixes = string_list containing normalized, absolute paths without
1176  * trailing slashes (except for the root directory, which is denoted by "/").
1177  *
1178  * Determines, for each path in prefixes, whether the "prefix"
1179  * is an ancestor directory of path.  Returns the length of the longest
1180  * ancestor directory, excluding any trailing slashes, or -1 if no prefix
1181  * is an ancestor.  (Note that this means 0 is returned if prefixes is
1182  * ["/"].) "/foo" is not considered an ancestor of "/foobar".  Directories
1183  * are not considered to be their own ancestors.  path must be in a
1184  * canonical form: empty components, or "." or ".." components are not
1185  * allowed.
1186  */
1187 int longest_ancestor_length(const char *path, struct string_list *prefixes)
1188 {
1189         int i, max_len = -1;
1190
1191         if (!strcmp(path, "/"))
1192                 return -1;
1193
1194         for (i = 0; i < prefixes->nr; i++) {
1195                 const char *ceil = prefixes->items[i].string;
1196                 int len = strlen(ceil);
1197
1198                 if (len == 1 && ceil[0] == '/')
1199                         len = 0; /* root matches anything, with length 0 */
1200                 else if (!strncmp(path, ceil, len) && path[len] == '/')
1201                         ; /* match of length len */
1202                 else
1203                         continue; /* no match */
1204
1205                 if (len > max_len)
1206                         max_len = len;
1207         }
1208
1209         return max_len;
1210 }
1211
1212 /* strip arbitrary amount of directory separators at end of path */
1213 static inline int chomp_trailing_dir_sep(const char *path, int len)
1214 {
1215         while (len && is_dir_sep(path[len - 1]))
1216                 len--;
1217         return len;
1218 }
1219
1220 /*
1221  * If path ends with suffix (complete path components), returns the
1222  * part before suffix (sans trailing directory separators).
1223  * Otherwise returns NULL.
1224  */
1225 char *strip_path_suffix(const char *path, const char *suffix)
1226 {
1227         int path_len = strlen(path), suffix_len = strlen(suffix);
1228
1229         while (suffix_len) {
1230                 if (!path_len)
1231                         return NULL;
1232
1233                 if (is_dir_sep(path[path_len - 1])) {
1234                         if (!is_dir_sep(suffix[suffix_len - 1]))
1235                                 return NULL;
1236                         path_len = chomp_trailing_dir_sep(path, path_len);
1237                         suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
1238                 }
1239                 else if (path[--path_len] != suffix[--suffix_len])
1240                         return NULL;
1241         }
1242
1243         if (path_len && !is_dir_sep(path[path_len - 1]))
1244                 return NULL;
1245         return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
1246 }
1247
1248 int daemon_avoid_alias(const char *p)
1249 {
1250         int sl, ndot;
1251
1252         /*
1253          * This resurrects the belts and suspenders paranoia check by HPA
1254          * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
1255          * does not do getcwd() based path canonicalization.
1256          *
1257          * sl becomes true immediately after seeing '/' and continues to
1258          * be true as long as dots continue after that without intervening
1259          * non-dot character.
1260          */
1261         if (!p || (*p != '/' && *p != '~'))
1262                 return -1;
1263         sl = 1; ndot = 0;
1264         p++;
1265
1266         while (1) {
1267                 char ch = *p++;
1268                 if (sl) {
1269                         if (ch == '.')
1270                                 ndot++;
1271                         else if (ch == '/') {
1272                                 if (ndot < 3)
1273                                         /* reject //, /./ and /../ */
1274                                         return -1;
1275                                 ndot = 0;
1276                         }
1277                         else if (ch == 0) {
1278                                 if (0 < ndot && ndot < 3)
1279                                         /* reject /.$ and /..$ */
1280                                         return -1;
1281                                 return 0;
1282                         }
1283                         else
1284                                 sl = ndot = 0;
1285                 }
1286                 else if (ch == 0)
1287                         return 0;
1288                 else if (ch == '/') {
1289                         sl = 1;
1290                         ndot = 0;
1291                 }
1292         }
1293 }
1294
1295 static int only_spaces_and_periods(const char *path, size_t len, size_t skip)
1296 {
1297         if (len < skip)
1298                 return 0;
1299         len -= skip;
1300         path += skip;
1301         while (len-- > 0) {
1302                 char c = *(path++);
1303                 if (c != ' ' && c != '.')
1304                         return 0;
1305         }
1306         return 1;
1307 }
1308
1309 int is_ntfs_dotgit(const char *name)
1310 {
1311         int len;
1312
1313         for (len = 0; ; len++)
1314                 if (!name[len] || name[len] == '\\' || is_dir_sep(name[len])) {
1315                         if (only_spaces_and_periods(name, len, 4) &&
1316                                         !strncasecmp(name, ".git", 4))
1317                                 return 1;
1318                         if (only_spaces_and_periods(name, len, 5) &&
1319                                         !strncasecmp(name, "git~1", 5))
1320                                 return 1;
1321                         if (name[len] != '\\')
1322                                 return 0;
1323                         name += len + 1;
1324                         len = -1;
1325                 }
1326 }
1327
1328 int looks_like_command_line_option(const char *str)
1329 {
1330         return str && str[0] == '-';
1331 }
1332
1333 char *xdg_config_home(const char *filename)
1334 {
1335         const char *home, *config_home;
1336
1337         assert(filename);
1338         config_home = getenv("XDG_CONFIG_HOME");
1339         if (config_home && *config_home)
1340                 return mkpathdup("%s/git/%s", config_home, filename);
1341
1342         home = getenv("HOME");
1343         if (home)
1344                 return mkpathdup("%s/.config/git/%s", home, filename);
1345         return NULL;
1346 }
1347
1348 char *xdg_cache_home(const char *filename)
1349 {
1350         const char *home, *cache_home;
1351
1352         assert(filename);
1353         cache_home = getenv("XDG_CACHE_HOME");
1354         if (cache_home && *cache_home)
1355                 return mkpathdup("%s/git/%s", cache_home, filename);
1356
1357         home = getenv("HOME");
1358         if (home)
1359                 return mkpathdup("%s/.cache/git/%s", home, filename);
1360         return NULL;
1361 }
1362
1363 GIT_PATH_FUNC(git_path_cherry_pick_head, "CHERRY_PICK_HEAD")
1364 GIT_PATH_FUNC(git_path_revert_head, "REVERT_HEAD")
1365 GIT_PATH_FUNC(git_path_squash_msg, "SQUASH_MSG")
1366 GIT_PATH_FUNC(git_path_merge_msg, "MERGE_MSG")
1367 GIT_PATH_FUNC(git_path_merge_rr, "MERGE_RR")
1368 GIT_PATH_FUNC(git_path_merge_mode, "MERGE_MODE")
1369 GIT_PATH_FUNC(git_path_merge_head, "MERGE_HEAD")
1370 GIT_PATH_FUNC(git_path_fetch_head, "FETCH_HEAD")
1371 GIT_PATH_FUNC(git_path_shallow, "shallow")