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