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