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