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