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