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