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