]> git.ipfire.org Git - thirdparty/git.git/blob - setup.c
Merge branch 'ab/remove-implicit-use-of-the-repository' into en/header-split-cache-h
[thirdparty/git.git] / setup.c
1 #include "cache.h"
2 #include "abspath.h"
3 #include "environment.h"
4 #include "gettext.h"
5 #include "repository.h"
6 #include "config.h"
7 #include "dir.h"
8 #include "setup.h"
9 #include "string-list.h"
10 #include "chdir-notify.h"
11 #include "promisor-remote.h"
12 #include "quote.h"
13
14 static int inside_git_dir = -1;
15 static int inside_work_tree = -1;
16 static int work_tree_config_is_bogus;
17 enum allowed_bare_repo {
18 ALLOWED_BARE_REPO_EXPLICIT = 0,
19 ALLOWED_BARE_REPO_ALL,
20 };
21
22 static struct startup_info the_startup_info;
23 struct startup_info *startup_info = &the_startup_info;
24 const char *tmp_original_cwd;
25
26 /*
27 * The input parameter must contain an absolute path, and it must already be
28 * normalized.
29 *
30 * Find the part of an absolute path that lies inside the work tree by
31 * dereferencing symlinks outside the work tree, for example:
32 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
33 * /dir/file (work tree is /) -> dir/file
34 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
35 * /dir/repolink/file (repolink points to /dir/repo) -> file
36 * /dir/repo (exactly equal to work tree) -> (empty string)
37 */
38 static int abspath_part_inside_repo(char *path)
39 {
40 size_t len;
41 size_t wtlen;
42 char *path0;
43 int off;
44 const char *work_tree = get_git_work_tree();
45 struct strbuf realpath = STRBUF_INIT;
46
47 if (!work_tree)
48 return -1;
49 wtlen = strlen(work_tree);
50 len = strlen(path);
51 off = offset_1st_component(path);
52
53 /* check if work tree is already the prefix */
54 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
55 if (path[wtlen] == '/') {
56 memmove(path, path + wtlen + 1, len - wtlen);
57 return 0;
58 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
59 /* work tree is the root, or the whole path */
60 memmove(path, path + wtlen, len - wtlen + 1);
61 return 0;
62 }
63 /* work tree might match beginning of a symlink to work tree */
64 off = wtlen;
65 }
66 path0 = path;
67 path += off;
68
69 /* check each '/'-terminated level */
70 while (*path) {
71 path++;
72 if (*path == '/') {
73 *path = '\0';
74 strbuf_realpath(&realpath, path0, 1);
75 if (fspathcmp(realpath.buf, work_tree) == 0) {
76 memmove(path0, path + 1, len - (path - path0));
77 strbuf_release(&realpath);
78 return 0;
79 }
80 *path = '/';
81 }
82 }
83
84 /* check whole path */
85 strbuf_realpath(&realpath, path0, 1);
86 if (fspathcmp(realpath.buf, work_tree) == 0) {
87 *path0 = '\0';
88 strbuf_release(&realpath);
89 return 0;
90 }
91
92 strbuf_release(&realpath);
93 return -1;
94 }
95
96 /*
97 * Normalize "path", prepending the "prefix" for relative paths. If
98 * remaining_prefix is not NULL, return the actual prefix still
99 * remains in the path. For example, prefix = sub1/sub2/ and path is
100 *
101 * foo -> sub1/sub2/foo (full prefix)
102 * ../foo -> sub1/foo (remaining prefix is sub1/)
103 * ../../bar -> bar (no remaining prefix)
104 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
105 * `pwd`/../bar -> sub1/bar (no remaining prefix)
106 */
107 char *prefix_path_gently(const char *prefix, int len,
108 int *remaining_prefix, const char *path)
109 {
110 const char *orig = path;
111 char *sanitized;
112 if (is_absolute_path(orig)) {
113 sanitized = xmallocz(strlen(path));
114 if (remaining_prefix)
115 *remaining_prefix = 0;
116 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
117 free(sanitized);
118 return NULL;
119 }
120 if (abspath_part_inside_repo(sanitized)) {
121 free(sanitized);
122 return NULL;
123 }
124 } else {
125 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
126 if (remaining_prefix)
127 *remaining_prefix = len;
128 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
129 free(sanitized);
130 return NULL;
131 }
132 }
133 return sanitized;
134 }
135
136 char *prefix_path(const char *prefix, int len, const char *path)
137 {
138 char *r = prefix_path_gently(prefix, len, NULL, path);
139 if (!r) {
140 const char *hint_path = get_git_work_tree();
141 if (!hint_path)
142 hint_path = get_git_dir();
143 die(_("'%s' is outside repository at '%s'"), path,
144 absolute_path(hint_path));
145 }
146 return r;
147 }
148
149 int path_inside_repo(const char *prefix, const char *path)
150 {
151 int len = prefix ? strlen(prefix) : 0;
152 char *r = prefix_path_gently(prefix, len, NULL, path);
153 if (r) {
154 free(r);
155 return 1;
156 }
157 return 0;
158 }
159
160 int check_filename(const char *prefix, const char *arg)
161 {
162 char *to_free = NULL;
163 struct stat st;
164
165 if (skip_prefix(arg, ":/", &arg)) {
166 if (!*arg) /* ":/" is root dir, always exists */
167 return 1;
168 prefix = NULL;
169 } else if (skip_prefix(arg, ":!", &arg) ||
170 skip_prefix(arg, ":^", &arg)) {
171 if (!*arg) /* excluding everything is silly, but allowed */
172 return 1;
173 }
174
175 if (prefix)
176 arg = to_free = prefix_filename(prefix, arg);
177
178 if (!lstat(arg, &st)) {
179 free(to_free);
180 return 1; /* file exists */
181 }
182 if (is_missing_file_error(errno)) {
183 free(to_free);
184 return 0; /* file does not exist */
185 }
186 die_errno(_("failed to stat '%s'"), arg);
187 }
188
189 static void NORETURN die_verify_filename(struct repository *r,
190 const char *prefix,
191 const char *arg,
192 int diagnose_misspelt_rev)
193 {
194 if (!diagnose_misspelt_rev)
195 die(_("%s: no such path in the working tree.\n"
196 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
197 arg);
198 /*
199 * Saying "'(icase)foo' does not exist in the index" when the
200 * user gave us ":(icase)foo" is just stupid. A magic pathspec
201 * begins with a colon and is followed by a non-alnum; do not
202 * let maybe_die_on_misspelt_object_name() even trigger.
203 */
204 if (!(arg[0] == ':' && !isalnum(arg[1])))
205 maybe_die_on_misspelt_object_name(r, arg, prefix);
206
207 /* ... or fall back the most general message. */
208 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
209 "Use '--' to separate paths from revisions, like this:\n"
210 "'git <command> [<revision>...] -- [<file>...]'"), arg);
211
212 }
213
214 /*
215 * Check for arguments that don't resolve as actual files,
216 * but which look sufficiently like pathspecs that we'll consider
217 * them such for the purposes of rev/pathspec DWIM parsing.
218 */
219 static int looks_like_pathspec(const char *arg)
220 {
221 const char *p;
222 int escaped = 0;
223
224 /*
225 * Wildcard characters imply the user is looking to match pathspecs
226 * that aren't in the filesystem. Note that this doesn't include
227 * backslash even though it's a glob special; by itself it doesn't
228 * cause any increase in the match. Likewise ignore backslash-escaped
229 * wildcard characters.
230 */
231 for (p = arg; *p; p++) {
232 if (escaped) {
233 escaped = 0;
234 } else if (is_glob_special(*p)) {
235 if (*p == '\\')
236 escaped = 1;
237 else
238 return 1;
239 }
240 }
241
242 /* long-form pathspec magic */
243 if (starts_with(arg, ":("))
244 return 1;
245
246 return 0;
247 }
248
249 /*
250 * Verify a filename that we got as an argument for a pathspec
251 * entry. Note that a filename that begins with "-" never verifies
252 * as true, because even if such a filename were to exist, we want
253 * it to be preceded by the "--" marker (or we want the user to
254 * use a format like "./-filename")
255 *
256 * The "diagnose_misspelt_rev" is used to provide a user-friendly
257 * diagnosis when dying upon finding that "name" is not a pathname.
258 * If set to 1, the diagnosis will try to diagnose "name" as an
259 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
260 * will only complain about an inexisting file.
261 *
262 * This function is typically called to check that a "file or rev"
263 * argument is unambiguous. In this case, the caller will want
264 * diagnose_misspelt_rev == 1 when verifying the first non-rev
265 * argument (which could have been a revision), and
266 * diagnose_misspelt_rev == 0 for the next ones (because we already
267 * saw a filename, there's not ambiguity anymore).
268 */
269 void verify_filename(const char *prefix,
270 const char *arg,
271 int diagnose_misspelt_rev)
272 {
273 if (*arg == '-')
274 die(_("option '%s' must come before non-option arguments"), arg);
275 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
276 return;
277 die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
278 }
279
280 /*
281 * Opposite of the above: the command line did not have -- marker
282 * and we parsed the arg as a refname. It should not be interpretable
283 * as a filename.
284 */
285 void verify_non_filename(const char *prefix, const char *arg)
286 {
287 if (!is_inside_work_tree() || is_inside_git_dir())
288 return;
289 if (*arg == '-')
290 return; /* flag */
291 if (!check_filename(prefix, arg))
292 return;
293 die(_("ambiguous argument '%s': both revision and filename\n"
294 "Use '--' to separate paths from revisions, like this:\n"
295 "'git <command> [<revision>...] -- [<file>...]'"), arg);
296 }
297
298 int get_common_dir(struct strbuf *sb, const char *gitdir)
299 {
300 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
301 if (git_env_common_dir) {
302 strbuf_addstr(sb, git_env_common_dir);
303 return 1;
304 } else {
305 return get_common_dir_noenv(sb, gitdir);
306 }
307 }
308
309 int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
310 {
311 struct strbuf data = STRBUF_INIT;
312 struct strbuf path = STRBUF_INIT;
313 int ret = 0;
314
315 strbuf_addf(&path, "%s/commondir", gitdir);
316 if (file_exists(path.buf)) {
317 if (strbuf_read_file(&data, path.buf, 0) <= 0)
318 die_errno(_("failed to read %s"), path.buf);
319 while (data.len && (data.buf[data.len - 1] == '\n' ||
320 data.buf[data.len - 1] == '\r'))
321 data.len--;
322 data.buf[data.len] = '\0';
323 strbuf_reset(&path);
324 if (!is_absolute_path(data.buf))
325 strbuf_addf(&path, "%s/", gitdir);
326 strbuf_addbuf(&path, &data);
327 strbuf_add_real_path(sb, path.buf);
328 ret = 1;
329 } else {
330 strbuf_addstr(sb, gitdir);
331 }
332
333 strbuf_release(&data);
334 strbuf_release(&path);
335 return ret;
336 }
337
338 /*
339 * Test if it looks like we're at a git directory.
340 * We want to see:
341 *
342 * - either an objects/ directory _or_ the proper
343 * GIT_OBJECT_DIRECTORY environment variable
344 * - a refs/ directory
345 * - either a HEAD symlink or a HEAD file that is formatted as
346 * a proper "ref:", or a regular file HEAD that has a properly
347 * formatted sha1 object name.
348 */
349 int is_git_directory(const char *suspect)
350 {
351 struct strbuf path = STRBUF_INIT;
352 int ret = 0;
353 size_t len;
354
355 /* Check worktree-related signatures */
356 strbuf_addstr(&path, suspect);
357 strbuf_complete(&path, '/');
358 strbuf_addstr(&path, "HEAD");
359 if (validate_headref(path.buf))
360 goto done;
361
362 strbuf_reset(&path);
363 get_common_dir(&path, suspect);
364 len = path.len;
365
366 /* Check non-worktree-related signatures */
367 if (getenv(DB_ENVIRONMENT)) {
368 if (access(getenv(DB_ENVIRONMENT), X_OK))
369 goto done;
370 }
371 else {
372 strbuf_setlen(&path, len);
373 strbuf_addstr(&path, "/objects");
374 if (access(path.buf, X_OK))
375 goto done;
376 }
377
378 strbuf_setlen(&path, len);
379 strbuf_addstr(&path, "/refs");
380 if (access(path.buf, X_OK))
381 goto done;
382
383 ret = 1;
384 done:
385 strbuf_release(&path);
386 return ret;
387 }
388
389 int is_nonbare_repository_dir(struct strbuf *path)
390 {
391 int ret = 0;
392 int gitfile_error;
393 size_t orig_path_len = path->len;
394 assert(orig_path_len != 0);
395 strbuf_complete(path, '/');
396 strbuf_addstr(path, ".git");
397 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
398 ret = 1;
399 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
400 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
401 ret = 1;
402 strbuf_setlen(path, orig_path_len);
403 return ret;
404 }
405
406 int is_inside_git_dir(void)
407 {
408 if (inside_git_dir < 0)
409 inside_git_dir = is_inside_dir(get_git_dir());
410 return inside_git_dir;
411 }
412
413 int is_inside_work_tree(void)
414 {
415 if (inside_work_tree < 0)
416 inside_work_tree = is_inside_dir(get_git_work_tree());
417 return inside_work_tree;
418 }
419
420 void setup_work_tree(void)
421 {
422 const char *work_tree;
423 static int initialized = 0;
424
425 if (initialized)
426 return;
427
428 if (work_tree_config_is_bogus)
429 die(_("unable to set up work tree using invalid config"));
430
431 work_tree = get_git_work_tree();
432 if (!work_tree || chdir_notify(work_tree))
433 die(_("this operation must be run in a work tree"));
434
435 /*
436 * Make sure subsequent git processes find correct worktree
437 * if $GIT_WORK_TREE is set relative
438 */
439 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
440 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
441
442 initialized = 1;
443 }
444
445 static void setup_original_cwd(void)
446 {
447 struct strbuf tmp = STRBUF_INIT;
448 const char *worktree = NULL;
449 int offset = -1;
450
451 if (!tmp_original_cwd)
452 return;
453
454 /*
455 * startup_info->original_cwd points to the current working
456 * directory we inherited from our parent process, which is a
457 * directory we want to avoid removing.
458 *
459 * For convience, we would like to have the path relative to the
460 * worktree instead of an absolute path.
461 *
462 * Yes, startup_info->original_cwd is usually the same as 'prefix',
463 * but differs in two ways:
464 * - prefix has a trailing '/'
465 * - if the user passes '-C' to git, that modifies the prefix but
466 * not startup_info->original_cwd.
467 */
468
469 /* Normalize the directory */
470 if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) {
471 trace2_data_string("setup", the_repository,
472 "realpath-path", tmp_original_cwd);
473 trace2_data_string("setup", the_repository,
474 "realpath-failure", strerror(errno));
475 free((char*)tmp_original_cwd);
476 tmp_original_cwd = NULL;
477 return;
478 }
479
480 free((char*)tmp_original_cwd);
481 tmp_original_cwd = NULL;
482 startup_info->original_cwd = strbuf_detach(&tmp, NULL);
483
484 /*
485 * Get our worktree; we only protect the current working directory
486 * if it's in the worktree.
487 */
488 worktree = get_git_work_tree();
489 if (!worktree)
490 goto no_prevention_needed;
491
492 offset = dir_inside_of(startup_info->original_cwd, worktree);
493 if (offset >= 0) {
494 /*
495 * If startup_info->original_cwd == worktree, that is already
496 * protected and we don't need original_cwd as a secondary
497 * protection measure.
498 */
499 if (!*(startup_info->original_cwd + offset))
500 goto no_prevention_needed;
501
502 /*
503 * original_cwd was inside worktree; precompose it just as
504 * we do prefix so that built up paths will match
505 */
506 startup_info->original_cwd = \
507 precompose_string_if_needed(startup_info->original_cwd
508 + offset);
509 return;
510 }
511
512 no_prevention_needed:
513 free((char*)startup_info->original_cwd);
514 startup_info->original_cwd = NULL;
515 }
516
517 static int read_worktree_config(const char *var, const char *value, void *vdata)
518 {
519 struct repository_format *data = vdata;
520
521 if (strcmp(var, "core.bare") == 0) {
522 data->is_bare = git_config_bool(var, value);
523 } else if (strcmp(var, "core.worktree") == 0) {
524 if (!value)
525 return config_error_nonbool(var);
526 free(data->work_tree);
527 data->work_tree = xstrdup(value);
528 }
529 return 0;
530 }
531
532 enum extension_result {
533 EXTENSION_ERROR = -1, /* compatible with error(), etc */
534 EXTENSION_UNKNOWN = 0,
535 EXTENSION_OK = 1
536 };
537
538 /*
539 * Do not add new extensions to this function. It handles extensions which are
540 * respected even in v0-format repositories for historical compatibility.
541 */
542 static enum extension_result handle_extension_v0(const char *var,
543 const char *value,
544 const char *ext,
545 struct repository_format *data)
546 {
547 if (!strcmp(ext, "noop")) {
548 return EXTENSION_OK;
549 } else if (!strcmp(ext, "preciousobjects")) {
550 data->precious_objects = git_config_bool(var, value);
551 return EXTENSION_OK;
552 } else if (!strcmp(ext, "partialclone")) {
553 data->partial_clone = xstrdup(value);
554 return EXTENSION_OK;
555 } else if (!strcmp(ext, "worktreeconfig")) {
556 data->worktree_config = git_config_bool(var, value);
557 return EXTENSION_OK;
558 }
559
560 return EXTENSION_UNKNOWN;
561 }
562
563 /*
564 * Record any new extensions in this function.
565 */
566 static enum extension_result handle_extension(const char *var,
567 const char *value,
568 const char *ext,
569 struct repository_format *data)
570 {
571 if (!strcmp(ext, "noop-v1")) {
572 return EXTENSION_OK;
573 } else if (!strcmp(ext, "objectformat")) {
574 int format;
575
576 if (!value)
577 return config_error_nonbool(var);
578 format = hash_algo_by_name(value);
579 if (format == GIT_HASH_UNKNOWN)
580 return error(_("invalid value for '%s': '%s'"),
581 "extensions.objectformat", value);
582 data->hash_algo = format;
583 return EXTENSION_OK;
584 }
585 return EXTENSION_UNKNOWN;
586 }
587
588 static int check_repo_format(const char *var, const char *value, void *vdata)
589 {
590 struct repository_format *data = vdata;
591 const char *ext;
592
593 if (strcmp(var, "core.repositoryformatversion") == 0)
594 data->version = git_config_int(var, value);
595 else if (skip_prefix(var, "extensions.", &ext)) {
596 switch (handle_extension_v0(var, value, ext, data)) {
597 case EXTENSION_ERROR:
598 return -1;
599 case EXTENSION_OK:
600 return 0;
601 case EXTENSION_UNKNOWN:
602 break;
603 }
604
605 switch (handle_extension(var, value, ext, data)) {
606 case EXTENSION_ERROR:
607 return -1;
608 case EXTENSION_OK:
609 string_list_append(&data->v1_only_extensions, ext);
610 return 0;
611 case EXTENSION_UNKNOWN:
612 string_list_append(&data->unknown_extensions, ext);
613 return 0;
614 }
615 }
616
617 return read_worktree_config(var, value, vdata);
618 }
619
620 static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
621 {
622 struct strbuf sb = STRBUF_INIT;
623 struct strbuf err = STRBUF_INIT;
624 int has_common;
625
626 has_common = get_common_dir(&sb, gitdir);
627 strbuf_addstr(&sb, "/config");
628 read_repository_format(candidate, sb.buf);
629 strbuf_release(&sb);
630
631 /*
632 * For historical use of check_repository_format() in git-init,
633 * we treat a missing config as a silent "ok", even when nongit_ok
634 * is unset.
635 */
636 if (candidate->version < 0)
637 return 0;
638
639 if (verify_repository_format(candidate, &err) < 0) {
640 if (nongit_ok) {
641 warning("%s", err.buf);
642 strbuf_release(&err);
643 *nongit_ok = -1;
644 return -1;
645 }
646 die("%s", err.buf);
647 }
648
649 repository_format_precious_objects = candidate->precious_objects;
650 repository_format_worktree_config = candidate->worktree_config;
651 string_list_clear(&candidate->unknown_extensions, 0);
652 string_list_clear(&candidate->v1_only_extensions, 0);
653
654 if (repository_format_worktree_config) {
655 /*
656 * pick up core.bare and core.worktree from per-worktree
657 * config if present
658 */
659 strbuf_addf(&sb, "%s/config.worktree", gitdir);
660 git_config_from_file(read_worktree_config, sb.buf, candidate);
661 strbuf_release(&sb);
662 has_common = 0;
663 }
664
665 if (!has_common) {
666 if (candidate->is_bare != -1) {
667 is_bare_repository_cfg = candidate->is_bare;
668 if (is_bare_repository_cfg == 1)
669 inside_work_tree = -1;
670 }
671 if (candidate->work_tree) {
672 free(git_work_tree_cfg);
673 git_work_tree_cfg = xstrdup(candidate->work_tree);
674 inside_work_tree = -1;
675 }
676 }
677
678 return 0;
679 }
680
681 int upgrade_repository_format(int target_version)
682 {
683 struct strbuf sb = STRBUF_INIT;
684 struct strbuf err = STRBUF_INIT;
685 struct strbuf repo_version = STRBUF_INIT;
686 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
687
688 strbuf_git_common_path(&sb, the_repository, "config");
689 read_repository_format(&repo_fmt, sb.buf);
690 strbuf_release(&sb);
691
692 if (repo_fmt.version >= target_version)
693 return 0;
694
695 if (verify_repository_format(&repo_fmt, &err) < 0) {
696 error("cannot upgrade repository format from %d to %d: %s",
697 repo_fmt.version, target_version, err.buf);
698 strbuf_release(&err);
699 return -1;
700 }
701 if (!repo_fmt.version && repo_fmt.unknown_extensions.nr)
702 return error("cannot upgrade repository format: "
703 "unknown extension %s",
704 repo_fmt.unknown_extensions.items[0].string);
705
706 strbuf_addf(&repo_version, "%d", target_version);
707 git_config_set("core.repositoryformatversion", repo_version.buf);
708 strbuf_release(&repo_version);
709 return 1;
710 }
711
712 static void init_repository_format(struct repository_format *format)
713 {
714 const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
715
716 memcpy(format, &fresh, sizeof(fresh));
717 }
718
719 int read_repository_format(struct repository_format *format, const char *path)
720 {
721 clear_repository_format(format);
722 git_config_from_file(check_repo_format, path, format);
723 if (format->version == -1)
724 clear_repository_format(format);
725 return format->version;
726 }
727
728 void clear_repository_format(struct repository_format *format)
729 {
730 string_list_clear(&format->unknown_extensions, 0);
731 string_list_clear(&format->v1_only_extensions, 0);
732 free(format->work_tree);
733 free(format->partial_clone);
734 init_repository_format(format);
735 }
736
737 int verify_repository_format(const struct repository_format *format,
738 struct strbuf *err)
739 {
740 if (GIT_REPO_VERSION_READ < format->version) {
741 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
742 GIT_REPO_VERSION_READ, format->version);
743 return -1;
744 }
745
746 if (format->version >= 1 && format->unknown_extensions.nr) {
747 int i;
748
749 strbuf_addstr(err, Q_("unknown repository extension found:",
750 "unknown repository extensions found:",
751 format->unknown_extensions.nr));
752
753 for (i = 0; i < format->unknown_extensions.nr; i++)
754 strbuf_addf(err, "\n\t%s",
755 format->unknown_extensions.items[i].string);
756 return -1;
757 }
758
759 if (format->version == 0 && format->v1_only_extensions.nr) {
760 int i;
761
762 strbuf_addstr(err,
763 Q_("repo version is 0, but v1-only extension found:",
764 "repo version is 0, but v1-only extensions found:",
765 format->v1_only_extensions.nr));
766
767 for (i = 0; i < format->v1_only_extensions.nr; i++)
768 strbuf_addf(err, "\n\t%s",
769 format->v1_only_extensions.items[i].string);
770 return -1;
771 }
772
773 return 0;
774 }
775
776 void read_gitfile_error_die(int error_code, const char *path, const char *dir)
777 {
778 switch (error_code) {
779 case READ_GITFILE_ERR_STAT_FAILED:
780 case READ_GITFILE_ERR_NOT_A_FILE:
781 /* non-fatal; follow return path */
782 break;
783 case READ_GITFILE_ERR_OPEN_FAILED:
784 die_errno(_("error opening '%s'"), path);
785 case READ_GITFILE_ERR_TOO_LARGE:
786 die(_("too large to be a .git file: '%s'"), path);
787 case READ_GITFILE_ERR_READ_FAILED:
788 die(_("error reading %s"), path);
789 case READ_GITFILE_ERR_INVALID_FORMAT:
790 die(_("invalid gitfile format: %s"), path);
791 case READ_GITFILE_ERR_NO_PATH:
792 die(_("no path in gitfile: %s"), path);
793 case READ_GITFILE_ERR_NOT_A_REPO:
794 die(_("not a git repository: %s"), dir);
795 default:
796 BUG("unknown error code");
797 }
798 }
799
800 /*
801 * Try to read the location of the git directory from the .git file,
802 * return path to git directory if found. The return value comes from
803 * a shared buffer.
804 *
805 * On failure, if return_error_code is not NULL, return_error_code
806 * will be set to an error code and NULL will be returned. If
807 * return_error_code is NULL the function will die instead (for most
808 * cases).
809 */
810 const char *read_gitfile_gently(const char *path, int *return_error_code)
811 {
812 const int max_file_size = 1 << 20; /* 1MB */
813 int error_code = 0;
814 char *buf = NULL;
815 char *dir = NULL;
816 const char *slash;
817 struct stat st;
818 int fd;
819 ssize_t len;
820 static struct strbuf realpath = STRBUF_INIT;
821
822 if (stat(path, &st)) {
823 /* NEEDSWORK: discern between ENOENT vs other errors */
824 error_code = READ_GITFILE_ERR_STAT_FAILED;
825 goto cleanup_return;
826 }
827 if (!S_ISREG(st.st_mode)) {
828 error_code = READ_GITFILE_ERR_NOT_A_FILE;
829 goto cleanup_return;
830 }
831 if (st.st_size > max_file_size) {
832 error_code = READ_GITFILE_ERR_TOO_LARGE;
833 goto cleanup_return;
834 }
835 fd = open(path, O_RDONLY);
836 if (fd < 0) {
837 error_code = READ_GITFILE_ERR_OPEN_FAILED;
838 goto cleanup_return;
839 }
840 buf = xmallocz(st.st_size);
841 len = read_in_full(fd, buf, st.st_size);
842 close(fd);
843 if (len != st.st_size) {
844 error_code = READ_GITFILE_ERR_READ_FAILED;
845 goto cleanup_return;
846 }
847 if (!starts_with(buf, "gitdir: ")) {
848 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
849 goto cleanup_return;
850 }
851 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
852 len--;
853 if (len < 9) {
854 error_code = READ_GITFILE_ERR_NO_PATH;
855 goto cleanup_return;
856 }
857 buf[len] = '\0';
858 dir = buf + 8;
859
860 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
861 size_t pathlen = slash+1 - path;
862 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
863 (int)(len - 8), buf + 8);
864 free(buf);
865 buf = dir;
866 }
867 if (!is_git_directory(dir)) {
868 error_code = READ_GITFILE_ERR_NOT_A_REPO;
869 goto cleanup_return;
870 }
871
872 strbuf_realpath(&realpath, dir, 1);
873 path = realpath.buf;
874
875 cleanup_return:
876 if (return_error_code)
877 *return_error_code = error_code;
878 else if (error_code)
879 read_gitfile_error_die(error_code, path, dir);
880
881 free(buf);
882 return error_code ? NULL : path;
883 }
884
885 static const char *setup_explicit_git_dir(const char *gitdirenv,
886 struct strbuf *cwd,
887 struct repository_format *repo_fmt,
888 int *nongit_ok)
889 {
890 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
891 const char *worktree;
892 char *gitfile;
893 int offset;
894
895 if (PATH_MAX - 40 < strlen(gitdirenv))
896 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
897
898 gitfile = (char*)read_gitfile(gitdirenv);
899 if (gitfile) {
900 gitfile = xstrdup(gitfile);
901 gitdirenv = gitfile;
902 }
903
904 if (!is_git_directory(gitdirenv)) {
905 if (nongit_ok) {
906 *nongit_ok = 1;
907 free(gitfile);
908 return NULL;
909 }
910 die(_("not a git repository: '%s'"), gitdirenv);
911 }
912
913 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
914 free(gitfile);
915 return NULL;
916 }
917
918 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
919 if (work_tree_env)
920 set_git_work_tree(work_tree_env);
921 else if (is_bare_repository_cfg > 0) {
922 if (git_work_tree_cfg) {
923 /* #22.2, #30 */
924 warning("core.bare and core.worktree do not make sense");
925 work_tree_config_is_bogus = 1;
926 }
927
928 /* #18, #26 */
929 set_git_dir(gitdirenv, 0);
930 free(gitfile);
931 return NULL;
932 }
933 else if (git_work_tree_cfg) { /* #6, #14 */
934 if (is_absolute_path(git_work_tree_cfg))
935 set_git_work_tree(git_work_tree_cfg);
936 else {
937 char *core_worktree;
938 if (chdir(gitdirenv))
939 die_errno(_("cannot chdir to '%s'"), gitdirenv);
940 if (chdir(git_work_tree_cfg))
941 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
942 core_worktree = xgetcwd();
943 if (chdir(cwd->buf))
944 die_errno(_("cannot come back to cwd"));
945 set_git_work_tree(core_worktree);
946 free(core_worktree);
947 }
948 }
949 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
950 /* #16d */
951 set_git_dir(gitdirenv, 0);
952 free(gitfile);
953 return NULL;
954 }
955 else /* #2, #10 */
956 set_git_work_tree(".");
957
958 /* set_git_work_tree() must have been called by now */
959 worktree = get_git_work_tree();
960
961 /* both get_git_work_tree() and cwd are already normalized */
962 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
963 set_git_dir(gitdirenv, 0);
964 free(gitfile);
965 return NULL;
966 }
967
968 offset = dir_inside_of(cwd->buf, worktree);
969 if (offset >= 0) { /* cwd inside worktree? */
970 set_git_dir(gitdirenv, 1);
971 if (chdir(worktree))
972 die_errno(_("cannot chdir to '%s'"), worktree);
973 strbuf_addch(cwd, '/');
974 free(gitfile);
975 return cwd->buf + offset;
976 }
977
978 /* cwd outside worktree */
979 set_git_dir(gitdirenv, 0);
980 free(gitfile);
981 return NULL;
982 }
983
984 static const char *setup_discovered_git_dir(const char *gitdir,
985 struct strbuf *cwd, int offset,
986 struct repository_format *repo_fmt,
987 int *nongit_ok)
988 {
989 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
990 return NULL;
991
992 /* --work-tree is set without --git-dir; use discovered one */
993 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
994 char *to_free = NULL;
995 const char *ret;
996
997 if (offset != cwd->len && !is_absolute_path(gitdir))
998 gitdir = to_free = real_pathdup(gitdir, 1);
999 if (chdir(cwd->buf))
1000 die_errno(_("cannot come back to cwd"));
1001 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1002 free(to_free);
1003 return ret;
1004 }
1005
1006 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1007 if (is_bare_repository_cfg > 0) {
1008 set_git_dir(gitdir, (offset != cwd->len));
1009 if (chdir(cwd->buf))
1010 die_errno(_("cannot come back to cwd"));
1011 return NULL;
1012 }
1013
1014 /* #0, #1, #5, #8, #9, #12, #13 */
1015 set_git_work_tree(".");
1016 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
1017 set_git_dir(gitdir, 0);
1018 inside_git_dir = 0;
1019 inside_work_tree = 1;
1020 if (offset >= cwd->len)
1021 return NULL;
1022
1023 /* Make "offset" point past the '/' (already the case for root dirs) */
1024 if (offset != offset_1st_component(cwd->buf))
1025 offset++;
1026 /* Add a '/' at the end */
1027 strbuf_addch(cwd, '/');
1028 return cwd->buf + offset;
1029 }
1030
1031 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1032 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
1033 struct repository_format *repo_fmt,
1034 int *nongit_ok)
1035 {
1036 int root_len;
1037
1038 if (check_repository_format_gently(".", repo_fmt, nongit_ok))
1039 return NULL;
1040
1041 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
1042
1043 /* --work-tree is set without --git-dir; use discovered one */
1044 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1045 static const char *gitdir;
1046
1047 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
1048 if (chdir(cwd->buf))
1049 die_errno(_("cannot come back to cwd"));
1050 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1051 }
1052
1053 inside_git_dir = 1;
1054 inside_work_tree = 0;
1055 if (offset != cwd->len) {
1056 if (chdir(cwd->buf))
1057 die_errno(_("cannot come back to cwd"));
1058 root_len = offset_1st_component(cwd->buf);
1059 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
1060 set_git_dir(cwd->buf, 0);
1061 }
1062 else
1063 set_git_dir(".", 0);
1064 return NULL;
1065 }
1066
1067 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
1068 {
1069 struct stat buf;
1070 if (stat(path, &buf)) {
1071 die_errno(_("failed to stat '%*s%s%s'"),
1072 prefix_len,
1073 prefix ? prefix : "",
1074 prefix ? "/" : "", path);
1075 }
1076 return buf.st_dev;
1077 }
1078
1079 /*
1080 * A "string_list_each_func_t" function that canonicalizes an entry
1081 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1082 * discards it if unusable. The presence of an empty entry in
1083 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1084 * subsequent entries.
1085 */
1086 static int canonicalize_ceiling_entry(struct string_list_item *item,
1087 void *cb_data)
1088 {
1089 int *empty_entry_found = cb_data;
1090 char *ceil = item->string;
1091
1092 if (!*ceil) {
1093 *empty_entry_found = 1;
1094 return 0;
1095 } else if (!is_absolute_path(ceil)) {
1096 return 0;
1097 } else if (*empty_entry_found) {
1098 /* Keep entry but do not canonicalize it */
1099 return 1;
1100 } else {
1101 char *real_path = real_pathdup(ceil, 0);
1102 if (!real_path) {
1103 return 0;
1104 }
1105 free(item->string);
1106 item->string = real_path;
1107 return 1;
1108 }
1109 }
1110
1111 struct safe_directory_data {
1112 const char *path;
1113 int is_safe;
1114 };
1115
1116 static int safe_directory_cb(const char *key, const char *value, void *d)
1117 {
1118 struct safe_directory_data *data = d;
1119
1120 if (strcmp(key, "safe.directory"))
1121 return 0;
1122
1123 if (!value || !*value) {
1124 data->is_safe = 0;
1125 } else if (!strcmp(value, "*")) {
1126 data->is_safe = 1;
1127 } else {
1128 const char *interpolated = NULL;
1129
1130 if (!git_config_pathname(&interpolated, key, value) &&
1131 !fspathcmp(data->path, interpolated ? interpolated : value))
1132 data->is_safe = 1;
1133
1134 free((char *)interpolated);
1135 }
1136
1137 return 0;
1138 }
1139
1140 /*
1141 * Check if a repository is safe, by verifying the ownership of the
1142 * worktree (if any), the git directory, and the gitfile (if any).
1143 *
1144 * Exemptions for known-safe repositories can be added via `safe.directory`
1145 * config settings; for non-bare repositories, their worktree needs to be
1146 * added, for bare ones their git directory.
1147 */
1148 static int ensure_valid_ownership(const char *gitfile,
1149 const char *worktree, const char *gitdir,
1150 struct strbuf *report)
1151 {
1152 struct safe_directory_data data = {
1153 .path = worktree ? worktree : gitdir
1154 };
1155
1156 if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1157 (!gitfile || is_path_owned_by_current_user(gitfile, report)) &&
1158 (!worktree || is_path_owned_by_current_user(worktree, report)) &&
1159 (!gitdir || is_path_owned_by_current_user(gitdir, report)))
1160 return 1;
1161
1162 /*
1163 * data.path is the "path" that identifies the repository and it is
1164 * constant regardless of what failed above. data.is_safe should be
1165 * initialized to false, and might be changed by the callback.
1166 */
1167 git_protected_config(safe_directory_cb, &data);
1168
1169 return data.is_safe;
1170 }
1171
1172 static int allowed_bare_repo_cb(const char *key, const char *value, void *d)
1173 {
1174 enum allowed_bare_repo *allowed_bare_repo = d;
1175
1176 if (strcasecmp(key, "safe.bareRepository"))
1177 return 0;
1178
1179 if (!strcmp(value, "explicit")) {
1180 *allowed_bare_repo = ALLOWED_BARE_REPO_EXPLICIT;
1181 return 0;
1182 }
1183 if (!strcmp(value, "all")) {
1184 *allowed_bare_repo = ALLOWED_BARE_REPO_ALL;
1185 return 0;
1186 }
1187 return -1;
1188 }
1189
1190 static enum allowed_bare_repo get_allowed_bare_repo(void)
1191 {
1192 enum allowed_bare_repo result = ALLOWED_BARE_REPO_ALL;
1193 git_protected_config(allowed_bare_repo_cb, &result);
1194 return result;
1195 }
1196
1197 static const char *allowed_bare_repo_to_string(
1198 enum allowed_bare_repo allowed_bare_repo)
1199 {
1200 switch (allowed_bare_repo) {
1201 case ALLOWED_BARE_REPO_EXPLICIT:
1202 return "explicit";
1203 case ALLOWED_BARE_REPO_ALL:
1204 return "all";
1205 default:
1206 BUG("invalid allowed_bare_repo %d",
1207 allowed_bare_repo);
1208 }
1209 return NULL;
1210 }
1211
1212 enum discovery_result {
1213 GIT_DIR_NONE = 0,
1214 GIT_DIR_EXPLICIT,
1215 GIT_DIR_DISCOVERED,
1216 GIT_DIR_BARE,
1217 /* these are errors */
1218 GIT_DIR_HIT_CEILING = -1,
1219 GIT_DIR_HIT_MOUNT_POINT = -2,
1220 GIT_DIR_INVALID_GITFILE = -3,
1221 GIT_DIR_INVALID_OWNERSHIP = -4,
1222 GIT_DIR_DISALLOWED_BARE = -5,
1223 };
1224
1225 /*
1226 * We cannot decide in this function whether we are in the work tree or
1227 * not, since the config can only be read _after_ this function was called.
1228 *
1229 * Also, we avoid changing any global state (such as the current working
1230 * directory) to allow early callers.
1231 *
1232 * The directory where the search should start needs to be passed in via the
1233 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1234 * the directory where the search ended, and `gitdir` will contain the path of
1235 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1236 * is relative to `dir` (i.e. *not* necessarily the cwd).
1237 */
1238 static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
1239 struct strbuf *gitdir,
1240 struct strbuf *report,
1241 int die_on_error)
1242 {
1243 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
1244 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
1245 const char *gitdirenv;
1246 int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
1247 dev_t current_device = 0;
1248 int one_filesystem = 1;
1249
1250 /*
1251 * If GIT_DIR is set explicitly, we're not going
1252 * to do any discovery, but we still do repository
1253 * validation.
1254 */
1255 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
1256 if (gitdirenv) {
1257 strbuf_addstr(gitdir, gitdirenv);
1258 return GIT_DIR_EXPLICIT;
1259 }
1260
1261 if (env_ceiling_dirs) {
1262 int empty_entry_found = 0;
1263
1264 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
1265 filter_string_list(&ceiling_dirs, 0,
1266 canonicalize_ceiling_entry, &empty_entry_found);
1267 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
1268 string_list_clear(&ceiling_dirs, 0);
1269 }
1270
1271 if (ceil_offset < 0)
1272 ceil_offset = min_offset - 2;
1273
1274 if (min_offset && min_offset == dir->len &&
1275 !is_dir_sep(dir->buf[min_offset - 1])) {
1276 strbuf_addch(dir, '/');
1277 min_offset++;
1278 }
1279
1280 /*
1281 * Test in the following order (relative to the dir):
1282 * - .git (file containing "gitdir: <path>")
1283 * - .git/
1284 * - ./ (bare)
1285 * - ../.git
1286 * - ../.git/
1287 * - ../ (bare)
1288 * - ../../.git
1289 * etc.
1290 */
1291 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1292 if (one_filesystem)
1293 current_device = get_device_or_die(dir->buf, NULL, 0);
1294 for (;;) {
1295 int offset = dir->len, error_code = 0;
1296 char *gitdir_path = NULL;
1297 char *gitfile = NULL;
1298
1299 if (offset > min_offset)
1300 strbuf_addch(dir, '/');
1301 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
1302 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
1303 NULL : &error_code);
1304 if (!gitdirenv) {
1305 if (die_on_error ||
1306 error_code == READ_GITFILE_ERR_NOT_A_FILE) {
1307 /* NEEDSWORK: fail if .git is not file nor dir */
1308 if (is_git_directory(dir->buf)) {
1309 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1310 gitdir_path = xstrdup(dir->buf);
1311 }
1312 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
1313 return GIT_DIR_INVALID_GITFILE;
1314 } else
1315 gitfile = xstrdup(dir->buf);
1316 /*
1317 * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1318 * to check that directory for a repository.
1319 * Now trim that tentative addition away, because we want to
1320 * focus on the real directory we are in.
1321 */
1322 strbuf_setlen(dir, offset);
1323 if (gitdirenv) {
1324 enum discovery_result ret;
1325 const char *gitdir_candidate =
1326 gitdir_path ? gitdir_path : gitdirenv;
1327
1328 if (ensure_valid_ownership(gitfile, dir->buf,
1329 gitdir_candidate, report)) {
1330 strbuf_addstr(gitdir, gitdirenv);
1331 ret = GIT_DIR_DISCOVERED;
1332 } else
1333 ret = GIT_DIR_INVALID_OWNERSHIP;
1334
1335 /*
1336 * Earlier, during discovery, we might have allocated
1337 * string copies for gitdir_path or gitfile so make
1338 * sure we don't leak by freeing them now, before
1339 * leaving the loop and function.
1340 *
1341 * Note: gitdirenv will be non-NULL whenever these are
1342 * allocated, therefore we need not take care of releasing
1343 * them outside of this conditional block.
1344 */
1345 free(gitdir_path);
1346 free(gitfile);
1347
1348 return ret;
1349 }
1350
1351 if (is_git_directory(dir->buf)) {
1352 if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT)
1353 return GIT_DIR_DISALLOWED_BARE;
1354 if (!ensure_valid_ownership(NULL, NULL, dir->buf, report))
1355 return GIT_DIR_INVALID_OWNERSHIP;
1356 strbuf_addstr(gitdir, ".");
1357 return GIT_DIR_BARE;
1358 }
1359
1360 if (offset <= min_offset)
1361 return GIT_DIR_HIT_CEILING;
1362
1363 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1364 ; /* continue */
1365 if (offset <= ceil_offset)
1366 return GIT_DIR_HIT_CEILING;
1367
1368 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
1369 if (one_filesystem &&
1370 current_device != get_device_or_die(dir->buf, NULL, offset))
1371 return GIT_DIR_HIT_MOUNT_POINT;
1372 }
1373 }
1374
1375 int discover_git_directory(struct strbuf *commondir,
1376 struct strbuf *gitdir)
1377 {
1378 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1379 size_t gitdir_offset = gitdir->len, cwd_len;
1380 size_t commondir_offset = commondir->len;
1381 struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1382
1383 if (strbuf_getcwd(&dir))
1384 return -1;
1385
1386 cwd_len = dir.len;
1387 if (setup_git_directory_gently_1(&dir, gitdir, NULL, 0) <= 0) {
1388 strbuf_release(&dir);
1389 return -1;
1390 }
1391
1392 /*
1393 * The returned gitdir is relative to dir, and if dir does not reflect
1394 * the current working directory, we simply make the gitdir absolute.
1395 */
1396 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1397 /* Avoid a trailing "/." */
1398 if (!strcmp(".", gitdir->buf + gitdir_offset))
1399 strbuf_setlen(gitdir, gitdir_offset);
1400 else
1401 strbuf_addch(&dir, '/');
1402 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1403 }
1404
1405 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1406
1407 strbuf_reset(&dir);
1408 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1409 read_repository_format(&candidate, dir.buf);
1410 strbuf_release(&dir);
1411
1412 if (verify_repository_format(&candidate, &err) < 0) {
1413 warning("ignoring git dir '%s': %s",
1414 gitdir->buf + gitdir_offset, err.buf);
1415 strbuf_release(&err);
1416 strbuf_setlen(commondir, commondir_offset);
1417 strbuf_setlen(gitdir, gitdir_offset);
1418 clear_repository_format(&candidate);
1419 return -1;
1420 }
1421
1422 /* take ownership of candidate.partial_clone */
1423 the_repository->repository_format_partial_clone =
1424 candidate.partial_clone;
1425 candidate.partial_clone = NULL;
1426
1427 clear_repository_format(&candidate);
1428 return 0;
1429 }
1430
1431 const char *setup_git_directory_gently(int *nongit_ok)
1432 {
1433 static struct strbuf cwd = STRBUF_INIT;
1434 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT;
1435 const char *prefix = NULL;
1436 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1437
1438 /*
1439 * We may have read an incomplete configuration before
1440 * setting-up the git directory. If so, clear the cache so
1441 * that the next queries to the configuration reload complete
1442 * configuration (including the per-repo config file that we
1443 * ignored previously).
1444 */
1445 git_config_clear();
1446
1447 /*
1448 * Let's assume that we are in a git repository.
1449 * If it turns out later that we are somewhere else, the value will be
1450 * updated accordingly.
1451 */
1452 if (nongit_ok)
1453 *nongit_ok = 0;
1454
1455 if (strbuf_getcwd(&cwd))
1456 die_errno(_("Unable to read current working directory"));
1457 strbuf_addbuf(&dir, &cwd);
1458
1459 switch (setup_git_directory_gently_1(&dir, &gitdir, &report, 1)) {
1460 case GIT_DIR_EXPLICIT:
1461 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1462 break;
1463 case GIT_DIR_DISCOVERED:
1464 if (dir.len < cwd.len && chdir(dir.buf))
1465 die(_("cannot change to '%s'"), dir.buf);
1466 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1467 &repo_fmt, nongit_ok);
1468 break;
1469 case GIT_DIR_BARE:
1470 if (dir.len < cwd.len && chdir(dir.buf))
1471 die(_("cannot change to '%s'"), dir.buf);
1472 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1473 break;
1474 case GIT_DIR_HIT_CEILING:
1475 if (!nongit_ok)
1476 die(_("not a git repository (or any of the parent directories): %s"),
1477 DEFAULT_GIT_DIR_ENVIRONMENT);
1478 *nongit_ok = 1;
1479 break;
1480 case GIT_DIR_HIT_MOUNT_POINT:
1481 if (!nongit_ok)
1482 die(_("not a git repository (or any parent up to mount point %s)\n"
1483 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1484 dir.buf);
1485 *nongit_ok = 1;
1486 break;
1487 case GIT_DIR_INVALID_OWNERSHIP:
1488 if (!nongit_ok) {
1489 struct strbuf quoted = STRBUF_INIT;
1490
1491 strbuf_complete(&report, '\n');
1492 sq_quote_buf_pretty(&quoted, dir.buf);
1493 die(_("detected dubious ownership in repository at '%s'\n"
1494 "%s"
1495 "To add an exception for this directory, call:\n"
1496 "\n"
1497 "\tgit config --global --add safe.directory %s"),
1498 dir.buf, report.buf, quoted.buf);
1499 }
1500 *nongit_ok = 1;
1501 break;
1502 case GIT_DIR_DISALLOWED_BARE:
1503 if (!nongit_ok) {
1504 die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
1505 dir.buf,
1506 allowed_bare_repo_to_string(get_allowed_bare_repo()));
1507 }
1508 *nongit_ok = 1;
1509 break;
1510 case GIT_DIR_NONE:
1511 /*
1512 * As a safeguard against setup_git_directory_gently_1 returning
1513 * this value, fallthrough to BUG. Otherwise it is possible to
1514 * set startup_info->have_repository to 1 when we did nothing to
1515 * find a repository.
1516 */
1517 default:
1518 BUG("unhandled setup_git_directory_gently_1() result");
1519 }
1520
1521 /*
1522 * At this point, nongit_ok is stable. If it is non-NULL and points
1523 * to a non-zero value, then this means that we haven't found a
1524 * repository and that the caller expects startup_info to reflect
1525 * this.
1526 *
1527 * Regardless of the state of nongit_ok, startup_info->prefix and
1528 * the GIT_PREFIX environment variable must always match. For details
1529 * see Documentation/config/alias.txt.
1530 */
1531 if (nongit_ok && *nongit_ok)
1532 startup_info->have_repository = 0;
1533 else
1534 startup_info->have_repository = 1;
1535
1536 /*
1537 * Not all paths through the setup code will call 'set_git_dir()' (which
1538 * directly sets up the environment) so in order to guarantee that the
1539 * environment is in a consistent state after setup, explicitly setup
1540 * the environment if we have a repository.
1541 *
1542 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1543 * code paths so we also need to explicitly setup the environment if
1544 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1545 * GIT_DIR values at some point in the future.
1546 */
1547 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1548 startup_info->have_repository ||
1549 /* GIT_DIR_EXPLICIT */
1550 getenv(GIT_DIR_ENVIRONMENT)) {
1551 if (!the_repository->gitdir) {
1552 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1553 if (!gitdir)
1554 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1555 setup_git_env(gitdir);
1556 }
1557 if (startup_info->have_repository) {
1558 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1559 /* take ownership of repo_fmt.partial_clone */
1560 the_repository->repository_format_partial_clone =
1561 repo_fmt.partial_clone;
1562 repo_fmt.partial_clone = NULL;
1563 }
1564 }
1565 /*
1566 * Since precompose_string_if_needed() needs to look at
1567 * the core.precomposeunicode configuration, this
1568 * has to happen after the above block that finds
1569 * out where the repository is, i.e. a preparation
1570 * for calling git_config_get_bool().
1571 */
1572 if (prefix) {
1573 prefix = precompose_string_if_needed(prefix);
1574 startup_info->prefix = prefix;
1575 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1576 } else {
1577 startup_info->prefix = NULL;
1578 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1579 }
1580
1581 setup_original_cwd();
1582
1583 strbuf_release(&dir);
1584 strbuf_release(&gitdir);
1585 strbuf_release(&report);
1586 clear_repository_format(&repo_fmt);
1587
1588 return prefix;
1589 }
1590
1591 int git_config_perm(const char *var, const char *value)
1592 {
1593 int i;
1594 char *endptr;
1595
1596 if (!value)
1597 return PERM_GROUP;
1598
1599 if (!strcmp(value, "umask"))
1600 return PERM_UMASK;
1601 if (!strcmp(value, "group"))
1602 return PERM_GROUP;
1603 if (!strcmp(value, "all") ||
1604 !strcmp(value, "world") ||
1605 !strcmp(value, "everybody"))
1606 return PERM_EVERYBODY;
1607
1608 /* Parse octal numbers */
1609 i = strtol(value, &endptr, 8);
1610
1611 /* If not an octal number, maybe true/false? */
1612 if (*endptr != 0)
1613 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1614
1615 /*
1616 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1617 * a chmod value to restrict to.
1618 */
1619 switch (i) {
1620 case PERM_UMASK: /* 0 */
1621 return PERM_UMASK;
1622 case OLD_PERM_GROUP: /* 1 */
1623 return PERM_GROUP;
1624 case OLD_PERM_EVERYBODY: /* 2 */
1625 return PERM_EVERYBODY;
1626 }
1627
1628 /* A filemode value was given: 0xxx */
1629
1630 if ((i & 0600) != 0600)
1631 die(_("problem with core.sharedRepository filemode value "
1632 "(0%.3o).\nThe owner of files must always have "
1633 "read and write permissions."), i);
1634
1635 /*
1636 * Mask filemode value. Others can not get write permission.
1637 * x flags for directories are handled separately.
1638 */
1639 return -(i & 0666);
1640 }
1641
1642 void check_repository_format(struct repository_format *fmt)
1643 {
1644 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1645 if (!fmt)
1646 fmt = &repo_fmt;
1647 check_repository_format_gently(get_git_dir(), fmt, NULL);
1648 startup_info->have_repository = 1;
1649 repo_set_hash_algo(the_repository, fmt->hash_algo);
1650 the_repository->repository_format_partial_clone =
1651 xstrdup_or_null(fmt->partial_clone);
1652 clear_repository_format(&repo_fmt);
1653 }
1654
1655 /*
1656 * Returns the "prefix", a path to the current working directory
1657 * relative to the work tree root, or NULL, if the current working
1658 * directory is not a strict subdirectory of the work tree root. The
1659 * prefix always ends with a '/' character.
1660 */
1661 const char *setup_git_directory(void)
1662 {
1663 return setup_git_directory_gently(NULL);
1664 }
1665
1666 const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1667 {
1668 if (is_git_directory(suspect))
1669 return suspect;
1670 return read_gitfile_gently(suspect, return_error_code);
1671 }
1672
1673 /* if any standard file descriptor is missing open it to /dev/null */
1674 void sanitize_stdfds(void)
1675 {
1676 int fd = xopen("/dev/null", O_RDWR);
1677 while (fd < 2)
1678 fd = xdup(fd);
1679 if (fd > 2)
1680 close(fd);
1681 }
1682
1683 int daemonize(void)
1684 {
1685 #ifdef NO_POSIX_GOODIES
1686 errno = ENOSYS;
1687 return -1;
1688 #else
1689 switch (fork()) {
1690 case 0:
1691 break;
1692 case -1:
1693 die_errno(_("fork failed"));
1694 default:
1695 exit(0);
1696 }
1697 if (setsid() == -1)
1698 die_errno(_("setsid failed"));
1699 close(0);
1700 close(1);
1701 close(2);
1702 sanitize_stdfds();
1703 return 0;
1704 #endif
1705 }