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