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