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