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