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