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