Merge branch 'js/icase-wt-detection'
[git] / setup.c
1 #include "cache.h"
2 #include "dir.h"
3 #include "string-list.h"
4
5 static int inside_git_dir = -1;
6 static int inside_work_tree = -1;
7 static int work_tree_config_is_bogus;
8
9 /*
10  * The input parameter must contain an absolute path, and it must already be
11  * normalized.
12  *
13  * Find the part of an absolute path that lies inside the work tree by
14  * dereferencing symlinks outside the work tree, for example:
15  * /dir1/repo/dir2/file   (work tree is /dir1/repo)      -> dir2/file
16  * /dir/file              (work tree is /)               -> dir/file
17  * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
18  * /dir/repolink/file     (repolink points to /dir/repo) -> file
19  * /dir/repo              (exactly equal to work tree)   -> (empty string)
20  */
21 static int abspath_part_inside_repo(char *path)
22 {
23         size_t len;
24         size_t wtlen;
25         char *path0;
26         int off;
27         const char *work_tree = get_git_work_tree();
28
29         if (!work_tree)
30                 return -1;
31         wtlen = strlen(work_tree);
32         len = strlen(path);
33         off = offset_1st_component(path);
34
35         /* check if work tree is already the prefix */
36         if (wtlen <= len && !strncmp(path, work_tree, wtlen)) {
37                 if (path[wtlen] == '/') {
38                         memmove(path, path + wtlen + 1, len - wtlen);
39                         return 0;
40                 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
41                         /* work tree is the root, or the whole path */
42                         memmove(path, path + wtlen, len - wtlen + 1);
43                         return 0;
44                 }
45                 /* work tree might match beginning of a symlink to work tree */
46                 off = wtlen;
47         }
48         path0 = path;
49         path += off;
50
51         /* check each '/'-terminated level */
52         while (*path) {
53                 path++;
54                 if (*path == '/') {
55                         *path = '\0';
56                         if (strcmp(real_path(path0), work_tree) == 0) {
57                                 memmove(path0, path + 1, len - (path - path0));
58                                 return 0;
59                         }
60                         *path = '/';
61                 }
62         }
63
64         /* check whole path */
65         if (strcmp(real_path(path0), work_tree) == 0) {
66                 *path0 = '\0';
67                 return 0;
68         }
69
70         return -1;
71 }
72
73 /*
74  * Normalize "path", prepending the "prefix" for relative paths. If
75  * remaining_prefix is not NULL, return the actual prefix still
76  * remains in the path. For example, prefix = sub1/sub2/ and path is
77  *
78  *  foo          -> sub1/sub2/foo  (full prefix)
79  *  ../foo       -> sub1/foo       (remaining prefix is sub1/)
80  *  ../../bar    -> bar            (no remaining prefix)
81  *  ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
82  *  `pwd`/../bar -> sub1/bar       (no remaining prefix)
83  */
84 char *prefix_path_gently(const char *prefix, int len,
85                          int *remaining_prefix, const char *path)
86 {
87         const char *orig = path;
88         char *sanitized;
89         if (is_absolute_path(orig)) {
90                 sanitized = xmalloc(strlen(path) + 1);
91                 if (remaining_prefix)
92                         *remaining_prefix = 0;
93                 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
94                         free(sanitized);
95                         return NULL;
96                 }
97                 if (abspath_part_inside_repo(sanitized)) {
98                         free(sanitized);
99                         return NULL;
100                 }
101         } else {
102                 sanitized = xmalloc(len + strlen(path) + 1);
103                 if (len)
104                         memcpy(sanitized, prefix, len);
105                 strcpy(sanitized + len, path);
106                 if (remaining_prefix)
107                         *remaining_prefix = len;
108                 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
109                         free(sanitized);
110                         return NULL;
111                 }
112         }
113         return sanitized;
114 }
115
116 char *prefix_path(const char *prefix, int len, const char *path)
117 {
118         char *r = prefix_path_gently(prefix, len, NULL, path);
119         if (!r)
120                 die("'%s' is outside repository", path);
121         return r;
122 }
123
124 int path_inside_repo(const char *prefix, const char *path)
125 {
126         int len = prefix ? strlen(prefix) : 0;
127         char *r = prefix_path_gently(prefix, len, NULL, path);
128         if (r) {
129                 free(r);
130                 return 1;
131         }
132         return 0;
133 }
134
135 int check_filename(const char *prefix, const char *arg)
136 {
137         const char *name;
138         struct stat st;
139
140         if (starts_with(arg, ":/")) {
141                 if (arg[2] == '\0') /* ":/" is root dir, always exists */
142                         return 1;
143                 name = arg + 2;
144         } else if (!no_wildcard(arg))
145                 return 1;
146         else if (prefix)
147                 name = prefix_filename(prefix, strlen(prefix), arg);
148         else
149                 name = arg;
150         if (!lstat(name, &st))
151                 return 1; /* file exists */
152         if (errno == ENOENT || errno == ENOTDIR)
153                 return 0; /* file does not exist */
154         die_errno("failed to stat '%s'", arg);
155 }
156
157 static void NORETURN die_verify_filename(const char *prefix,
158                                          const char *arg,
159                                          int diagnose_misspelt_rev)
160 {
161         if (!diagnose_misspelt_rev)
162                 die("%s: no such path in the working tree.\n"
163                     "Use 'git <command> -- <path>...' to specify paths that do not exist locally.",
164                     arg);
165         /*
166          * Saying "'(icase)foo' does not exist in the index" when the
167          * user gave us ":(icase)foo" is just stupid.  A magic pathspec
168          * begins with a colon and is followed by a non-alnum; do not
169          * let maybe_die_on_misspelt_object_name() even trigger.
170          */
171         if (!(arg[0] == ':' && !isalnum(arg[1])))
172                 maybe_die_on_misspelt_object_name(arg, prefix);
173
174         /* ... or fall back the most general message. */
175         die("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
176             "Use '--' to separate paths from revisions, like this:\n"
177             "'git <command> [<revision>...] -- [<file>...]'", arg);
178
179 }
180
181 /*
182  * Verify a filename that we got as an argument for a pathspec
183  * entry. Note that a filename that begins with "-" never verifies
184  * as true, because even if such a filename were to exist, we want
185  * it to be preceded by the "--" marker (or we want the user to
186  * use a format like "./-filename")
187  *
188  * The "diagnose_misspelt_rev" is used to provide a user-friendly
189  * diagnosis when dying upon finding that "name" is not a pathname.
190  * If set to 1, the diagnosis will try to diagnose "name" as an
191  * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
192  * will only complain about an inexisting file.
193  *
194  * This function is typically called to check that a "file or rev"
195  * argument is unambiguous. In this case, the caller will want
196  * diagnose_misspelt_rev == 1 when verifying the first non-rev
197  * argument (which could have been a revision), and
198  * diagnose_misspelt_rev == 0 for the next ones (because we already
199  * saw a filename, there's not ambiguity anymore).
200  */
201 void verify_filename(const char *prefix,
202                      const char *arg,
203                      int diagnose_misspelt_rev)
204 {
205         if (*arg == '-')
206                 die("bad flag '%s' used after filename", arg);
207         if (check_filename(prefix, arg))
208                 return;
209         die_verify_filename(prefix, arg, diagnose_misspelt_rev);
210 }
211
212 /*
213  * Opposite of the above: the command line did not have -- marker
214  * and we parsed the arg as a refname.  It should not be interpretable
215  * as a filename.
216  */
217 void verify_non_filename(const char *prefix, const char *arg)
218 {
219         if (!is_inside_work_tree() || is_inside_git_dir())
220                 return;
221         if (*arg == '-')
222                 return; /* flag */
223         if (!check_filename(prefix, arg))
224                 return;
225         die("ambiguous argument '%s': both revision and filename\n"
226             "Use '--' to separate paths from revisions, like this:\n"
227             "'git <command> [<revision>...] -- [<file>...]'", arg);
228 }
229
230 int get_common_dir(struct strbuf *sb, const char *gitdir)
231 {
232         const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
233         if (git_env_common_dir) {
234                 strbuf_addstr(sb, git_env_common_dir);
235                 return 1;
236         } else {
237                 return get_common_dir_noenv(sb, gitdir);
238         }
239 }
240
241 int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
242 {
243         struct strbuf data = STRBUF_INIT;
244         struct strbuf path = STRBUF_INIT;
245         int ret = 0;
246
247         strbuf_addf(&path, "%s/commondir", gitdir);
248         if (file_exists(path.buf)) {
249                 if (strbuf_read_file(&data, path.buf, 0) <= 0)
250                         die_errno(_("failed to read %s"), path.buf);
251                 while (data.len && (data.buf[data.len - 1] == '\n' ||
252                                     data.buf[data.len - 1] == '\r'))
253                         data.len--;
254                 data.buf[data.len] = '\0';
255                 strbuf_reset(&path);
256                 if (!is_absolute_path(data.buf))
257                         strbuf_addf(&path, "%s/", gitdir);
258                 strbuf_addbuf(&path, &data);
259                 strbuf_addstr(sb, real_path(path.buf));
260                 ret = 1;
261         } else
262                 strbuf_addstr(sb, gitdir);
263         strbuf_release(&data);
264         strbuf_release(&path);
265         return ret;
266 }
267
268 /*
269  * Test if it looks like we're at a git directory.
270  * We want to see:
271  *
272  *  - either an objects/ directory _or_ the proper
273  *    GIT_OBJECT_DIRECTORY environment variable
274  *  - a refs/ directory
275  *  - either a HEAD symlink or a HEAD file that is formatted as
276  *    a proper "ref:", or a regular file HEAD that has a properly
277  *    formatted sha1 object name.
278  */
279 int is_git_directory(const char *suspect)
280 {
281         struct strbuf path = STRBUF_INIT;
282         int ret = 0;
283         size_t len;
284
285         /* Check worktree-related signatures */
286         strbuf_addf(&path, "%s/HEAD", suspect);
287         if (validate_headref(path.buf))
288                 goto done;
289
290         strbuf_reset(&path);
291         get_common_dir(&path, suspect);
292         len = path.len;
293
294         /* Check non-worktree-related signatures */
295         if (getenv(DB_ENVIRONMENT)) {
296                 if (access(getenv(DB_ENVIRONMENT), X_OK))
297                         goto done;
298         }
299         else {
300                 strbuf_setlen(&path, len);
301                 strbuf_addstr(&path, "/objects");
302                 if (access(path.buf, X_OK))
303                         goto done;
304         }
305
306         strbuf_setlen(&path, len);
307         strbuf_addstr(&path, "/refs");
308         if (access(path.buf, X_OK))
309                 goto done;
310
311         ret = 1;
312 done:
313         strbuf_release(&path);
314         return ret;
315 }
316
317 int is_inside_git_dir(void)
318 {
319         if (inside_git_dir < 0)
320                 inside_git_dir = is_inside_dir(get_git_dir());
321         return inside_git_dir;
322 }
323
324 int is_inside_work_tree(void)
325 {
326         if (inside_work_tree < 0)
327                 inside_work_tree = is_inside_dir(get_git_work_tree());
328         return inside_work_tree;
329 }
330
331 void setup_work_tree(void)
332 {
333         const char *work_tree, *git_dir;
334         static int initialized = 0;
335
336         if (initialized)
337                 return;
338
339         if (work_tree_config_is_bogus)
340                 die("unable to set up work tree using invalid config");
341
342         work_tree = get_git_work_tree();
343         git_dir = get_git_dir();
344         if (!is_absolute_path(git_dir))
345                 git_dir = real_path(get_git_dir());
346         if (!work_tree || chdir(work_tree))
347                 die("This operation must be run in a work tree");
348
349         /*
350          * Make sure subsequent git processes find correct worktree
351          * if $GIT_WORK_TREE is set relative
352          */
353         if (getenv(GIT_WORK_TREE_ENVIRONMENT))
354                 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
355
356         set_git_dir(remove_leading_path(git_dir, work_tree));
357         initialized = 1;
358 }
359
360 static int check_repo_format(const char *var, const char *value, void *cb)
361 {
362         if (strcmp(var, "core.repositoryformatversion") == 0)
363                 repository_format_version = git_config_int(var, value);
364         else if (strcmp(var, "core.sharedrepository") == 0)
365                 shared_repository = git_config_perm(var, value);
366         return 0;
367 }
368
369 static int check_repository_format_gently(const char *gitdir, int *nongit_ok)
370 {
371         struct strbuf sb = STRBUF_INIT;
372         const char *repo_config;
373         config_fn_t fn;
374         int ret = 0;
375
376         if (get_common_dir(&sb, gitdir))
377                 fn = check_repo_format;
378         else
379                 fn = check_repository_format_version;
380         strbuf_addstr(&sb, "/config");
381         repo_config = sb.buf;
382
383         /*
384          * git_config() can't be used here because it calls git_pathdup()
385          * to get $GIT_CONFIG/config. That call will make setup_git_env()
386          * set git_dir to ".git".
387          *
388          * We are in gitdir setup, no git dir has been found useable yet.
389          * Use a gentler version of git_config() to check if this repo
390          * is a good one.
391          */
392         git_config_early(fn, NULL, repo_config);
393         if (GIT_REPO_VERSION < repository_format_version) {
394                 if (!nongit_ok)
395                         die ("Expected git repo version <= %d, found %d",
396                              GIT_REPO_VERSION, repository_format_version);
397                 warning("Expected git repo version <= %d, found %d",
398                         GIT_REPO_VERSION, repository_format_version);
399                 warning("Please upgrade Git");
400                 *nongit_ok = -1;
401                 ret = -1;
402         }
403         strbuf_release(&sb);
404         return ret;
405 }
406
407 static void update_linked_gitdir(const char *gitfile, const char *gitdir)
408 {
409         struct strbuf path = STRBUF_INIT;
410         struct stat st;
411
412         strbuf_addf(&path, "%s/gitdir", gitdir);
413         if (stat(path.buf, &st) || st.st_mtime + 24 * 3600 < time(NULL))
414                 write_file(path.buf, "%s", gitfile);
415         strbuf_release(&path);
416 }
417
418 /*
419  * Try to read the location of the git directory from the .git file,
420  * return path to git directory if found.
421  *
422  * On failure, if return_error_code is not NULL, return_error_code
423  * will be set to an error code and NULL will be returned. If
424  * return_error_code is NULL the function will die instead (for most
425  * cases).
426  */
427 const char *read_gitfile_gently(const char *path, int *return_error_code)
428 {
429         const int max_file_size = 1 << 20;  /* 1MB */
430         int error_code = 0;
431         char *buf = NULL;
432         char *dir = NULL;
433         const char *slash;
434         struct stat st;
435         int fd;
436         ssize_t len;
437
438         if (stat(path, &st)) {
439                 error_code = READ_GITFILE_ERR_STAT_FAILED;
440                 goto cleanup_return;
441         }
442         if (!S_ISREG(st.st_mode)) {
443                 error_code = READ_GITFILE_ERR_NOT_A_FILE;
444                 goto cleanup_return;
445         }
446         if (st.st_size > max_file_size) {
447                 error_code = READ_GITFILE_ERR_TOO_LARGE;
448                 goto cleanup_return;
449         }
450         fd = open(path, O_RDONLY);
451         if (fd < 0) {
452                 error_code = READ_GITFILE_ERR_OPEN_FAILED;
453                 goto cleanup_return;
454         }
455         buf = xmalloc(st.st_size + 1);
456         len = read_in_full(fd, buf, st.st_size);
457         close(fd);
458         if (len != st.st_size) {
459                 error_code = READ_GITFILE_ERR_READ_FAILED;
460                 goto cleanup_return;
461         }
462         buf[len] = '\0';
463         if (!starts_with(buf, "gitdir: ")) {
464                 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
465                 goto cleanup_return;
466         }
467         while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
468                 len--;
469         if (len < 9) {
470                 error_code = READ_GITFILE_ERR_NO_PATH;
471                 goto cleanup_return;
472         }
473         buf[len] = '\0';
474         dir = buf + 8;
475
476         if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
477                 size_t pathlen = slash+1 - path;
478                 size_t dirlen = pathlen + len - 8;
479                 dir = xmalloc(dirlen + 1);
480                 strncpy(dir, path, pathlen);
481                 strncpy(dir + pathlen, buf + 8, len - 8);
482                 dir[dirlen] = '\0';
483                 free(buf);
484                 buf = dir;
485         }
486         if (!is_git_directory(dir)) {
487                 error_code = READ_GITFILE_ERR_NOT_A_REPO;
488                 goto cleanup_return;
489         }
490         update_linked_gitdir(path, dir);
491         path = real_path(dir);
492
493 cleanup_return:
494         if (return_error_code)
495                 *return_error_code = error_code;
496         else if (error_code) {
497                 switch (error_code) {
498                 case READ_GITFILE_ERR_STAT_FAILED:
499                 case READ_GITFILE_ERR_NOT_A_FILE:
500                         /* non-fatal; follow return path */
501                         break;
502                 case READ_GITFILE_ERR_OPEN_FAILED:
503                         die_errno("Error opening '%s'", path);
504                 case READ_GITFILE_ERR_TOO_LARGE:
505                         die("Too large to be a .git file: '%s'", path);
506                 case READ_GITFILE_ERR_READ_FAILED:
507                         die("Error reading %s", path);
508                 case READ_GITFILE_ERR_INVALID_FORMAT:
509                         die("Invalid gitfile format: %s", path);
510                 case READ_GITFILE_ERR_NO_PATH:
511                         die("No path in gitfile: %s", path);
512                 case READ_GITFILE_ERR_NOT_A_REPO:
513                         die("Not a git repository: %s", dir);
514                 default:
515                         assert(0);
516                 }
517         }
518
519         free(buf);
520         return error_code ? NULL : path;
521 }
522
523 static const char *setup_explicit_git_dir(const char *gitdirenv,
524                                           struct strbuf *cwd,
525                                           int *nongit_ok)
526 {
527         const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
528         const char *worktree;
529         char *gitfile;
530         int offset;
531
532         if (PATH_MAX - 40 < strlen(gitdirenv))
533                 die("'$%s' too big", GIT_DIR_ENVIRONMENT);
534
535         gitfile = (char*)read_gitfile(gitdirenv);
536         if (gitfile) {
537                 gitfile = xstrdup(gitfile);
538                 gitdirenv = gitfile;
539         }
540
541         if (!is_git_directory(gitdirenv)) {
542                 if (nongit_ok) {
543                         *nongit_ok = 1;
544                         free(gitfile);
545                         return NULL;
546                 }
547                 die("Not a git repository: '%s'", gitdirenv);
548         }
549
550         if (check_repository_format_gently(gitdirenv, nongit_ok)) {
551                 free(gitfile);
552                 return NULL;
553         }
554
555         /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
556         if (work_tree_env)
557                 set_git_work_tree(work_tree_env);
558         else if (is_bare_repository_cfg > 0) {
559                 if (git_work_tree_cfg) {
560                         /* #22.2, #30 */
561                         warning("core.bare and core.worktree do not make sense");
562                         work_tree_config_is_bogus = 1;
563                 }
564
565                 /* #18, #26 */
566                 set_git_dir(gitdirenv);
567                 free(gitfile);
568                 return NULL;
569         }
570         else if (git_work_tree_cfg) { /* #6, #14 */
571                 if (is_absolute_path(git_work_tree_cfg))
572                         set_git_work_tree(git_work_tree_cfg);
573                 else {
574                         char *core_worktree;
575                         if (chdir(gitdirenv))
576                                 die_errno("Could not chdir to '%s'", gitdirenv);
577                         if (chdir(git_work_tree_cfg))
578                                 die_errno("Could not chdir to '%s'", git_work_tree_cfg);
579                         core_worktree = xgetcwd();
580                         if (chdir(cwd->buf))
581                                 die_errno("Could not come back to cwd");
582                         set_git_work_tree(core_worktree);
583                         free(core_worktree);
584                 }
585         }
586         else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
587                 /* #16d */
588                 set_git_dir(gitdirenv);
589                 free(gitfile);
590                 return NULL;
591         }
592         else /* #2, #10 */
593                 set_git_work_tree(".");
594
595         /* set_git_work_tree() must have been called by now */
596         worktree = get_git_work_tree();
597
598         /* both get_git_work_tree() and cwd are already normalized */
599         if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
600                 set_git_dir(gitdirenv);
601                 free(gitfile);
602                 return NULL;
603         }
604
605         offset = dir_inside_of(cwd->buf, worktree);
606         if (offset >= 0) {      /* cwd inside worktree? */
607                 set_git_dir(real_path(gitdirenv));
608                 if (chdir(worktree))
609                         die_errno("Could not chdir to '%s'", worktree);
610                 strbuf_addch(cwd, '/');
611                 free(gitfile);
612                 return cwd->buf + offset;
613         }
614
615         /* cwd outside worktree */
616         set_git_dir(gitdirenv);
617         free(gitfile);
618         return NULL;
619 }
620
621 static const char *setup_discovered_git_dir(const char *gitdir,
622                                             struct strbuf *cwd, int offset,
623                                             int *nongit_ok)
624 {
625         if (check_repository_format_gently(gitdir, nongit_ok))
626                 return NULL;
627
628         /* --work-tree is set without --git-dir; use discovered one */
629         if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
630                 if (offset != cwd->len && !is_absolute_path(gitdir))
631                         gitdir = xstrdup(real_path(gitdir));
632                 if (chdir(cwd->buf))
633                         die_errno("Could not come back to cwd");
634                 return setup_explicit_git_dir(gitdir, cwd, nongit_ok);
635         }
636
637         /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
638         if (is_bare_repository_cfg > 0) {
639                 set_git_dir(offset == cwd->len ? gitdir : real_path(gitdir));
640                 if (chdir(cwd->buf))
641                         die_errno("Could not come back to cwd");
642                 return NULL;
643         }
644
645         /* #0, #1, #5, #8, #9, #12, #13 */
646         set_git_work_tree(".");
647         if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
648                 set_git_dir(gitdir);
649         inside_git_dir = 0;
650         inside_work_tree = 1;
651         if (offset == cwd->len)
652                 return NULL;
653
654         /* Make "offset" point to past the '/', and add a '/' at the end */
655         offset++;
656         strbuf_addch(cwd, '/');
657         return cwd->buf + offset;
658 }
659
660 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
661 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
662                                       int *nongit_ok)
663 {
664         int root_len;
665
666         if (check_repository_format_gently(".", nongit_ok))
667                 return NULL;
668
669         setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
670
671         /* --work-tree is set without --git-dir; use discovered one */
672         if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
673                 const char *gitdir;
674
675                 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
676                 if (chdir(cwd->buf))
677                         die_errno("Could not come back to cwd");
678                 return setup_explicit_git_dir(gitdir, cwd, nongit_ok);
679         }
680
681         inside_git_dir = 1;
682         inside_work_tree = 0;
683         if (offset != cwd->len) {
684                 if (chdir(cwd->buf))
685                         die_errno("Cannot come back to cwd");
686                 root_len = offset_1st_component(cwd->buf);
687                 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
688                 set_git_dir(cwd->buf);
689         }
690         else
691                 set_git_dir(".");
692         return NULL;
693 }
694
695 static const char *setup_nongit(const char *cwd, int *nongit_ok)
696 {
697         if (!nongit_ok)
698                 die("Not a git repository (or any of the parent directories): %s", DEFAULT_GIT_DIR_ENVIRONMENT);
699         if (chdir(cwd))
700                 die_errno("Cannot come back to cwd");
701         *nongit_ok = 1;
702         return NULL;
703 }
704
705 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
706 {
707         struct stat buf;
708         if (stat(path, &buf)) {
709                 die_errno("failed to stat '%*s%s%s'",
710                                 prefix_len,
711                                 prefix ? prefix : "",
712                                 prefix ? "/" : "", path);
713         }
714         return buf.st_dev;
715 }
716
717 /*
718  * A "string_list_each_func_t" function that canonicalizes an entry
719  * from GIT_CEILING_DIRECTORIES using real_path_if_valid(), or
720  * discards it if unusable.  The presence of an empty entry in
721  * GIT_CEILING_DIRECTORIES turns off canonicalization for all
722  * subsequent entries.
723  */
724 static int canonicalize_ceiling_entry(struct string_list_item *item,
725                                       void *cb_data)
726 {
727         int *empty_entry_found = cb_data;
728         char *ceil = item->string;
729
730         if (!*ceil) {
731                 *empty_entry_found = 1;
732                 return 0;
733         } else if (!is_absolute_path(ceil)) {
734                 return 0;
735         } else if (*empty_entry_found) {
736                 /* Keep entry but do not canonicalize it */
737                 return 1;
738         } else {
739                 const char *real_path = real_path_if_valid(ceil);
740                 if (!real_path)
741                         return 0;
742                 free(item->string);
743                 item->string = xstrdup(real_path);
744                 return 1;
745         }
746 }
747
748 /*
749  * We cannot decide in this function whether we are in the work tree or
750  * not, since the config can only be read _after_ this function was called.
751  */
752 static const char *setup_git_directory_gently_1(int *nongit_ok)
753 {
754         const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
755         struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
756         static struct strbuf cwd = STRBUF_INIT;
757         const char *gitdirenv, *ret;
758         char *gitfile;
759         int offset, offset_parent, ceil_offset = -1;
760         dev_t current_device = 0;
761         int one_filesystem = 1;
762
763         /*
764          * We may have read an incomplete configuration before
765          * setting-up the git directory. If so, clear the cache so
766          * that the next queries to the configuration reload complete
767          * configuration (including the per-repo config file that we
768          * ignored previously).
769          */
770         git_config_clear();
771
772         /*
773          * Let's assume that we are in a git repository.
774          * If it turns out later that we are somewhere else, the value will be
775          * updated accordingly.
776          */
777         if (nongit_ok)
778                 *nongit_ok = 0;
779
780         if (strbuf_getcwd(&cwd))
781                 die_errno("Unable to read current working directory");
782         offset = cwd.len;
783
784         /*
785          * If GIT_DIR is set explicitly, we're not going
786          * to do any discovery, but we still do repository
787          * validation.
788          */
789         gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
790         if (gitdirenv)
791                 return setup_explicit_git_dir(gitdirenv, &cwd, nongit_ok);
792
793         if (env_ceiling_dirs) {
794                 int empty_entry_found = 0;
795
796                 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
797                 filter_string_list(&ceiling_dirs, 0,
798                                    canonicalize_ceiling_entry, &empty_entry_found);
799                 ceil_offset = longest_ancestor_length(cwd.buf, &ceiling_dirs);
800                 string_list_clear(&ceiling_dirs, 0);
801         }
802
803         if (ceil_offset < 0 && has_dos_drive_prefix(cwd.buf))
804                 ceil_offset = 1;
805
806         /*
807          * Test in the following order (relative to the cwd):
808          * - .git (file containing "gitdir: <path>")
809          * - .git/
810          * - ./ (bare)
811          * - ../.git
812          * - ../.git/
813          * - ../ (bare)
814          * - ../../.git/
815          *   etc.
816          */
817         one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
818         if (one_filesystem)
819                 current_device = get_device_or_die(".", NULL, 0);
820         for (;;) {
821                 gitfile = (char*)read_gitfile(DEFAULT_GIT_DIR_ENVIRONMENT);
822                 if (gitfile)
823                         gitdirenv = gitfile = xstrdup(gitfile);
824                 else {
825                         if (is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT))
826                                 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
827                 }
828
829                 if (gitdirenv) {
830                         ret = setup_discovered_git_dir(gitdirenv,
831                                                        &cwd, offset,
832                                                        nongit_ok);
833                         free(gitfile);
834                         return ret;
835                 }
836                 free(gitfile);
837
838                 if (is_git_directory("."))
839                         return setup_bare_git_dir(&cwd, offset, nongit_ok);
840
841                 offset_parent = offset;
842                 while (--offset_parent > ceil_offset && cwd.buf[offset_parent] != '/');
843                 if (offset_parent <= ceil_offset)
844                         return setup_nongit(cwd.buf, nongit_ok);
845                 if (one_filesystem) {
846                         dev_t parent_device = get_device_or_die("..", cwd.buf,
847                                                                 offset);
848                         if (parent_device != current_device) {
849                                 if (nongit_ok) {
850                                         if (chdir(cwd.buf))
851                                                 die_errno("Cannot come back to cwd");
852                                         *nongit_ok = 1;
853                                         return NULL;
854                                 }
855                                 strbuf_setlen(&cwd, offset);
856                                 die("Not a git repository (or any parent up to mount point %s)\n"
857                                 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).",
858                                     cwd.buf);
859                         }
860                 }
861                 if (chdir("..")) {
862                         strbuf_setlen(&cwd, offset);
863                         die_errno("Cannot change to '%s/..'", cwd.buf);
864                 }
865                 offset = offset_parent;
866         }
867 }
868
869 const char *setup_git_directory_gently(int *nongit_ok)
870 {
871         const char *prefix;
872
873         prefix = setup_git_directory_gently_1(nongit_ok);
874         if (prefix)
875                 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
876         else
877                 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
878
879         if (startup_info) {
880                 startup_info->have_repository = !nongit_ok || !*nongit_ok;
881                 startup_info->prefix = prefix;
882         }
883         return prefix;
884 }
885
886 int git_config_perm(const char *var, const char *value)
887 {
888         int i;
889         char *endptr;
890
891         if (value == NULL)
892                 return PERM_GROUP;
893
894         if (!strcmp(value, "umask"))
895                 return PERM_UMASK;
896         if (!strcmp(value, "group"))
897                 return PERM_GROUP;
898         if (!strcmp(value, "all") ||
899             !strcmp(value, "world") ||
900             !strcmp(value, "everybody"))
901                 return PERM_EVERYBODY;
902
903         /* Parse octal numbers */
904         i = strtol(value, &endptr, 8);
905
906         /* If not an octal number, maybe true/false? */
907         if (*endptr != 0)
908                 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
909
910         /*
911          * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
912          * a chmod value to restrict to.
913          */
914         switch (i) {
915         case PERM_UMASK:               /* 0 */
916                 return PERM_UMASK;
917         case OLD_PERM_GROUP:           /* 1 */
918                 return PERM_GROUP;
919         case OLD_PERM_EVERYBODY:       /* 2 */
920                 return PERM_EVERYBODY;
921         }
922
923         /* A filemode value was given: 0xxx */
924
925         if ((i & 0600) != 0600)
926                 die("Problem with core.sharedRepository filemode value "
927                     "(0%.3o).\nThe owner of files must always have "
928                     "read and write permissions.", i);
929
930         /*
931          * Mask filemode value. Others can not get write permission.
932          * x flags for directories are handled separately.
933          */
934         return -(i & 0666);
935 }
936
937 int check_repository_format_version(const char *var, const char *value, void *cb)
938 {
939         int ret = check_repo_format(var, value, cb);
940         if (ret)
941                 return ret;
942         if (strcmp(var, "core.bare") == 0) {
943                 is_bare_repository_cfg = git_config_bool(var, value);
944                 if (is_bare_repository_cfg == 1)
945                         inside_work_tree = -1;
946         } else if (strcmp(var, "core.worktree") == 0) {
947                 if (!value)
948                         return config_error_nonbool(var);
949                 free(git_work_tree_cfg);
950                 git_work_tree_cfg = xstrdup(value);
951                 inside_work_tree = -1;
952         }
953         return 0;
954 }
955
956 int check_repository_format(void)
957 {
958         return check_repository_format_gently(get_git_dir(), NULL);
959 }
960
961 /*
962  * Returns the "prefix", a path to the current working directory
963  * relative to the work tree root, or NULL, if the current working
964  * directory is not a strict subdirectory of the work tree root. The
965  * prefix always ends with a '/' character.
966  */
967 const char *setup_git_directory(void)
968 {
969         return setup_git_directory_gently(NULL);
970 }
971
972 const char *resolve_gitdir(const char *suspect)
973 {
974         if (is_git_directory(suspect))
975                 return suspect;
976         return read_gitfile(suspect);
977 }
978
979 /* if any standard file descriptor is missing open it to /dev/null */
980 void sanitize_stdfds(void)
981 {
982         int fd = open("/dev/null", O_RDWR, 0);
983         while (fd != -1 && fd < 2)
984                 fd = dup(fd);
985         if (fd == -1)
986                 die_errno("open /dev/null or dup failed");
987         if (fd > 2)
988                 close(fd);
989 }
990
991 int daemonize(void)
992 {
993 #ifdef NO_POSIX_GOODIES
994         errno = ENOSYS;
995         return -1;
996 #else
997         switch (fork()) {
998                 case 0:
999                         break;
1000                 case -1:
1001                         die_errno("fork failed");
1002                 default:
1003                         exit(0);
1004         }
1005         if (setsid() == -1)
1006                 die_errno("setsid failed");
1007         close(0);
1008         close(1);
1009         close(2);
1010         sanitize_stdfds();
1011         return 0;
1012 #endif
1013 }