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