Git 2.25-rc0
[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 = offset_1st_component(dir->buf);
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         if (min_offset && min_offset == dir->len &&
952             !is_dir_sep(dir->buf[min_offset - 1])) {
953                 strbuf_addch(dir, '/');
954                 min_offset++;
955         }
956
957         /*
958          * Test in the following order (relative to the dir):
959          * - .git (file containing "gitdir: <path>")
960          * - .git/
961          * - ./ (bare)
962          * - ../.git
963          * - ../.git/
964          * - ../ (bare)
965          * - ../../.git
966          *   etc.
967          */
968         one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
969         if (one_filesystem)
970                 current_device = get_device_or_die(dir->buf, NULL, 0);
971         for (;;) {
972                 int offset = dir->len, error_code = 0;
973
974                 if (offset > min_offset)
975                         strbuf_addch(dir, '/');
976                 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
977                 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
978                                                 NULL : &error_code);
979                 if (!gitdirenv) {
980                         if (die_on_error ||
981                             error_code == READ_GITFILE_ERR_NOT_A_FILE) {
982                                 /* NEEDSWORK: fail if .git is not file nor dir */
983                                 if (is_git_directory(dir->buf))
984                                         gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
985                         } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
986                                 return GIT_DIR_INVALID_GITFILE;
987                 }
988                 strbuf_setlen(dir, offset);
989                 if (gitdirenv) {
990                         strbuf_addstr(gitdir, gitdirenv);
991                         return GIT_DIR_DISCOVERED;
992                 }
993
994                 if (is_git_directory(dir->buf)) {
995                         strbuf_addstr(gitdir, ".");
996                         return GIT_DIR_BARE;
997                 }
998
999                 if (offset <= min_offset)
1000                         return GIT_DIR_HIT_CEILING;
1001
1002                 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1003                         ; /* continue */
1004                 if (offset <= ceil_offset)
1005                         return GIT_DIR_HIT_CEILING;
1006
1007                 strbuf_setlen(dir, offset > min_offset ?  offset : min_offset);
1008                 if (one_filesystem &&
1009                     current_device != get_device_or_die(dir->buf, NULL, offset))
1010                         return GIT_DIR_HIT_MOUNT_POINT;
1011         }
1012 }
1013
1014 int discover_git_directory(struct strbuf *commondir,
1015                            struct strbuf *gitdir)
1016 {
1017         struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1018         size_t gitdir_offset = gitdir->len, cwd_len;
1019         size_t commondir_offset = commondir->len;
1020         struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1021
1022         if (strbuf_getcwd(&dir))
1023                 return -1;
1024
1025         cwd_len = dir.len;
1026         if (setup_git_directory_gently_1(&dir, gitdir, 0) <= 0) {
1027                 strbuf_release(&dir);
1028                 return -1;
1029         }
1030
1031         /*
1032          * The returned gitdir is relative to dir, and if dir does not reflect
1033          * the current working directory, we simply make the gitdir absolute.
1034          */
1035         if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1036                 /* Avoid a trailing "/." */
1037                 if (!strcmp(".", gitdir->buf + gitdir_offset))
1038                         strbuf_setlen(gitdir, gitdir_offset);
1039                 else
1040                         strbuf_addch(&dir, '/');
1041                 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1042         }
1043
1044         get_common_dir(commondir, gitdir->buf + gitdir_offset);
1045
1046         strbuf_reset(&dir);
1047         strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1048         read_repository_format(&candidate, dir.buf);
1049         strbuf_release(&dir);
1050
1051         if (verify_repository_format(&candidate, &err) < 0) {
1052                 warning("ignoring git dir '%s': %s",
1053                         gitdir->buf + gitdir_offset, err.buf);
1054                 strbuf_release(&err);
1055                 strbuf_setlen(commondir, commondir_offset);
1056                 strbuf_setlen(gitdir, gitdir_offset);
1057                 clear_repository_format(&candidate);
1058                 return -1;
1059         }
1060
1061         clear_repository_format(&candidate);
1062         return 0;
1063 }
1064
1065 const char *setup_git_directory_gently(int *nongit_ok)
1066 {
1067         static struct strbuf cwd = STRBUF_INIT;
1068         struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT;
1069         const char *prefix = NULL;
1070         struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1071
1072         /*
1073          * We may have read an incomplete configuration before
1074          * setting-up the git directory. If so, clear the cache so
1075          * that the next queries to the configuration reload complete
1076          * configuration (including the per-repo config file that we
1077          * ignored previously).
1078          */
1079         git_config_clear();
1080
1081         /*
1082          * Let's assume that we are in a git repository.
1083          * If it turns out later that we are somewhere else, the value will be
1084          * updated accordingly.
1085          */
1086         if (nongit_ok)
1087                 *nongit_ok = 0;
1088
1089         if (strbuf_getcwd(&cwd))
1090                 die_errno(_("Unable to read current working directory"));
1091         strbuf_addbuf(&dir, &cwd);
1092
1093         switch (setup_git_directory_gently_1(&dir, &gitdir, 1)) {
1094         case GIT_DIR_EXPLICIT:
1095                 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1096                 break;
1097         case GIT_DIR_DISCOVERED:
1098                 if (dir.len < cwd.len && chdir(dir.buf))
1099                         die(_("cannot change to '%s'"), dir.buf);
1100                 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1101                                                   &repo_fmt, nongit_ok);
1102                 break;
1103         case GIT_DIR_BARE:
1104                 if (dir.len < cwd.len && chdir(dir.buf))
1105                         die(_("cannot change to '%s'"), dir.buf);
1106                 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1107                 break;
1108         case GIT_DIR_HIT_CEILING:
1109                 if (!nongit_ok)
1110                         die(_("not a git repository (or any of the parent directories): %s"),
1111                             DEFAULT_GIT_DIR_ENVIRONMENT);
1112                 *nongit_ok = 1;
1113                 break;
1114         case GIT_DIR_HIT_MOUNT_POINT:
1115                 if (!nongit_ok)
1116                         die(_("not a git repository (or any parent up to mount point %s)\n"
1117                               "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1118                             dir.buf);
1119                 *nongit_ok = 1;
1120                 break;
1121         case GIT_DIR_NONE:
1122                 /*
1123                  * As a safeguard against setup_git_directory_gently_1 returning
1124                  * this value, fallthrough to BUG. Otherwise it is possible to
1125                  * set startup_info->have_repository to 1 when we did nothing to
1126                  * find a repository.
1127                  */
1128         default:
1129                 BUG("unhandled setup_git_directory_1() result");
1130         }
1131
1132         /*
1133          * At this point, nongit_ok is stable. If it is non-NULL and points
1134          * to a non-zero value, then this means that we haven't found a
1135          * repository and that the caller expects startup_info to reflect
1136          * this.
1137          *
1138          * Regardless of the state of nongit_ok, startup_info->prefix and
1139          * the GIT_PREFIX environment variable must always match. For details
1140          * see Documentation/config/alias.txt.
1141          */
1142         if (nongit_ok && *nongit_ok) {
1143                 startup_info->have_repository = 0;
1144                 startup_info->prefix = NULL;
1145                 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1146         } else {
1147                 startup_info->have_repository = 1;
1148                 startup_info->prefix = prefix;
1149                 if (prefix)
1150                         setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1151                 else
1152                         setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1153         }
1154
1155         /*
1156          * Not all paths through the setup code will call 'set_git_dir()' (which
1157          * directly sets up the environment) so in order to guarantee that the
1158          * environment is in a consistent state after setup, explicitly setup
1159          * the environment if we have a repository.
1160          *
1161          * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1162          * code paths so we also need to explicitly setup the environment if
1163          * the user has set GIT_DIR.  It may be beneficial to disallow bogus
1164          * GIT_DIR values at some point in the future.
1165          */
1166         if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1167             startup_info->have_repository ||
1168             /* GIT_DIR_EXPLICIT */
1169             getenv(GIT_DIR_ENVIRONMENT)) {
1170                 if (!the_repository->gitdir) {
1171                         const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1172                         if (!gitdir)
1173                                 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1174                         setup_git_env(gitdir);
1175                 }
1176                 if (startup_info->have_repository)
1177                         repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1178         }
1179
1180         strbuf_release(&dir);
1181         strbuf_release(&gitdir);
1182         clear_repository_format(&repo_fmt);
1183
1184         return prefix;
1185 }
1186
1187 int git_config_perm(const char *var, const char *value)
1188 {
1189         int i;
1190         char *endptr;
1191
1192         if (value == NULL)
1193                 return PERM_GROUP;
1194
1195         if (!strcmp(value, "umask"))
1196                 return PERM_UMASK;
1197         if (!strcmp(value, "group"))
1198                 return PERM_GROUP;
1199         if (!strcmp(value, "all") ||
1200             !strcmp(value, "world") ||
1201             !strcmp(value, "everybody"))
1202                 return PERM_EVERYBODY;
1203
1204         /* Parse octal numbers */
1205         i = strtol(value, &endptr, 8);
1206
1207         /* If not an octal number, maybe true/false? */
1208         if (*endptr != 0)
1209                 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1210
1211         /*
1212          * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1213          * a chmod value to restrict to.
1214          */
1215         switch (i) {
1216         case PERM_UMASK:               /* 0 */
1217                 return PERM_UMASK;
1218         case OLD_PERM_GROUP:           /* 1 */
1219                 return PERM_GROUP;
1220         case OLD_PERM_EVERYBODY:       /* 2 */
1221                 return PERM_EVERYBODY;
1222         }
1223
1224         /* A filemode value was given: 0xxx */
1225
1226         if ((i & 0600) != 0600)
1227                 die(_("problem with core.sharedRepository filemode value "
1228                     "(0%.3o).\nThe owner of files must always have "
1229                     "read and write permissions."), i);
1230
1231         /*
1232          * Mask filemode value. Others can not get write permission.
1233          * x flags for directories are handled separately.
1234          */
1235         return -(i & 0666);
1236 }
1237
1238 void check_repository_format(void)
1239 {
1240         struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1241         check_repository_format_gently(get_git_dir(), &repo_fmt, NULL);
1242         startup_info->have_repository = 1;
1243         clear_repository_format(&repo_fmt);
1244 }
1245
1246 /*
1247  * Returns the "prefix", a path to the current working directory
1248  * relative to the work tree root, or NULL, if the current working
1249  * directory is not a strict subdirectory of the work tree root. The
1250  * prefix always ends with a '/' character.
1251  */
1252 const char *setup_git_directory(void)
1253 {
1254         return setup_git_directory_gently(NULL);
1255 }
1256
1257 const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1258 {
1259         if (is_git_directory(suspect))
1260                 return suspect;
1261         return read_gitfile_gently(suspect, return_error_code);
1262 }
1263
1264 /* if any standard file descriptor is missing open it to /dev/null */
1265 void sanitize_stdfds(void)
1266 {
1267         int fd = open("/dev/null", O_RDWR, 0);
1268         while (fd != -1 && fd < 2)
1269                 fd = dup(fd);
1270         if (fd == -1)
1271                 die_errno(_("open /dev/null or dup failed"));
1272         if (fd > 2)
1273                 close(fd);
1274 }
1275
1276 int daemonize(void)
1277 {
1278 #ifdef NO_POSIX_GOODIES
1279         errno = ENOSYS;
1280         return -1;
1281 #else
1282         switch (fork()) {
1283                 case 0:
1284                         break;
1285                 case -1:
1286                         die_errno(_("fork failed"));
1287                 default:
1288                         exit(0);
1289         }
1290         if (setsid() == -1)
1291                 die_errno(_("setsid failed"));
1292         close(0);
1293         close(1);
1294         close(2);
1295         sanitize_stdfds();
1296         return 0;
1297 #endif
1298 }