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