interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / setup.c

3127 lines · 91095 bytes Raw Blame History
1#define DISABLE_SIGN_COMPARE_WARNINGS
2
3#include "git-compat-util.h"
4#include "abspath.h"
5#include "copy.h"
6#include "environment.h"
7#include "exec-cmd.h"
8#include "gettext.h"
9#include "hex.h"
10#include "object-file.h"
11#include "object-name.h"
12#include "refs.h"
13#include "repository.h"
14#include "config.h"
15#include "dir.h"
16#include "setup.h"
17#include "shallow.h"
18#include "string-list.h"
19#include "strvec.h"
20#include "chdir-notify.h"
21#include "path.h"
22#include "quote.h"
23#include "trace.h"
24#include "trace2.h"
25#include "worktree.h"
26
27enum allowed_bare_repo {
28 ALLOWED_BARE_REPO_EXPLICIT = 0,
29 ALLOWED_BARE_REPO_ALL,
30};
31
32static struct startup_info the_startup_info;
33struct startup_info *startup_info = &the_startup_info;
34const char *tmp_original_cwd;
35
36/*
37 * The input parameter must contain an absolute path, and it must already be
38 * normalized.
39 *
40 * Find the part of an absolute path that lies inside the work tree by
41 * dereferencing symlinks outside the work tree, for example:
42 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
43 * /dir/file (work tree is /) -> dir/file
44 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
45 * /dir/repolink/file (repolink points to /dir/repo) -> file
46 * /dir/repo (exactly equal to work tree) -> (empty string)
47 */
48static int abspath_part_inside_repo(struct repository *repo, char *path)
49{
50 size_t len;
51 size_t wtlen;
52 char *path0;
53 int off;
54 const char *work_tree = precompose_string_if_needed(repo_get_work_tree(repo));
55 struct strbuf realpath = STRBUF_INIT;
56
57 if (!work_tree)
58 return -1;
59 wtlen = strlen(work_tree);
60 len = strlen(path);
61 off = offset_1st_component(path);
62
63 /* check if work tree is already the prefix */
64 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
65 if (path[wtlen] == '/') {
66 memmove(path, path + wtlen + 1, len - wtlen);
67 return 0;
68 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
69 /* work tree is the root, or the whole path */
70 memmove(path, path + wtlen, len - wtlen + 1);
71 return 0;
72 }
73 /* work tree might match beginning of a symlink to work tree */
74 off = wtlen;
75 }
76 path0 = path;
77 path += off;
78
79 /* check each '/'-terminated level */
80 while (*path) {
81 path++;
82 if (*path == '/') {
83 *path = '\0';
84 strbuf_realpath(&realpath, path0, 1);
85 if (fspathcmp(realpath.buf, work_tree) == 0) {
86 memmove(path0, path + 1, len - (path - path0));
87 strbuf_release(&realpath);
88 return 0;
89 }
90 *path = '/';
91 }
92 }
93
94 /* check whole path */
95 strbuf_realpath(&realpath, path0, 1);
96 if (fspathcmp(realpath.buf, work_tree) == 0) {
97 *path0 = '\0';
98 strbuf_release(&realpath);
99 return 0;
100 }
101
102 strbuf_release(&realpath);
103 return -1;
104}
105
106/*
107 * Normalize "path", prepending the "prefix" for relative paths. If
108 * remaining_prefix is not NULL, return the actual prefix still
109 * remains in the path. For example, prefix = sub1/sub2/ and path is
110 *
111 * foo -> sub1/sub2/foo (full prefix)
112 * ../foo -> sub1/foo (remaining prefix is sub1/)
113 * ../../bar -> bar (no remaining prefix)
114 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
115 * `pwd`/../bar -> sub1/bar (no remaining prefix)
116 */
117char *prefix_path_gently(struct repository *repo,
118 const char *prefix, int len,
119 int *remaining_prefix, const char *path)
120{
121 const char *orig = path;
122 char *sanitized;
123 if (is_absolute_path(orig)) {
124 sanitized = xmallocz(strlen(path));
125 if (remaining_prefix)
126 *remaining_prefix = 0;
127 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
128 free(sanitized);
129 return NULL;
130 }
131 if (abspath_part_inside_repo(repo, sanitized)) {
132 free(sanitized);
133 return NULL;
134 }
135 } else {
136 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
137 if (remaining_prefix)
138 *remaining_prefix = len;
139 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
140 free(sanitized);
141 return NULL;
142 }
143 }
144 return sanitized;
145}
146
147char *prefix_path(struct repository *repo, const char *prefix, int len, const char *path)
148{
149 char *r = prefix_path_gently(repo, prefix, len, NULL, path);
150 if (!r) {
151 const char *hint_path = repo_get_work_tree(repo);
152 if (!hint_path)
153 hint_path = repo_get_git_dir(repo);
154 die(_("'%s' is outside repository at '%s'"), path,
155 absolute_path(hint_path));
156 }
157 return r;
158}
159
160int path_inside_repo(struct repository *repo, const char *prefix, const char *path)
161{
162 int len = prefix ? strlen(prefix) : 0;
163 char *r = prefix_path_gently(repo, prefix, len, NULL, path);
164 if (r) {
165 free(r);
166 return 1;
167 }
168 return 0;
169}
170
171int check_filename(const char *prefix, const char *arg)
172{
173 char *to_free = NULL;
174 struct stat st;
175
176 if (skip_prefix(arg, ":/", &arg)) {
177 if (!*arg) /* ":/" is root dir, always exists */
178 return 1;
179 prefix = NULL;
180 } else if (skip_prefix(arg, ":!", &arg) ||
181 skip_prefix(arg, ":^", &arg)) {
182 if (!*arg) /* excluding everything is silly, but allowed */
183 return 1;
184 }
185
186 if (prefix)
187 arg = to_free = prefix_filename(prefix, arg);
188
189 if (!lstat(arg, &st)) {
190 free(to_free);
191 return 1; /* file exists */
192 }
193 if (is_missing_file_error(errno)) {
194 free(to_free);
195 return 0; /* file does not exist */
196 }
197 die_errno(_("failed to stat '%s'"), arg);
198}
199
200static void NORETURN die_verify_filename(struct repository *r,
201 const char *prefix,
202 const char *arg,
203 int diagnose_misspelt_rev)
204{
205 if (!diagnose_misspelt_rev)
206 die(_("%s: no such path in the working tree.\n"
207 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
208 arg);
209 /*
210 * Saying "'(icase)foo' does not exist in the index" when the
211 * user gave us ":(icase)foo" is just stupid. A magic pathspec
212 * begins with a colon and is followed by a non-alnum; do not
213 * let maybe_die_on_misspelt_object_name() even trigger.
214 */
215 if (!(arg[0] == ':' && !isalnum(arg[1])))
216 maybe_die_on_misspelt_object_name(r, arg, prefix);
217
218 /* ... or fall back the most general message. */
219 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
220 "Use '--' to separate paths from revisions, like this:\n"
221 "'git <command> [<revision>...] -- [<file>...]'"), arg);
222
223}
224
225/*
226 * Check for arguments that don't resolve as actual files,
227 * but which look sufficiently like pathspecs that we'll consider
228 * them such for the purposes of rev/pathspec DWIM parsing.
229 */
230static int looks_like_pathspec(const char *arg)
231{
232 const char *p;
233 int escaped = 0;
234
235 /*
236 * Wildcard characters imply the user is looking to match pathspecs
237 * that aren't in the filesystem. Note that this doesn't include
238 * backslash even though it's a glob special; by itself it doesn't
239 * cause any increase in the match. Likewise ignore backslash-escaped
240 * wildcard characters.
241 */
242 for (p = arg; *p; p++) {
243 if (escaped) {
244 escaped = 0;
245 } else if (is_glob_special(*p)) {
246 if (*p == '\\')
247 escaped = 1;
248 else
249 return 1;
250 }
251 }
252
253 /* long-form pathspec magic */
254 if (starts_with(arg, ":("))
255 return 1;
256
257 return 0;
258}
259
260/*
261 * Verify a filename that we got as an argument for a pathspec
262 * entry. Note that a filename that begins with "-" never verifies
263 * as true, because even if such a filename were to exist, we want
264 * it to be preceded by the "--" marker (or we want the user to
265 * use a format like "./-filename")
266 *
267 * The "diagnose_misspelt_rev" is used to provide a user-friendly
268 * diagnosis when dying upon finding that "name" is not a pathname.
269 * If set to 1, the diagnosis will try to diagnose "name" as an
270 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
271 * will only complain about an inexisting file.
272 *
273 * This function is typically called to check that a "file or rev"
274 * argument is unambiguous. In this case, the caller will want
275 * diagnose_misspelt_rev == 1 when verifying the first non-rev
276 * argument (which could have been a revision), and
277 * diagnose_misspelt_rev == 0 for the next ones (because we already
278 * saw a filename, there's not ambiguity anymore).
279 */
280void verify_filename(struct repository *repo,
281 const char *prefix,
282 const char *arg,
283 int diagnose_misspelt_rev)
284{
285 if (*arg == '-')
286 die(_("option '%s' must come before non-option arguments"), arg);
287 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
288 return;
289 die_verify_filename(repo, prefix, arg, diagnose_misspelt_rev);
290}
291
292/*
293 * Opposite of the above: the command line did not have -- marker
294 * and we parsed the arg as a refname. It should not be interpretable
295 * as a filename.
296 */
297void verify_non_filename(struct repository *repo, const char *prefix, const char *arg)
298{
299 if (!is_inside_work_tree(repo) || is_inside_git_dir(repo))
300 return;
301 if (*arg == '-')
302 return; /* flag */
303 if (!check_filename(prefix, arg))
304 return;
305 die(_("ambiguous argument '%s': both revision and filename\n"
306 "Use '--' to separate paths from revisions, like this:\n"
307 "'git <command> [<revision>...] -- [<file>...]'"), arg);
308}
309
310int get_common_dir(struct strbuf *sb, const char *gitdir)
311{
312 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
313 if (git_env_common_dir) {
314 strbuf_addstr(sb, git_env_common_dir);
315 return 1;
316 } else {
317 return get_common_dir_noenv(sb, gitdir);
318 }
319}
320
321int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
322{
323 struct strbuf data = STRBUF_INIT;
324 struct strbuf path = STRBUF_INIT;
325 int ret = 0;
326
327 strbuf_addf(&path, "%s/commondir", gitdir);
328 if (file_exists(path.buf)) {
329 if (strbuf_read_file(&data, path.buf, 0) <= 0)
330 die_errno(_("failed to read %s"), path.buf);
331 while (data.len && (data.buf[data.len - 1] == '\n' ||
332 data.buf[data.len - 1] == '\r'))
333 data.len--;
334 data.buf[data.len] = '\0';
335 strbuf_reset(&path);
336 if (!is_absolute_path(data.buf))
337 strbuf_addf(&path, "%s/", gitdir);
338 strbuf_addbuf(&path, &data);
339 strbuf_add_real_path(sb, path.buf);
340 ret = 1;
341 } else {
342 strbuf_addstr(sb, gitdir);
343 }
344
345 strbuf_release(&data);
346 strbuf_release(&path);
347 return ret;
348}
349
350static int validate_headref(const char *path)
351{
352 struct stat st;
353 char buffer[256];
354 const char *refname;
355 struct object_id oid;
356 int fd;
357 ssize_t len;
358
359 if (lstat(path, &st) < 0)
360 return -1;
361
362 /* Make sure it is a "refs/.." symlink */
363 if (S_ISLNK(st.st_mode)) {
364 len = readlink(path, buffer, sizeof(buffer)-1);
365 if (len >= 5 && !memcmp("refs/", buffer, 5))
366 return 0;
367 return -1;
368 }
369
370 /*
371 * Anything else, just open it and try to see if it is a symbolic ref.
372 */
373 fd = open(path, O_RDONLY);
374 if (fd < 0)
375 return -1;
376 len = read_in_full(fd, buffer, sizeof(buffer)-1);
377 close(fd);
378
379 if (len < 0)
380 return -1;
381 buffer[len] = '\0';
382
383 /*
384 * Is it a symbolic ref?
385 */
386 if (skip_prefix(buffer, "ref:", &refname)) {
387 while (isspace(*refname))
388 refname++;
389 if (starts_with(refname, "refs/"))
390 return 0;
391 }
392
393 /*
394 * Is this a detached HEAD?
395 */
396 if (get_oid_hex_any(buffer, &oid) != GIT_HASH_UNKNOWN)
397 return 0;
398
399 return -1;
400}
401
402/*
403 * Test if it looks like we're at a git directory.
404 * We want to see:
405 *
406 * - either an objects/ directory _or_ the proper
407 * GIT_OBJECT_DIRECTORY environment variable
408 * - a refs/ directory
409 * - either a HEAD symlink or a HEAD file that is formatted as
410 * a proper "ref:", or a regular file HEAD that has a properly
411 * formatted sha1 object name.
412 */
413int is_git_directory(const char *suspect)
414{
415 struct strbuf path = STRBUF_INIT;
416 int ret = 0;
417 size_t len;
418
419 /* Check worktree-related signatures */
420 strbuf_addstr(&path, suspect);
421 strbuf_complete(&path, '/');
422 strbuf_addstr(&path, "HEAD");
423 if (validate_headref(path.buf))
424 goto done;
425
426 strbuf_reset(&path);
427 get_common_dir(&path, suspect);
428 len = path.len;
429
430 /* Check non-worktree-related signatures */
431 if (getenv(DB_ENVIRONMENT)) {
432 if (access(getenv(DB_ENVIRONMENT), X_OK))
433 goto done;
434 }
435 else {
436 strbuf_setlen(&path, len);
437 strbuf_addstr(&path, "/objects");
438 if (access(path.buf, X_OK))
439 goto done;
440 }
441
442 strbuf_setlen(&path, len);
443 strbuf_addstr(&path, "/refs");
444 if (access(path.buf, X_OK))
445 goto done;
446
447 ret = 1;
448done:
449 strbuf_release(&path);
450 return ret;
451}
452
453int is_nonbare_repository_dir(struct strbuf *path)
454{
455 int ret = 0;
456 int gitfile_error;
457 size_t orig_path_len = path->len;
458 assert(orig_path_len != 0);
459 strbuf_complete(path, '/');
460 strbuf_addstr(path, ".git");
461 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
462 ret = 1;
463 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
464 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
465 ret = 1;
466 strbuf_setlen(path, orig_path_len);
467 return ret;
468}
469
470int is_inside_git_dir(struct repository *repo)
471{
472 struct strbuf buf = STRBUF_INIT;
473 int ret = is_inside_dir(strbuf_realpath(&buf, repo_get_git_dir(repo), 1));
474 strbuf_release(&buf);
475 return ret;
476}
477
478int is_inside_work_tree(struct repository *repo)
479{
480 struct strbuf buf = STRBUF_INIT;
481 const char *worktree;
482 int ret;
483
484 worktree = repo_get_work_tree(repo);
485 if (!worktree)
486 return 0;
487
488 ret = is_inside_dir(strbuf_realpath(&buf, worktree, 1));
489
490 strbuf_release(&buf);
491 return ret;
492}
493
494void setup_work_tree(struct repository *repo)
495{
496 const char *work_tree;
497
498 if (repo->worktree_config_is_bogus)
499 die(_("unable to set up work tree using invalid config"));
500
501 work_tree = repo_get_work_tree(repo);
502 if (!work_tree || chdir_notify(work_tree))
503 die(_("this operation must be run in a work tree"));
504
505 /*
506 * Make sure subsequent git processes find correct worktree
507 * if $GIT_WORK_TREE is set relative
508 */
509 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
510 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
511}
512
513static void setup_original_cwd(struct repository *repo)
514{
515 struct strbuf tmp = STRBUF_INIT;
516 const char *worktree = NULL;
517 int offset = -1;
518
519 if (!tmp_original_cwd)
520 return;
521
522 /*
523 * startup_info->original_cwd points to the current working
524 * directory we inherited from our parent process, which is a
525 * directory we want to avoid removing.
526 *
527 * For convenience, we would like to have the path relative to the
528 * worktree instead of an absolute path.
529 *
530 * Yes, startup_info->original_cwd is usually the same as 'prefix',
531 * but differs in two ways:
532 * - prefix has a trailing '/'
533 * - if the user passes '-C' to git, that modifies the prefix but
534 * not startup_info->original_cwd.
535 */
536
537 /* Normalize the directory */
538 if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) {
539 trace2_data_string("setup", repo,
540 "realpath-path", tmp_original_cwd);
541 trace2_data_string("setup", repo,
542 "realpath-failure", strerror(errno));
543 free((char*)tmp_original_cwd);
544 tmp_original_cwd = NULL;
545 return;
546 }
547
548 free((char*)tmp_original_cwd);
549 tmp_original_cwd = NULL;
550 startup_info->original_cwd = strbuf_detach(&tmp, NULL);
551
552 /*
553 * Get our worktree; we only protect the current working directory
554 * if it's in the worktree.
555 */
556 worktree = repo_get_work_tree(repo);
557 if (!worktree)
558 goto no_prevention_needed;
559
560 offset = dir_inside_of(startup_info->original_cwd, worktree);
561 if (offset >= 0) {
562 /*
563 * If startup_info->original_cwd == worktree, that is already
564 * protected and we don't need original_cwd as a secondary
565 * protection measure.
566 */
567 if (!*(startup_info->original_cwd + offset))
568 goto no_prevention_needed;
569
570 /*
571 * original_cwd was inside worktree; precompose it just as
572 * we do prefix so that built up paths will match
573 */
574 startup_info->original_cwd = \
575 precompose_string_if_needed(startup_info->original_cwd
576 + offset);
577 return;
578 }
579
580no_prevention_needed:
581 free((char*)startup_info->original_cwd);
582 startup_info->original_cwd = NULL;
583}
584
585static int read_worktree_config(const char *var, const char *value,
586 const struct config_context *ctx UNUSED,
587 void *vdata)
588{
589 struct repository_format *data = vdata;
590
591 if (strcmp(var, "core.bare") == 0) {
592 data->is_bare = git_config_bool(var, value);
593 } else if (strcmp(var, "core.worktree") == 0) {
594 if (!value)
595 return config_error_nonbool(var);
596 free(data->work_tree);
597 data->work_tree = xstrdup(value);
598 }
599 return 0;
600}
601
602enum extension_result {
603 EXTENSION_ERROR = -1, /* compatible with error(), etc */
604 EXTENSION_UNKNOWN = 0,
605 EXTENSION_OK = 1
606};
607
608/*
609 * Do not add new extensions to this function. It handles extensions which are
610 * respected even in v0-format repositories for historical compatibility.
611 */
612static enum extension_result handle_extension_v0(const char *var,
613 const char *value,
614 const char *ext,
615 struct repository_format *data)
616{
617 if (!strcmp(ext, "noop")) {
618 return EXTENSION_OK;
619 } else if (!strcmp(ext, "preciousobjects")) {
620 data->precious_objects = git_config_bool(var, value);
621 return EXTENSION_OK;
622 } else if (!strcmp(ext, "partialclone")) {
623 if (!value)
624 return config_error_nonbool(var);
625 data->partial_clone = xstrdup(value);
626 return EXTENSION_OK;
627 } else if (!strcmp(ext, "worktreeconfig")) {
628 data->worktree_config = git_config_bool(var, value);
629 return EXTENSION_OK;
630 }
631
632 return EXTENSION_UNKNOWN;
633}
634
635/*
636 * Record any new extensions in this function.
637 */
638static enum extension_result handle_extension(const char *var,
639 const char *value,
640 const char *ext,
641 struct repository_format *data)
642{
643 if (!strcmp(ext, "noop-v1")) {
644 return EXTENSION_OK;
645 } else if (!strcmp(ext, "objectformat")) {
646 int format;
647
648 if (!value)
649 return config_error_nonbool(var);
650 format = hash_algo_by_name(value);
651 if (format == GIT_HASH_UNKNOWN)
652 return error(_("invalid value for '%s': '%s'"),
653 "extensions.objectformat", value);
654 data->hash_algo = format;
655 return EXTENSION_OK;
656 } else if (!strcmp(ext, "compatobjectformat")) {
657 struct string_list_item *item;
658 int format;
659
660 if (!value)
661 return config_error_nonbool(var);
662 format = hash_algo_by_name(value);
663 if (format == GIT_HASH_UNKNOWN)
664 return error(_("invalid value for '%s': '%s'"),
665 "extensions.compatobjectformat", value);
666 /* For now only support compatObjectFormat being specified once. */
667 for_each_string_list_item(item, &data->v1_only_extensions) {
668 if (!strcmp(item->string, "compatobjectformat"))
669 return error(_("'%s' already specified as '%s'"),
670 "extensions.compatobjectformat",
671 hash_algos[data->compat_hash_algo].name);
672 }
673 data->compat_hash_algo = format;
674 return EXTENSION_OK;
675 } else if (!strcmp(ext, "refstorage")) {
676 unsigned int format;
677
678 if (!value)
679 return config_error_nonbool(var);
680
681 FREE_AND_NULL(data->ref_storage_payload);
682 format = ref_storage_format_by_uri(value,
683 &data->ref_storage_payload);
684
685 if (format == REF_STORAGE_FORMAT_UNKNOWN)
686 return error(_("invalid value for '%s': '%s'"),
687 "extensions.refstorage", value);
688 data->ref_storage_format = format;
689 return EXTENSION_OK;
690 } else if (!strcmp(ext, "objectstorage")) {
691 enum object_storage_format format;
692
693 if (!value)
694 return config_error_nonbool(var);
695
696 FREE_AND_NULL(data->object_storage_payload);
697 format = object_storage_format_by_uri(value, &data->object_storage_payload);
698 if (format == OBJECT_STORAGE_FORMAT_UNKNOWN)
699 return error(_("invalid value for '%s': '%s'"),
700 "extensions.objectstorage", value);
701 data->object_storage_format = format;
702
703 return EXTENSION_OK;
704 } else if (!strcmp(ext, "relativeworktrees")) {
705 data->relative_worktrees = git_config_bool(var, value);
706 return EXTENSION_OK;
707 } else if (!strcmp(ext, "submodulepathconfig")) {
708 data->submodule_path_cfg = git_config_bool(var, value);
709 return EXTENSION_OK;
710 }
711 return EXTENSION_UNKNOWN;
712}
713
714static int check_repo_format(const char *var, const char *value,
715 const struct config_context *ctx, void *vdata)
716{
717 struct repository_format *data = vdata;
718 const char *ext;
719
720 if (strcmp(var, "core.repositoryformatversion") == 0)
721 data->version = git_config_int(var, value, ctx->kvi);
722 else if (skip_prefix(var, "extensions.", &ext)) {
723 switch (handle_extension_v0(var, value, ext, data)) {
724 case EXTENSION_ERROR:
725 return -1;
726 case EXTENSION_OK:
727 return 0;
728 case EXTENSION_UNKNOWN:
729 break;
730 }
731
732 switch (handle_extension(var, value, ext, data)) {
733 case EXTENSION_ERROR:
734 return -1;
735 case EXTENSION_OK:
736 string_list_append(&data->v1_only_extensions, ext);
737 return 0;
738 case EXTENSION_UNKNOWN:
739 string_list_append(&data->unknown_extensions, ext);
740 return 0;
741 }
742 }
743
744 return read_worktree_config(var, value, ctx, vdata);
745}
746
747static int read_and_verify_repository_format(struct repository_format *format,
748 const char *gitdir,
749 int *nongit_ok)
750{
751 struct strbuf sb = STRBUF_INIT;
752 struct strbuf err = STRBUF_INIT;
753 int has_common;
754
755 has_common = get_common_dir(&sb, gitdir);
756 strbuf_addstr(&sb, "/config");
757 read_repository_format(format, sb.buf);
758 strbuf_release(&sb);
759
760 /*
761 * For historical use of check_and_apply_repository_format() in git-init,
762 * we treat a missing config as a silent "ok", even when nongit_ok
763 * is unset.
764 */
765 if (format->version < 0)
766 return 0;
767
768 if (verify_repository_format(format, &err) < 0) {
769 if (nongit_ok) {
770 warning("%s", err.buf);
771 strbuf_release(&err);
772 *nongit_ok = -1;
773 return -1;
774 }
775 die("%s", err.buf);
776 }
777
778 string_list_clear(&format->unknown_extensions, 0);
779 string_list_clear(&format->v1_only_extensions, 0);
780
781 if (format->worktree_config) {
782 /*
783 * pick up core.bare and core.worktree from per-worktree
784 * config if present
785 */
786 strbuf_addf(&sb, "%s/config.worktree", gitdir);
787 git_config_from_file(read_worktree_config, sb.buf, format);
788 strbuf_release(&sb);
789 has_common = 0;
790 }
791
792 if (startup_info->force_bare_repository) {
793 format->is_bare = 1;
794 FREE_AND_NULL(format->work_tree);
795 } else if (has_common) {
796 /*
797 * When sharing a common dir with another repository (e.g. a
798 * linked worktree), do not let this repository's config
799 * dictate bareness; it is inherited from the main worktree.
800 */
801 format->is_bare = -1;
802
803 /*
804 * Furthermore, "core.worktree" is supposed to be ignored when
805 * we have a commondir configured, unless it comes from the
806 * per-worktree configuration.
807 */
808 FREE_AND_NULL(format->work_tree);
809 }
810
811 return 0;
812}
813
814int upgrade_repository_format(struct repository *repo, int target_version)
815{
816 struct strbuf sb = STRBUF_INIT;
817 struct strbuf err = STRBUF_INIT;
818 struct strbuf repo_version = STRBUF_INIT;
819 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
820 int ret;
821
822 repo_common_path_append(repo, &sb, "config");
823 read_repository_format(&repo_fmt, sb.buf);
824 strbuf_release(&sb);
825
826 if (repo_fmt.version >= target_version) {
827 ret = 0;
828 goto out;
829 }
830
831 if (verify_repository_format(&repo_fmt, &err) < 0) {
832 ret = error("cannot upgrade repository format from %d to %d: %s",
833 repo_fmt.version, target_version, err.buf);
834 goto out;
835 }
836 if (!repo_fmt.version && repo_fmt.unknown_extensions.nr) {
837 ret = error("cannot upgrade repository format: "
838 "unknown extension %s",
839 repo_fmt.unknown_extensions.items[0].string);
840 goto out;
841 }
842
843 strbuf_addf(&repo_version, "%d", target_version);
844 repo_config_set(repo, "core.repositoryformatversion", repo_version.buf);
845
846 ret = 1;
847
848out:
849 clear_repository_format(&repo_fmt);
850 strbuf_release(&repo_version);
851 strbuf_release(&err);
852 return ret;
853}
854
855static void init_repository_format(struct repository_format *format)
856{
857 const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
858
859 memcpy(format, &fresh, sizeof(fresh));
860}
861
862int read_repository_format(struct repository_format *format, const char *path)
863{
864 clear_repository_format(format);
865 format->hash_algo = GIT_HASH_SHA1_LEGACY;
866 git_config_from_file(check_repo_format, path, format);
867 if (format->version == -1) {
868 clear_repository_format(format);
869 format->hash_algo = GIT_HASH_SHA1_LEGACY;
870 }
871 return format->version;
872}
873
874void clear_repository_format(struct repository_format *format)
875{
876 string_list_clear(&format->unknown_extensions, 0);
877 string_list_clear(&format->v1_only_extensions, 0);
878 free(format->work_tree);
879 free(format->partial_clone);
880 free(format->ref_storage_payload);
881 free(format->object_storage_payload);
882 init_repository_format(format);
883}
884
885int verify_repository_format(const struct repository_format *format,
886 struct strbuf *err)
887{
888 if (GIT_REPO_VERSION_READ < format->version) {
889 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
890 GIT_REPO_VERSION_READ, format->version);
891 return -1;
892 }
893
894 if (format->version >= 1 && format->unknown_extensions.nr) {
895 int i;
896
897 strbuf_addstr(err, Q_("unknown repository extension found:",
898 "unknown repository extensions found:",
899 format->unknown_extensions.nr));
900
901 for (i = 0; i < format->unknown_extensions.nr; i++)
902 strbuf_addf(err, "\n\t%s",
903 format->unknown_extensions.items[i].string);
904 return -1;
905 }
906
907 if (format->version == 0 && format->v1_only_extensions.nr) {
908 int i;
909
910 strbuf_addstr(err,
911 Q_("repo version is 0, but v1-only extension found:",
912 "repo version is 0, but v1-only extensions found:",
913 format->v1_only_extensions.nr));
914
915 for (i = 0; i < format->v1_only_extensions.nr; i++)
916 strbuf_addf(err, "\n\t%s",
917 format->v1_only_extensions.items[i].string);
918 return -1;
919 }
920
921 return 0;
922}
923
924void read_gitfile_error_die(int error_code, const char *path)
925{
926 switch (error_code) {
927 case READ_GITFILE_ERR_NOT_A_FILE:
928 case READ_GITFILE_ERR_STAT_FAILED:
929 case READ_GITFILE_ERR_MISSING:
930 case READ_GITFILE_ERR_IS_A_DIR:
931 /* non-fatal; follow return path */
932 break;
933 case READ_GITFILE_ERR_OPEN_FAILED:
934 die_errno(_("error opening '%s'"), path);
935 case READ_GITFILE_ERR_TOO_LARGE:
936 die(_("too large to be a .git file: '%s'"), path);
937 case READ_GITFILE_ERR_READ_FAILED:
938 die(_("error reading %s"), path);
939 case READ_GITFILE_ERR_INVALID_FORMAT:
940 die(_("invalid gitfile format: %s"), path);
941 case READ_GITFILE_ERR_NO_PATH:
942 die(_("no path in gitfile: %s"), path);
943 case READ_GITFILE_ERR_NOT_A_REPO:
944 die(_("gitfile does not point to a valid repository: %s"),
945 path);
946 default:
947 BUG("unknown error code");
948 }
949}
950
951/*
952 * Try to read the location of the git directory from the .git file,
953 * return path to git directory if found. The return value comes from
954 * a shared buffer.
955 *
956 * On failure, if return_error_code is not NULL, return_error_code
957 * will be set to an error code and NULL will be returned. If
958 * return_error_code is NULL the function will die instead (for most
959 * cases).
960 */
961const char *read_gitfile_gently(const char *path, int *return_error_code)
962{
963 int error_code = 0;
964 const char *slash;
965 struct strbuf contents = STRBUF_INIT;
966 static struct strbuf realpath = STRBUF_INIT;
967
968 error_code = read_gitfile_raw(&contents, path);
969 if (error_code)
970 goto cleanup_return;
971
972 if (!is_absolute_path(contents.buf) && (slash = strrchr(path, '/'))) {
973 size_t pathlen = slash+1 - path;
974 char *dir = xstrfmt("%.*s%s", (int)pathlen, path, contents.buf);
975 strbuf_reset(&contents);
976 strbuf_addstr(&contents, dir);
977 free(dir);
978 }
979 if (!is_git_directory(contents.buf)) {
980 error_code = READ_GITFILE_ERR_NOT_A_REPO;
981 goto cleanup_return;
982 }
983
984 strbuf_realpath(&realpath, contents.buf, 1);
985
986cleanup_return:
987 if (return_error_code)
988 *return_error_code = error_code;
989 else if (error_code)
990 read_gitfile_error_die(error_code, path);
991
992 strbuf_release(&contents);
993 return error_code ? NULL : realpath.buf;
994}
995
996/*
997 * Read the path following "gitdir: " from the .git file into strbuf.
998 *
999 * Unlike read_gitfile_gently(), this function does not resolve a
1000 * relative path or validate it using is_git_directory().
1001 */
1002int read_gitfile_raw(struct strbuf *contents, const char *path)
1003{
1004 const int max_file_size = 1 << 20; /* 1MB */
1005 int error_code = 0;
1006 char *buf = NULL;
1007 struct stat st;
1008 int fd;
1009 ssize_t len;
1010
1011 if (stat(path, &st)) {
1012 if (errno == ENOENT || errno == ENOTDIR)
1013 error_code = READ_GITFILE_ERR_MISSING;
1014 else
1015 error_code = READ_GITFILE_ERR_STAT_FAILED;
1016 goto cleanup_return;
1017 }
1018 if (S_ISDIR(st.st_mode)) {
1019 error_code = READ_GITFILE_ERR_IS_A_DIR;
1020 goto cleanup_return;
1021 }
1022 if (!S_ISREG(st.st_mode)) {
1023 error_code = READ_GITFILE_ERR_NOT_A_FILE;
1024 goto cleanup_return;
1025 }
1026 if (st.st_size > max_file_size) {
1027 error_code = READ_GITFILE_ERR_TOO_LARGE;
1028 goto cleanup_return;
1029 }
1030 fd = open(path, O_RDONLY);
1031 if (fd < 0) {
1032 error_code = READ_GITFILE_ERR_OPEN_FAILED;
1033 goto cleanup_return;
1034 }
1035 buf = xmallocz(st.st_size);
1036 len = read_in_full(fd, buf, st.st_size);
1037 close(fd);
1038 if (len != st.st_size) {
1039 error_code = READ_GITFILE_ERR_READ_FAILED;
1040 goto cleanup_return;
1041 }
1042 if (!starts_with(buf, "gitdir: ")) {
1043 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
1044 goto cleanup_return;
1045 }
1046 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
1047 len--;
1048 if (len < 9) {
1049 error_code = READ_GITFILE_ERR_NO_PATH;
1050 goto cleanup_return;
1051 }
1052 strbuf_add(contents, buf+8, len-8);
1053
1054cleanup_return:
1055 free(buf);
1056 return error_code;
1057}
1058
1059static void apply_gitdir_and_environment(struct repository *repo, const char *path)
1060{
1061 struct strvec to_free = STRVEC_INIT;
1062 struct set_gitdir_args args = {
1063 .commondir = getenv_safe(&to_free, GIT_COMMON_DIR_ENVIRONMENT),
1064 .graft_file = getenv_safe(&to_free, GRAFT_ENVIRONMENT),
1065 .index_file = getenv_safe(&to_free, INDEX_ENVIRONMENT),
1066 .disable_ref_updates = !!getenv(GIT_QUARANTINE_ENVIRONMENT),
1067 };
1068
1069 repo_set_gitdir(repo, path, &args);
1070
1071 strvec_clear(&to_free);
1072}
1073
1074static void update_relative_gitdir(const char *old_cwd,
1075 const char *new_cwd,
1076 void *data)
1077{
1078 struct repository *repo = data;
1079 char *path = reparent_relative_path(old_cwd, new_cwd,
1080 repo_get_git_dir(repo));
1081 trace_printf_key(&trace_setup_key,
1082 "setup: move $GIT_DIR to '%s'",
1083 path);
1084 apply_gitdir_and_environment(repo, path);
1085 xsetenv(GIT_DIR_ENVIRONMENT, path, 1);
1086 free(path);
1087}
1088
1089static void apply_and_export_relative_gitdir(struct repository *repo, const char *path, int make_realpath)
1090{
1091 struct strbuf realpath = STRBUF_INIT;
1092
1093 if (make_realpath) {
1094 strbuf_realpath(&realpath, path, 1);
1095 path = realpath.buf;
1096 }
1097
1098 apply_gitdir_and_environment(repo, path);
1099 xsetenv(GIT_DIR_ENVIRONMENT, path, 1);
1100
1101 if (!is_absolute_path(path))
1102 chdir_notify_register(update_relative_gitdir, repo);
1103
1104 strbuf_release(&realpath);
1105}
1106
1107struct repo_discovery {
1108 struct repository_format format;
1109 char *gitdir;
1110 char *worktree;
1111 char *prefix;
1112};
1113
1114#define REPO_DISCOVERY_INIT { \
1115 .format = REPOSITORY_FORMAT_INIT, \
1116}
1117
1118static void repo_discovery_release(struct repo_discovery *r)
1119{
1120 clear_repository_format(&r->format);
1121 free(r->gitdir);
1122 free(r->worktree);
1123 free(r->prefix);
1124}
1125
1126static void repo_discovery_set_gitdir(struct repo_discovery *r,
1127 const char *gitdir,
1128 int make_realpath)
1129{
1130 free(r->gitdir);
1131 if (make_realpath) {
1132 struct strbuf realpath = STRBUF_INIT;
1133 strbuf_realpath(&realpath, gitdir, 1);
1134 r->gitdir = strbuf_detach(&realpath, NULL);
1135 } else {
1136 r->gitdir = xstrdup(gitdir);
1137 }
1138}
1139
1140static void repo_discovery_set_worktree(struct repo_discovery *r,
1141 const char *worktree)
1142{
1143 free(r->worktree);
1144 r->worktree = real_pathdup(worktree, 1);
1145}
1146
1147static void repo_discover_explicit_gitdir(struct repo_discovery *discovery,
1148 const char *gitdirenv,
1149 struct strbuf *cwd,
1150 int *nongit_ok)
1151{
1152 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
1153 char *gitfile;
1154 int offset;
1155
1156 if (PATH_MAX - 40 < strlen(gitdirenv))
1157 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
1158
1159 gitfile = (char*)read_gitfile(gitdirenv);
1160 if (gitfile) {
1161 gitfile = xstrdup(gitfile);
1162 gitdirenv = gitfile;
1163 }
1164
1165 if (!is_git_directory(gitdirenv)) {
1166 if (nongit_ok) {
1167 *nongit_ok = 1;
1168 goto out;
1169 }
1170 die(_("not a git repository: '%s'"), gitdirenv);
1171 }
1172
1173 if (read_and_verify_repository_format(&discovery->format, gitdirenv, nongit_ok))
1174 goto out;
1175
1176 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
1177 if (work_tree_env) {
1178 /*
1179 * The environment variable overrides "core.worktree". This
1180 * also has the consequence that we don't want to flag cases as
1181 * bogus where we have both "core.worktree" and "core.bare", so
1182 * we have to explicitly unset the configuration.
1183 */
1184 FREE_AND_NULL(discovery->format.work_tree);
1185 repo_discovery_set_worktree(discovery, work_tree_env);
1186 } else if (discovery->format.is_bare > 0) {
1187 /* #18, #26 */
1188 repo_discovery_set_gitdir(discovery, gitdirenv, 0);
1189 goto out;
1190 } else if (discovery->format.work_tree) { /* #6, #14 */
1191 if (is_absolute_path(discovery->format.work_tree)) {
1192 repo_discovery_set_worktree(discovery, discovery->format.work_tree);
1193 } else {
1194 char *core_worktree;
1195 if (chdir(gitdirenv))
1196 die_errno(_("cannot chdir to '%s'"), gitdirenv);
1197 if (chdir(discovery->format.work_tree))
1198 die_errno(_("cannot chdir to '%s'"), discovery->format.work_tree);
1199 core_worktree = xgetcwd();
1200 if (chdir(cwd->buf))
1201 die_errno(_("cannot come back to cwd"));
1202 repo_discovery_set_worktree(discovery, core_worktree);
1203 free(core_worktree);
1204 }
1205 } else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
1206 /* #16d */
1207 repo_discovery_set_gitdir(discovery, gitdirenv, 0);
1208 goto out;
1209 } else { /* #2, #10 */
1210 repo_discovery_set_worktree(discovery, ".");
1211 }
1212
1213 /* both the worktree and cwd are already normalized */
1214 if (!strcmp(cwd->buf, discovery->worktree)) { /* cwd == worktree */
1215 repo_discovery_set_gitdir(discovery, gitdirenv, 0);
1216 goto out;
1217 }
1218
1219 offset = dir_inside_of(cwd->buf, discovery->worktree);
1220 if (offset >= 0) { /* cwd inside discovery->worktree? */
1221 repo_discovery_set_gitdir(discovery, gitdirenv, 1);
1222 if (chdir(discovery->worktree))
1223 die_errno(_("cannot chdir to '%s'"), discovery->worktree);
1224 discovery->prefix = xstrfmt("%s/", cwd->buf + offset);
1225 goto out;
1226 }
1227
1228 /* cwd outside worktree */
1229 repo_discovery_set_gitdir(discovery, gitdirenv, 0);
1230
1231out:
1232 free(gitfile);
1233}
1234
1235static void repo_discover_implicit_gitdir(struct repo_discovery *discovery,
1236 const char *gitdir,
1237 struct strbuf *cwd, int offset,
1238 int *nongit_ok)
1239{
1240 if (read_and_verify_repository_format(&discovery->format, gitdir, nongit_ok))
1241 return;
1242
1243 /* --work-tree is set without --git-dir; use discovered one */
1244 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || discovery->format.work_tree) {
1245 char *to_free = NULL;
1246
1247 if (offset != cwd->len && !is_absolute_path(gitdir))
1248 gitdir = to_free = real_pathdup(gitdir, 1);
1249 if (chdir(cwd->buf))
1250 die_errno(_("cannot come back to cwd"));
1251 repo_discover_explicit_gitdir(discovery, gitdir, cwd,
1252 nongit_ok);
1253 free(to_free);
1254 return;
1255 }
1256
1257 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1258 if (discovery->format.is_bare > 0) {
1259 repo_discovery_set_gitdir(discovery, gitdir, (offset != cwd->len));
1260 if (chdir(cwd->buf))
1261 die_errno(_("cannot come back to cwd"));
1262 return;
1263 }
1264
1265 /* #0, #1, #5, #8, #9, #12, #13 */
1266 repo_discovery_set_worktree(discovery, ".");
1267 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
1268 repo_discovery_set_gitdir(discovery, gitdir, 0);
1269 if (offset >= cwd->len)
1270 return;
1271
1272 /* Make "offset" point past the '/' (already the case for root dirs) */
1273 if (offset != offset_1st_component(cwd->buf))
1274 offset++;
1275 discovery->prefix = xstrfmt("%s/", cwd->buf + offset);
1276}
1277
1278/* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1279static void repo_discover_bare_gitdir(struct repo_discovery *discovery,
1280 struct strbuf *cwd, int offset,
1281 int *nongit_ok)
1282{
1283 int root_len;
1284
1285 if (read_and_verify_repository_format(&discovery->format, ".", nongit_ok))
1286 return;
1287
1288 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
1289
1290 /* --work-tree is set without --git-dir; use discovered one */
1291 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || discovery->format.work_tree) {
1292 char *gitdir = offset == cwd->len ? xstrdup(".") : xmemdupz(cwd->buf, offset);
1293 if (chdir(cwd->buf))
1294 die_errno(_("cannot come back to cwd"));
1295 repo_discover_explicit_gitdir(discovery, gitdir, cwd, nongit_ok);
1296 free(gitdir);
1297 return;
1298 }
1299
1300 if (offset != cwd->len) {
1301 if (chdir(cwd->buf))
1302 die_errno(_("cannot come back to cwd"));
1303 root_len = offset_1st_component(cwd->buf);
1304 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
1305 repo_discovery_set_gitdir(discovery, cwd->buf, 0);
1306 } else {
1307 repo_discovery_set_gitdir(discovery, ".", 0);
1308 }
1309}
1310
1311static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
1312{
1313 struct stat buf;
1314 if (stat(path, &buf)) {
1315 die_errno(_("failed to stat '%*s%s%s'"),
1316 prefix_len,
1317 prefix ? prefix : "",
1318 prefix ? "/" : "", path);
1319 }
1320 return buf.st_dev;
1321}
1322
1323/*
1324 * A "string_list_each_func_t" function that canonicalizes an entry
1325 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1326 * discards it if unusable. The presence of an empty entry in
1327 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1328 * subsequent entries.
1329 */
1330static int canonicalize_ceiling_entry(struct string_list_item *item,
1331 void *cb_data)
1332{
1333 int *empty_entry_found = cb_data;
1334 char *ceil = item->string;
1335
1336 if (!*ceil) {
1337 *empty_entry_found = 1;
1338 return 0;
1339 } else if (!is_absolute_path(ceil)) {
1340 return 0;
1341 } else if (*empty_entry_found) {
1342 /* Keep entry but do not canonicalize it */
1343 return 1;
1344 } else {
1345 char *real_path = real_pathdup(ceil, 0);
1346 if (!real_path) {
1347 return 0;
1348 }
1349 free(item->string);
1350 item->string = real_path;
1351 return 1;
1352 }
1353}
1354
1355void path_allowlist_apply(const char *allowed, const char *target_path,
1356 bool *matches,
1357 bool (*allow_path)(const char *path, void *cbdata),
1358 void *allow_path_cbdata)
1359{
1360 char *normalized = NULL;
1361
1362 if (!allowed || !*allowed) {
1363 *matches = false;
1364 return;
1365 }
1366
1367 if (!strcmp(allowed, "*")) {
1368 *matches = true;
1369 return;
1370 }
1371
1372 if (!allow_path(allowed, allow_path_cbdata))
1373 return;
1374
1375 /*
1376 * A .gitconfig in $HOME may be shared across different
1377 * machines and the config variable entries may or may not
1378 * exist as paths on all of these machines. In other words,
1379 * it is not a warning worthy event when there is no such path
1380 * on this machine---the entry may be useful elsewhere.
1381 *
1382 * NEEDSWORK: this also silently ignores misspelled paths. We
1383 * may want to warn about a missing path unless it is marked
1384 * as allowed to be missing, e.g., with an ":(optional)"
1385 * prefix like pathname-typed configuration values, and hint
1386 * about that prefix in the warning.
1387 */
1388 normalized = real_pathdup(allowed, 0);
1389 if (!normalized)
1390 return;
1391
1392 if (ends_with(normalized, "/*")) {
1393 size_t len = strlen(normalized);
1394 if (!fspathncmp(normalized, target_path, len - 1))
1395 *matches = true;
1396 } else if (!fspathcmp(target_path, normalized)) {
1397 *matches = true;
1398 }
1399
1400 free(normalized);
1401}
1402
1403void path_allowlist_config_apply(const char *key, const char *value,
1404 const char *target_path, bool *matches,
1405 bool (*allow_path)(const char *path, void *cbdata),
1406 void *allow_path_cbdata)
1407{
1408 char *allowed = NULL;
1409
1410 if (!value || !*value || !strcmp(value, "*")) {
1411 path_allowlist_apply(value, target_path, matches,
1412 allow_path, allow_path_cbdata);
1413 return;
1414 }
1415
1416 if (git_config_pathname(&allowed, key, value) || !allowed)
1417 return;
1418
1419 path_allowlist_apply(allowed, target_path, matches,
1420 allow_path, allow_path_cbdata);
1421
1422 free(allowed);
1423}
1424
1425/*
1426 * Setting the config variable to a non-absolute path makes
1427 * little sense---it won't be relative to the configuration
1428 * file the item is defined in. Except for ".", which means
1429 * "if we are at the top level of a repository, then it is
1430 * OK", which is slightly tighter than "*" that allows
1431 * discovery.
1432 */
1433static bool allow_safe_dir(const char *path, void *cbdata_)
1434{
1435 struct path_allowlist_cb_data *cbdata = cbdata_;
1436
1437 if (is_absolute_path(path) || !strcmp(path, "."))
1438 return true;
1439
1440 warning(_("%s '%s' not absolute"), cbdata->key, path);
1441 return false;
1442}
1443
1444struct safe_directory_data {
1445 char *path;
1446 bool is_safe;
1447};
1448
1449static int safe_directory_cb(const char *key, const char *value,
1450 const struct config_context *ctx UNUSED, void *d)
1451{
1452 struct safe_directory_data *data = d;
1453 struct path_allowlist_cb_data cbdata = { .key = key };
1454
1455 if (strcmp(key, "safe.directory"))
1456 return 0;
1457
1458 path_allowlist_config_apply(key, value, data->path, &data->is_safe,
1459 allow_safe_dir, &cbdata);
1460
1461 return 0;
1462}
1463
1464/*
1465 * Check if a repository is safe, by verifying the ownership of the
1466 * worktree (if any), the git directory, and the gitfile (if any).
1467 *
1468 * Exemptions for known-safe repositories can be added via `safe.directory`
1469 * config settings; for non-bare repositories, their worktree needs to be
1470 * added, for bare ones their git directory.
1471 */
1472static int ensure_valid_ownership(const char *gitfile,
1473 const char *worktree, const char *gitdir,
1474 struct strbuf *report)
1475{
1476 struct safe_directory_data data = { 0 };
1477
1478 if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1479 (!gitfile || is_path_owned_by_current_user(gitfile, report)) &&
1480 (!worktree || is_path_owned_by_current_user(worktree, report)) &&
1481 (!gitdir || is_path_owned_by_current_user(gitdir, report)))
1482 return 1;
1483
1484 /*
1485 * normalize the data.path for comparison with normalized paths
1486 * that come from the configuration file. The path is unsafe
1487 * if it cannot be normalized.
1488 */
1489 data.path = real_pathdup(worktree ? worktree : gitdir, 0);
1490 if (!data.path)
1491 return 0;
1492
1493 /*
1494 * data.path is the "path" that identifies the repository and it is
1495 * constant regardless of what failed above. data.is_safe should be
1496 * initialized to false, and might be changed by the callback.
1497 */
1498 git_protected_config(safe_directory_cb, &data);
1499
1500 free(data.path);
1501 return data.is_safe;
1502}
1503
1504void die_upon_dubious_ownership(const char *gitfile, const char *worktree,
1505 const char *gitdir)
1506{
1507 struct strbuf report = STRBUF_INIT, quoted = STRBUF_INIT;
1508 const char *path;
1509
1510 if (ensure_valid_ownership(gitfile, worktree, gitdir, &report))
1511 return;
1512
1513 strbuf_complete(&report, '\n');
1514 path = gitfile ? gitfile : gitdir;
1515 sq_quote_buf_pretty(&quoted, path);
1516
1517 die(_("detected dubious ownership in repository at '%s'\n"
1518 "%s"
1519 "To add an exception for this directory, call:\n"
1520 "\n"
1521 "\tgit config --global --add safe.directory %s"),
1522 path, report.buf, quoted.buf);
1523}
1524
1525static int allowed_bare_repo_cb(const char *key, const char *value,
1526 const struct config_context *ctx UNUSED,
1527 void *d)
1528{
1529 enum allowed_bare_repo *allowed_bare_repo = d;
1530
1531 if (strcasecmp(key, "safe.bareRepository"))
1532 return 0;
1533
1534 if (!strcmp(value, "explicit")) {
1535 *allowed_bare_repo = ALLOWED_BARE_REPO_EXPLICIT;
1536 return 0;
1537 }
1538 if (!strcmp(value, "all")) {
1539 *allowed_bare_repo = ALLOWED_BARE_REPO_ALL;
1540 return 0;
1541 }
1542 return -1;
1543}
1544
1545static enum allowed_bare_repo get_allowed_bare_repo(void)
1546{
1547#ifdef WITH_BREAKING_CHANGES
1548 enum allowed_bare_repo result = ALLOWED_BARE_REPO_EXPLICIT;
1549#else
1550 enum allowed_bare_repo result = ALLOWED_BARE_REPO_ALL;
1551#endif
1552 git_protected_config(allowed_bare_repo_cb, &result);
1553 return result;
1554}
1555
1556static const char *allowed_bare_repo_to_string(
1557 enum allowed_bare_repo allowed_bare_repo)
1558{
1559 switch (allowed_bare_repo) {
1560 case ALLOWED_BARE_REPO_EXPLICIT:
1561 return "explicit";
1562 case ALLOWED_BARE_REPO_ALL:
1563 return "all";
1564 default:
1565 BUG("invalid allowed_bare_repo %d",
1566 allowed_bare_repo);
1567 }
1568 return NULL;
1569}
1570
1571static int is_implicit_bare_repo(const char *path)
1572{
1573 /*
1574 * what we found is a ".git" directory at the root of
1575 * the working tree.
1576 */
1577 if (ends_with_path_components(path, ".git"))
1578 return 1;
1579
1580 /*
1581 * we are inside $GIT_DIR of a secondary worktree of a
1582 * non-bare repository.
1583 */
1584 if (strstr(path, "/.git/worktrees/"))
1585 return 1;
1586
1587 /*
1588 * we are inside $GIT_DIR of a worktree of a non-embedded
1589 * submodule, whose superproject is not a bare repository.
1590 */
1591 if (strstr(path, "/.git/modules/"))
1592 return 1;
1593
1594 return 0;
1595}
1596
1597/*
1598 * We cannot decide in this function whether we are in the work tree or
1599 * not, since the config can only be read _after_ this function was called.
1600 *
1601 * Also, we avoid changing any global state (such as the current working
1602 * directory) to allow early callers.
1603 *
1604 * The directory where the search should start needs to be passed in via the
1605 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1606 * the directory where the search ended, and `gitdir` will contain the path of
1607 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1608 * is relative to `dir` (i.e. *not* necessarily the cwd).
1609 */
1610static enum discovery_result repo_discovery_find_dir(struct strbuf *dir,
1611 struct strbuf *gitdir,
1612 struct strbuf *report,
1613 int die_on_error)
1614{
1615 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
1616 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
1617 const char *gitdirenv;
1618 int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
1619 dev_t current_device = 0;
1620 int one_filesystem = 1;
1621
1622 /*
1623 * If GIT_DIR is set explicitly, we're not going
1624 * to do any discovery, but we still do repository
1625 * validation.
1626 */
1627 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
1628 if (gitdirenv) {
1629 strbuf_addstr(gitdir, gitdirenv);
1630 return GIT_DIR_EXPLICIT;
1631 }
1632
1633 if (env_ceiling_dirs) {
1634 int empty_entry_found = 0;
1635 static const char path_sep[] = { PATH_SEP, '\0' };
1636
1637 string_list_split(&ceiling_dirs, env_ceiling_dirs, path_sep, -1);
1638 filter_string_list(&ceiling_dirs, 0,
1639 canonicalize_ceiling_entry, &empty_entry_found);
1640 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
1641 string_list_clear(&ceiling_dirs, 0);
1642 }
1643
1644 if (ceil_offset < 0)
1645 ceil_offset = min_offset - 2;
1646
1647 if (min_offset && min_offset == dir->len &&
1648 !is_dir_sep(dir->buf[min_offset - 1])) {
1649 strbuf_addch(dir, '/');
1650 min_offset++;
1651 }
1652
1653 /*
1654 * Test in the following order (relative to the dir):
1655 * - .git (file containing "gitdir: <path>")
1656 * - .git/
1657 * - ./ (bare)
1658 * - ../.git
1659 * - ../.git/
1660 * - ../ (bare)
1661 * - ../../.git
1662 * etc.
1663 */
1664 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1665 if (one_filesystem)
1666 current_device = get_device_or_die(dir->buf, NULL, 0);
1667 for (;;) {
1668 int offset = dir->len, error_code = 0;
1669 char *gitdir_path = NULL;
1670 char *gitfile = NULL;
1671
1672 if (offset > min_offset)
1673 strbuf_addch(dir, '/');
1674 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
1675 gitdirenv = read_gitfile_gently(dir->buf, &error_code);
1676 if (!gitdirenv) {
1677 switch (error_code) {
1678 case READ_GITFILE_ERR_MISSING:
1679 /* no .git in this directory, move on */
1680 break;
1681 case READ_GITFILE_ERR_IS_A_DIR:
1682 if (is_git_directory(dir->buf)) {
1683 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1684 gitdir_path = xstrdup(dir->buf);
1685 }
1686 break;
1687 case READ_GITFILE_ERR_STAT_FAILED:
1688 if (die_on_error)
1689 die(_("error reading '%s'"), dir->buf);
1690 else
1691 return GIT_DIR_INVALID_GITFILE;
1692 case READ_GITFILE_ERR_NOT_A_FILE:
1693 if (die_on_error)
1694 die(_("not a regular file: '%s'"), dir->buf);
1695 else
1696 return GIT_DIR_INVALID_GITFILE;
1697 default:
1698 if (die_on_error)
1699 read_gitfile_error_die(error_code, dir->buf);
1700 else
1701 return GIT_DIR_INVALID_GITFILE;
1702 }
1703 } else {
1704 gitfile = xstrdup(dir->buf);
1705 }
1706 /*
1707 * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1708 * to check that directory for a repository.
1709 * Now trim that tentative addition away, because we want to
1710 * focus on the real directory we are in.
1711 */
1712 strbuf_setlen(dir, offset);
1713 if (gitdirenv) {
1714 enum discovery_result ret;
1715 const char *gitdir_candidate =
1716 gitdir_path ? gitdir_path : gitdirenv;
1717
1718 if (ensure_valid_ownership(gitfile, dir->buf,
1719 gitdir_candidate, report)) {
1720 strbuf_addstr(gitdir, gitdirenv);
1721 ret = GIT_DIR_DISCOVERED;
1722 } else
1723 ret = GIT_DIR_INVALID_OWNERSHIP;
1724
1725 /*
1726 * Earlier, during discovery, we might have allocated
1727 * string copies for gitdir_path or gitfile so make
1728 * sure we don't leak by freeing them now, before
1729 * leaving the loop and function.
1730 *
1731 * Note: gitdirenv will be non-NULL whenever these are
1732 * allocated, therefore we need not take care of releasing
1733 * them outside of this conditional block.
1734 */
1735 free(gitdir_path);
1736 free(gitfile);
1737
1738 return ret;
1739 }
1740
1741 if (is_git_directory(dir->buf)) {
1742 trace2_data_string("setup", NULL, "implicit-bare-repository", dir->buf);
1743 if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT &&
1744 !is_implicit_bare_repo(dir->buf))
1745 return GIT_DIR_DISALLOWED_BARE;
1746 if (!ensure_valid_ownership(NULL, NULL, dir->buf, report))
1747 return GIT_DIR_INVALID_OWNERSHIP;
1748 strbuf_addstr(gitdir, ".");
1749 return GIT_DIR_BARE;
1750 }
1751
1752 if (offset <= min_offset)
1753 return GIT_DIR_HIT_CEILING;
1754
1755 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1756 ; /* continue */
1757 if (offset <= ceil_offset)
1758 return GIT_DIR_HIT_CEILING;
1759
1760 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
1761 if (one_filesystem &&
1762 current_device != get_device_or_die(dir->buf, NULL, offset))
1763 return GIT_DIR_HIT_MOUNT_POINT;
1764 }
1765}
1766
1767enum discovery_result discover_git_directory_reason(struct strbuf *commondir,
1768 struct strbuf *gitdir)
1769{
1770 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1771 size_t gitdir_offset = gitdir->len, cwd_len;
1772 size_t commondir_offset = commondir->len;
1773 struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1774 enum discovery_result result;
1775
1776 if (strbuf_getcwd(&dir))
1777 return GIT_DIR_CWD_FAILURE;
1778
1779 cwd_len = dir.len;
1780 result = repo_discovery_find_dir(&dir, gitdir, NULL, 0);
1781 if (result <= 0) {
1782 strbuf_release(&dir);
1783 return result;
1784 }
1785
1786 /*
1787 * The returned gitdir is relative to dir, and if dir does not reflect
1788 * the current working directory, we simply make the gitdir absolute.
1789 */
1790 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1791 /* Avoid a trailing "/." */
1792 if (!strcmp(".", gitdir->buf + gitdir_offset))
1793 strbuf_setlen(gitdir, gitdir_offset);
1794 else
1795 strbuf_addch(&dir, '/');
1796 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1797 }
1798
1799 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1800
1801 strbuf_reset(&dir);
1802 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1803 read_repository_format(&candidate, dir.buf);
1804 strbuf_release(&dir);
1805
1806 if (verify_repository_format(&candidate, &err) < 0) {
1807 warning("ignoring git dir '%s': %s",
1808 gitdir->buf + gitdir_offset, err.buf);
1809 strbuf_release(&err);
1810 strbuf_setlen(commondir, commondir_offset);
1811 strbuf_setlen(gitdir, gitdir_offset);
1812 clear_repository_format(&candidate);
1813 return GIT_DIR_INVALID_FORMAT;
1814 }
1815
1816 clear_repository_format(&candidate);
1817 return result;
1818}
1819
1820int apply_repository_format(struct repository *repo,
1821 const struct repository_format *format,
1822 enum apply_repository_format_flags flags,
1823 struct strbuf *err)
1824{
1825 if (verify_repository_format(format, err) < 0)
1826 return -1;
1827
1828 if (format->is_bare > 0 && format->work_tree) {
1829 /* #22.2, #30 */
1830 warning("core.bare and core.worktree do not make sense");
1831 repo->worktree_config_is_bogus = true;
1832 }
1833
1834 if (flags & APPLY_REPOSITORY_FORMAT_HONOR_ENV) {
1835 const char *shallow_file;
1836
1837 shallow_file = getenv(GIT_SHALLOW_FILE_ENVIRONMENT);
1838 if (shallow_file)
1839 set_alternate_shallow_file(repo, shallow_file);
1840 }
1841
1842 repo->bare_cfg = format->is_bare;
1843 repo_set_hash_algo(repo, format->hash_algo);
1844 repo_set_compat_hash_algo(repo, format->compat_hash_algo);
1845 repo_set_ref_storage_format(repo,
1846 format->ref_storage_format,
1847 format->ref_storage_payload);
1848 repo_set_object_storage_format(repo,
1849 format->object_storage_format,
1850 format->object_storage_payload);
1851 repo->repository_format_worktree_config =
1852 format->worktree_config;
1853 repo->repository_format_submodule_path_cfg =
1854 format->submodule_path_cfg;
1855 repo->repository_format_relative_worktrees =
1856 format->relative_worktrees;
1857 repo->repository_format_partial_clone =
1858 xstrdup_or_null(format->partial_clone);
1859 repo->repository_format_precious_objects =
1860 format->precious_objects;
1861
1862 return 0;
1863}
1864
1865const char *enter_repo(struct repository *repo, const char *path, unsigned flags)
1866{
1867 static struct strbuf validated_path = STRBUF_INIT;
1868 static struct strbuf used_path = STRBUF_INIT;
1869
1870 if (!path)
1871 return NULL;
1872
1873 if (!(flags & ENTER_REPO_STRICT)) {
1874 static const char *suffix[] = {
1875 "/.git", "", ".git/.git", ".git", NULL,
1876 };
1877 const char *gitfile;
1878 int len = strlen(path);
1879 int i;
1880 while ((1 < len) && (path[len-1] == '/'))
1881 len--;
1882
1883 /*
1884 * We can handle arbitrary-sized buffers, but this remains as a
1885 * sanity check on untrusted input.
1886 */
1887 if (PATH_MAX <= len)
1888 return NULL;
1889
1890 strbuf_reset(&used_path);
1891 strbuf_reset(&validated_path);
1892 strbuf_add(&used_path, path, len);
1893 strbuf_add(&validated_path, path, len);
1894
1895 if (used_path.buf[0] == '~') {
1896 char *newpath = interpolate_path(used_path.buf, 0);
1897 if (!newpath)
1898 return NULL;
1899 strbuf_attach(&used_path, newpath, strlen(newpath),
1900 strlen(newpath));
1901 }
1902 for (i = 0; suffix[i]; i++) {
1903 struct stat st;
1904 size_t baselen = used_path.len;
1905 strbuf_addstr(&used_path, suffix[i]);
1906 if (!stat(used_path.buf, &st) &&
1907 (S_ISREG(st.st_mode) ||
1908 (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
1909 strbuf_addstr(&validated_path, suffix[i]);
1910 break;
1911 }
1912 strbuf_setlen(&used_path, baselen);
1913 }
1914 if (!suffix[i])
1915 return NULL;
1916 gitfile = read_gitfile(used_path.buf);
1917 if (!(flags & ENTER_REPO_ANY_OWNER_OK))
1918 die_upon_dubious_ownership(gitfile, NULL, used_path.buf);
1919 if (gitfile) {
1920 strbuf_reset(&used_path);
1921 strbuf_addstr(&used_path, gitfile);
1922 }
1923 if (chdir(used_path.buf))
1924 return NULL;
1925 path = validated_path.buf;
1926 }
1927 else {
1928 const char *gitfile = read_gitfile(path);
1929 if (!(flags & ENTER_REPO_ANY_OWNER_OK))
1930 die_upon_dubious_ownership(gitfile, NULL, path);
1931 if (gitfile)
1932 path = gitfile;
1933 if (chdir(path))
1934 return NULL;
1935 }
1936
1937 if (is_git_directory(".")) {
1938 struct repository_format fmt = REPOSITORY_FORMAT_INIT;
1939 struct strbuf err = STRBUF_INIT;
1940
1941 apply_and_export_relative_gitdir(repo, ".", 0);
1942 read_and_verify_repository_format(&fmt, ".", NULL);
1943 if (apply_repository_format(repo, &fmt, APPLY_REPOSITORY_FORMAT_HONOR_ENV, &err) < 0)
1944 die("%s", err.buf);
1945 repo->objects = odb_new(repo, ODB_NEW_HONOR_ENV);
1946 startup_info->have_repository = 1;
1947
1948 clear_repository_format(&fmt);
1949 strbuf_release(&err);
1950 return path;
1951 }
1952
1953 return NULL;
1954}
1955
1956/*
1957 * Note. This works only before you used a work tree. This was added
1958 * primarily to support git-clone to work in a new repository it just
1959 * created, and is not meant to flip between different work trees.
1960 */
1961static void set_git_work_tree(struct repository *repo, const char *new_work_tree)
1962{
1963 if (repo->worktree_initialized) {
1964 struct strbuf realpath = STRBUF_INIT;
1965
1966 strbuf_realpath(&realpath, new_work_tree, 1);
1967 new_work_tree = realpath.buf;
1968 if (strcmp(new_work_tree, repo->worktree))
1969 die("internal error: work tree has already been set\n"
1970 "Current worktree: %s\nNew worktree: %s",
1971 repo->worktree, new_work_tree);
1972 strbuf_release(&realpath);
1973 return;
1974 }
1975 repo->worktree_initialized = true;
1976 repo_set_worktree(repo, new_work_tree);
1977}
1978
1979static void repo_discover(struct repo_discovery *discovery, int *nongit_ok)
1980{
1981 struct strbuf cwd = STRBUF_INIT;
1982 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT;
1983
1984 /*
1985 * Let's assume that we are in a git repository.
1986 * If it turns out later that we are somewhere else, the value will be
1987 * updated accordingly.
1988 */
1989 if (nongit_ok)
1990 *nongit_ok = 0;
1991
1992 if (strbuf_getcwd(&cwd))
1993 die_errno(_("Unable to read current working directory"));
1994 strbuf_addbuf(&dir, &cwd);
1995
1996 switch (repo_discovery_find_dir(&dir, &gitdir, &report, 1)) {
1997 case GIT_DIR_EXPLICIT:
1998 repo_discover_explicit_gitdir(discovery, gitdir.buf, &cwd,
1999 nongit_ok);
2000 break;
2001 case GIT_DIR_DISCOVERED:
2002 if (dir.len < cwd.len && chdir(dir.buf))
2003 die(_("cannot change to '%s'"), dir.buf);
2004 repo_discover_implicit_gitdir(discovery, gitdir.buf, &cwd, dir.len,
2005 nongit_ok);
2006 break;
2007 case GIT_DIR_BARE:
2008 if (dir.len < cwd.len && chdir(dir.buf))
2009 die(_("cannot change to '%s'"), dir.buf);
2010 repo_discover_bare_gitdir(discovery, &cwd, dir.len, nongit_ok);
2011 break;
2012 case GIT_DIR_HIT_CEILING:
2013 if (!nongit_ok)
2014 die(_("not a git repository (or any of the parent directories): %s"),
2015 DEFAULT_GIT_DIR_ENVIRONMENT);
2016 *nongit_ok = 1;
2017 break;
2018 case GIT_DIR_HIT_MOUNT_POINT:
2019 if (!nongit_ok)
2020 die(_("not a git repository (or any parent up to mount point %s)\n"
2021 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
2022 dir.buf);
2023 *nongit_ok = 1;
2024 break;
2025 case GIT_DIR_INVALID_OWNERSHIP:
2026 if (!nongit_ok) {
2027 struct strbuf quoted = STRBUF_INIT;
2028
2029 strbuf_complete(&report, '\n');
2030 sq_quote_buf_pretty(&quoted, dir.buf);
2031 die(_("detected dubious ownership in repository at '%s'\n"
2032 "%s"
2033 "To add an exception for this directory, call:\n"
2034 "\n"
2035 "\tgit config --global --add safe.directory %s"),
2036 dir.buf, report.buf, quoted.buf);
2037 }
2038 *nongit_ok = 1;
2039 break;
2040 case GIT_DIR_DISALLOWED_BARE:
2041 if (!nongit_ok) {
2042 die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
2043 dir.buf,
2044 allowed_bare_repo_to_string(get_allowed_bare_repo()));
2045 }
2046 *nongit_ok = 1;
2047 break;
2048 case GIT_DIR_CWD_FAILURE:
2049 case GIT_DIR_INVALID_FORMAT:
2050 /*
2051 * As a safeguard against repo_discovery_find_dir returning
2052 * these values, fallthrough to BUG. Otherwise it is possible to
2053 * set startup_info->have_repository to 1 when we did nothing to
2054 * find a repository.
2055 */
2056 default:
2057 BUG("unhandled repo_discovery_find_dir() result");
2058 }
2059
2060 strbuf_release(&dir);
2061 strbuf_release(&cwd);
2062 strbuf_release(&gitdir);
2063 strbuf_release(&report);
2064}
2065
2066const char *setup_git_directory_gently(struct repository *repo, int *nongit_ok)
2067{
2068 struct repo_discovery discovery = REPO_DISCOVERY_INIT;
2069
2070 /*
2071 * We may have read an incomplete configuration before
2072 * setting-up the git directory. If so, clear the cache so
2073 * that the next queries to the configuration reload complete
2074 * configuration (including the per-repo config file that we
2075 * ignored previously).
2076 */
2077 repo_config_clear(repo);
2078
2079 repo_discover(&discovery, nongit_ok);
2080
2081 /*
2082 * At this point, nongit_ok is stable. If it is non-NULL and points
2083 * to a non-zero value, then this means that we haven't found a
2084 * repository and that the caller expects startup_info to reflect
2085 * this.
2086 *
2087 * Regardless of the state of nongit_ok, the_repository->prefix and
2088 * the GIT_PREFIX environment variable must always match. For details
2089 * see Documentation/config/alias.adoc.
2090 */
2091 if (nongit_ok && *nongit_ok)
2092 startup_info->have_repository = 0;
2093 else
2094 startup_info->have_repository = 1;
2095
2096 /*
2097 * Not all paths through the setup code will have recorded a gitdir
2098 * above, so in order to guarantee that the environment is in a
2099 * consistent state after setup, explicitly set up the gitdir and
2100 * environment if we have a repository.
2101 *
2102 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
2103 * code paths so we also need to explicitly setup the environment if
2104 * the user has set GIT_DIR. It may be beneficial to disallow bogus
2105 * GIT_DIR values at some point in the future.
2106 */
2107 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
2108 startup_info->have_repository ||
2109 /* GIT_DIR_EXPLICIT */
2110 getenv(GIT_DIR_ENVIRONMENT)) {
2111 if (discovery.worktree)
2112 set_git_work_tree(repo, discovery.worktree);
2113
2114 if (discovery.gitdir) {
2115 apply_and_export_relative_gitdir(repo, discovery.gitdir, 0);
2116 } else {
2117 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
2118 if (!gitdir)
2119 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
2120 apply_gitdir_and_environment(repo, gitdir);
2121 }
2122
2123 if (startup_info->have_repository) {
2124 struct strbuf err = STRBUF_INIT;
2125 const char *object_storage_uri;
2126 const char *ref_backend_uri;
2127
2128 /*
2129 * The env variable should override the repository config
2130 * for 'extensions.refStorage'.
2131 */
2132 ref_backend_uri = getenv(GIT_REF_STORAGE_FORMAT_ENVIRONMENT);
2133 if (!ref_backend_uri)
2134 ref_backend_uri = getenv(GIT_REFERENCE_BACKEND_ENVIRONMENT);
2135 if (ref_backend_uri) {
2136 FREE_AND_NULL(discovery.format.ref_storage_payload);
2137 discovery.format.ref_storage_format =
2138 ref_storage_format_by_uri(ref_backend_uri,
2139 &discovery.format.ref_storage_payload);
2140 if (discovery.format.ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
2141 die(_("unknown ref storage format: '%s'"), ref_backend_uri);
2142 }
2143
2144 /*
2145 * The GIT_OBJECT_STORAGE_FORMAT env variable
2146 * should override the repository config for
2147 * 'extensions.objectStorage'.
2148 */
2149 object_storage_uri = getenv(GIT_OBJECT_STORAGE_FORMAT_ENVIRONMENT);
2150 if (object_storage_uri) {
2151 FREE_AND_NULL(discovery.format.object_storage_payload);
2152 discovery.format.object_storage_format =
2153 object_storage_format_by_uri(object_storage_uri,
2154 &discovery.format.object_storage_payload);
2155 if (discovery.format.object_storage_format == OBJECT_STORAGE_FORMAT_UNKNOWN)
2156 die(_("unknown object storage format: '%s'"), object_storage_uri);
2157 }
2158
2159 if (apply_repository_format(repo, &discovery.format,
2160 APPLY_REPOSITORY_FORMAT_HONOR_ENV, &err) < 0)
2161 die("%s", err.buf);
2162 repo->objects = odb_new(repo, ODB_NEW_HONOR_ENV);
2163
2164 clear_repository_format(&discovery.format);
2165 strbuf_release(&err);
2166 }
2167 }
2168 /*
2169 * Since precompose_string_if_needed() needs to look at
2170 * the core.precomposeunicode configuration, this
2171 * has to happen after the above block that finds
2172 * out where the repository is, i.e. a preparation
2173 * for calling repo_config_get_bool().
2174 */
2175 if (discovery.prefix) {
2176 const char *prefix = precompose_string_if_needed(discovery.prefix);
2177 repo->prefix = xstrdup(prefix);
2178 setenv(GIT_PREFIX_ENVIRONMENT, repo->prefix, 1);
2179 } else {
2180 FREE_AND_NULL(repo->prefix);
2181 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
2182 }
2183
2184 setup_original_cwd(repo);
2185
2186 repo_discovery_release(&discovery);
2187 return repo->prefix;
2188}
2189
2190int git_config_perm(const char *var, const char *value)
2191{
2192 int i;
2193 char *endptr;
2194
2195 if (!value)
2196 return PERM_GROUP;
2197
2198 if (!strcmp(value, "umask"))
2199 return PERM_UMASK;
2200 if (!strcmp(value, "group"))
2201 return PERM_GROUP;
2202 if (!strcmp(value, "all") ||
2203 !strcmp(value, "world") ||
2204 !strcmp(value, "everybody"))
2205 return PERM_EVERYBODY;
2206
2207 /* Parse octal numbers */
2208 i = strtol(value, &endptr, 8);
2209
2210 /* If not an octal number, maybe true/false? */
2211 if (*endptr != 0)
2212 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
2213
2214 /*
2215 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
2216 * a chmod value to restrict to.
2217 */
2218 switch (i) {
2219 case PERM_UMASK: /* 0 */
2220 return PERM_UMASK;
2221 case OLD_PERM_GROUP: /* 1 */
2222 return PERM_GROUP;
2223 case OLD_PERM_EVERYBODY: /* 2 */
2224 return PERM_EVERYBODY;
2225 }
2226
2227 /* A filemode value was given: 0xxx */
2228
2229 if ((i & 0600) != 0600)
2230 die(_("problem with core.sharedRepository filemode value "
2231 "(0%.3o).\nThe owner of files must always have "
2232 "read and write permissions."), i);
2233
2234 /*
2235 * Mask filemode value. Others can not get write permission.
2236 * x flags for directories are handled separately.
2237 */
2238 return -(i & 0666);
2239}
2240
2241/*
2242 * Returns the "prefix", a path to the current working directory
2243 * relative to the work tree root, or NULL, if the current working
2244 * directory is not a strict subdirectory of the work tree root. The
2245 * prefix always ends with a '/' character.
2246 */
2247const char *setup_git_directory(struct repository *repo)
2248{
2249 return setup_git_directory_gently(repo, NULL);
2250}
2251
2252const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
2253{
2254 if (is_git_directory(suspect))
2255 return suspect;
2256 return read_gitfile_gently(suspect, return_error_code);
2257}
2258
2259/* if any standard file descriptor is missing open it to /dev/null */
2260void sanitize_stdfds(void)
2261{
2262 int fd = xopen("/dev/null", O_RDWR);
2263 while (fd < 2)
2264 fd = xdup(fd);
2265 if (fd > 2)
2266 close(fd);
2267}
2268
2269int daemonize(void)
2270{
2271#ifdef NO_POSIX_GOODIES
2272 errno = ENOSYS;
2273 return -1;
2274#else
2275 pid_t parent_pid = getpid();
2276 pid_t child_pid = fork();
2277
2278 switch (child_pid) {
2279 case 0:
2280 /*
2281 * We're in the child process, so we take ownership of
2282 * all tempfiles.
2283 */
2284 reassign_tempfile_ownership(parent_pid, getpid());
2285 break;
2286 case -1:
2287 die_errno(_("fork failed"));
2288 default:
2289 /*
2290 * We're in the parent process, so we drop ownership of
2291 * all tempfiles to prevent us from removing them upon
2292 * exit.
2293 */
2294 reassign_tempfile_ownership(parent_pid, child_pid);
2295 exit(0);
2296 }
2297 if (setsid() == -1)
2298 die_errno(_("setsid failed"));
2299 close(0);
2300 close(1);
2301 close(2);
2302 sanitize_stdfds();
2303 return 0;
2304#endif
2305}
2306
2307struct template_dir_cb_data {
2308 char *path;
2309 int initialized;
2310};
2311
2312static int template_dir_cb(const char *key, const char *value,
2313 const struct config_context *ctx UNUSED, void *d)
2314{
2315 struct template_dir_cb_data *data = d;
2316
2317 if (strcmp(key, "init.templatedir"))
2318 return 0;
2319
2320 if (!value) {
2321 data->path = NULL;
2322 } else {
2323 char *path = NULL;
2324
2325 FREE_AND_NULL(data->path);
2326 if (!git_config_pathname(&path, key, value))
2327 data->path = path ? path : xstrdup(value);
2328 }
2329
2330 return 0;
2331}
2332
2333const char *get_template_dir(const char *option_template)
2334{
2335 const char *template_dir = option_template;
2336
2337 if (!template_dir)
2338 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
2339 if (!template_dir) {
2340 static struct template_dir_cb_data data;
2341
2342 if (!data.initialized) {
2343 git_protected_config(template_dir_cb, &data);
2344 data.initialized = 1;
2345 }
2346 template_dir = data.path;
2347 }
2348 if (!template_dir) {
2349 static char *dir;
2350
2351 if (!dir)
2352 dir = system_path(DEFAULT_GIT_TEMPLATE_DIR);
2353 template_dir = dir;
2354 }
2355 return template_dir;
2356}
2357
2358#ifdef NO_TRUSTABLE_FILEMODE
2359#define TEST_FILEMODE 0
2360#else
2361#define TEST_FILEMODE 1
2362#endif
2363
2364#define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
2365
2366static void copy_templates_1(struct repository *repo,
2367 struct strbuf *path,
2368 struct strbuf *template_path,
2369 DIR *dir)
2370{
2371 size_t path_baselen = path->len;
2372 size_t template_baselen = template_path->len;
2373 struct dirent *de;
2374
2375 /* Note: if ".git/hooks" file exists in the repository being
2376 * re-initialized, /etc/core-git/templates/hooks/update would
2377 * cause "git init" to fail here. I think this is sane but
2378 * it means that the set of templates we ship by default, along
2379 * with the way the namespace under .git/ is organized, should
2380 * be really carefully chosen.
2381 */
2382 safe_create_dir(repo, path->buf, 1);
2383 while ((de = readdir(dir)) != NULL) {
2384 struct stat st_git, st_template;
2385 int exists = 0;
2386
2387 strbuf_setlen(path, path_baselen);
2388 strbuf_setlen(template_path, template_baselen);
2389
2390 if (de->d_name[0] == '.')
2391 continue;
2392 strbuf_addstr(path, de->d_name);
2393 strbuf_addstr(template_path, de->d_name);
2394 if (lstat(path->buf, &st_git)) {
2395 if (errno != ENOENT)
2396 die_errno(_("cannot stat '%s'"), path->buf);
2397 }
2398 else
2399 exists = 1;
2400
2401 if (lstat(template_path->buf, &st_template))
2402 die_errno(_("cannot stat template '%s'"), template_path->buf);
2403
2404 if (S_ISDIR(st_template.st_mode)) {
2405 DIR *subdir = opendir(template_path->buf);
2406 if (!subdir)
2407 die_errno(_("cannot opendir '%s'"), template_path->buf);
2408 strbuf_addch(path, '/');
2409 strbuf_addch(template_path, '/');
2410 copy_templates_1(repo, path, template_path, subdir);
2411 closedir(subdir);
2412 }
2413 else if (exists)
2414 continue;
2415 else if (S_ISLNK(st_template.st_mode)) {
2416 struct strbuf lnk = STRBUF_INIT;
2417 if (strbuf_readlink(&lnk, template_path->buf,
2418 st_template.st_size) < 0)
2419 die_errno(_("cannot readlink '%s'"), template_path->buf);
2420 if (symlink(lnk.buf, path->buf))
2421 die_errno(_("cannot symlink '%s' '%s'"),
2422 lnk.buf, path->buf);
2423 strbuf_release(&lnk);
2424 }
2425 else if (S_ISREG(st_template.st_mode)) {
2426 if (copy_file(repo, path->buf, template_path->buf, st_template.st_mode))
2427 die_errno(_("cannot copy '%s' to '%s'"),
2428 template_path->buf, path->buf);
2429 }
2430 else
2431 error(_("ignoring template %s"), template_path->buf);
2432 }
2433}
2434
2435static void copy_templates(struct repository *repo, const char *option_template)
2436{
2437 const char *template_dir = get_template_dir(option_template);
2438 struct strbuf path = STRBUF_INIT;
2439 struct strbuf template_path = STRBUF_INIT;
2440 size_t template_len;
2441 struct repository_format template_format = REPOSITORY_FORMAT_INIT;
2442 struct strbuf err = STRBUF_INIT;
2443 DIR *dir;
2444 char *to_free = NULL;
2445
2446 if (!template_dir || !*template_dir)
2447 return;
2448
2449 strbuf_addstr(&template_path, template_dir);
2450 strbuf_complete(&template_path, '/');
2451 template_len = template_path.len;
2452
2453 dir = opendir(template_path.buf);
2454 if (!dir) {
2455 warning(_("templates not found in %s"), template_dir);
2456 goto free_return;
2457 }
2458
2459 /* Make sure that template is from the correct vintage */
2460 strbuf_addstr(&template_path, "config");
2461 read_repository_format(&template_format, template_path.buf);
2462 strbuf_setlen(&template_path, template_len);
2463
2464 /*
2465 * No mention of version at all is OK, but anything else should be
2466 * verified.
2467 */
2468 if (template_format.version >= 0 &&
2469 verify_repository_format(&template_format, &err) < 0) {
2470 warning(_("not copying templates from '%s': %s"),
2471 template_dir, err.buf);
2472 strbuf_release(&err);
2473 goto close_free_return;
2474 }
2475
2476 strbuf_addstr(&path, repo_get_common_dir(repo));
2477 strbuf_complete(&path, '/');
2478 copy_templates_1(repo, &path, &template_path, dir);
2479close_free_return:
2480 closedir(dir);
2481free_return:
2482 free(to_free);
2483 strbuf_release(&path);
2484 strbuf_release(&template_path);
2485 clear_repository_format(&template_format);
2486}
2487
2488/*
2489 * If the git_dir is not directly inside the working tree, then git will not
2490 * find it by default, and we need to set the worktree explicitly.
2491 */
2492static int needs_work_tree_config(const char *git_dir, const char *work_tree)
2493{
2494 if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
2495 return 0;
2496 if (skip_prefix(git_dir, work_tree, &git_dir) &&
2497 !strcmp(git_dir, "/.git"))
2498 return 0;
2499 return 1;
2500}
2501
2502void initialize_repository_version(struct repository *repo,
2503 int hash_algo,
2504 enum ref_storage_format ref_storage_format,
2505 enum object_storage_format object_storage_format,
2506 int reinit)
2507{
2508 struct strbuf repo_version = STRBUF_INIT;
2509 int target_version = GIT_REPO_VERSION;
2510 int default_submodule_path_config = 0;
2511
2512 /*
2513 * Note that we initialize the repository version to 1 when the ref
2514 * storage format is unknown. This is on purpose so that we can add the
2515 * correct object format to the config during git-clone(1). The format
2516 * version will get adjusted by git-clone(1) once it has learned about
2517 * the remote repository's format.
2518 */
2519 if (hash_algo != GIT_HASH_SHA1_LEGACY ||
2520 ref_storage_format != REF_STORAGE_FORMAT_FILES ||
2521 repo->ref_storage_payload ||
2522 object_storage_format != OBJECT_STORAGE_FORMAT_FILES ||
2523 repo->object_storage_payload)
2524 target_version = GIT_REPO_VERSION_READ;
2525
2526 if (hash_algo != GIT_HASH_SHA1_LEGACY && hash_algo != GIT_HASH_UNKNOWN)
2527 repo_config_set(repo, "extensions.objectformat",
2528 hash_algos[hash_algo].name);
2529 else if (reinit)
2530 repo_config_set_gently(repo, "extensions.objectformat", NULL);
2531
2532 if (repo->ref_storage_payload) {
2533 struct strbuf ref_uri = STRBUF_INIT;
2534
2535 strbuf_addf(&ref_uri, "%s://%s",
2536 ref_storage_format_to_name(ref_storage_format),
2537 repo->ref_storage_payload);
2538 repo_config_set(repo, "extensions.refstorage", ref_uri.buf);
2539 strbuf_release(&ref_uri);
2540 } else if (ref_storage_format != REF_STORAGE_FORMAT_FILES) {
2541 repo_config_set(repo, "extensions.refstorage",
2542 ref_storage_format_to_name(ref_storage_format));
2543 } else if (reinit) {
2544 repo_config_set_gently(repo, "extensions.refstorage", NULL);
2545 }
2546
2547 if (repo->object_storage_payload) {
2548 struct strbuf uri = STRBUF_INIT;
2549
2550 strbuf_addf(&uri, "%s://%s",
2551 object_storage_format_to_name(object_storage_format),
2552 repo->object_storage_payload);
2553 repo_config_set(repo, "extensions.objectstorage", uri.buf);
2554
2555 strbuf_release(&uri);
2556 } else if (object_storage_format != OBJECT_STORAGE_FORMAT_FILES) {
2557 repo_config_set(repo, "extensions.objectstorage",
2558 object_storage_format_to_name(object_storage_format));
2559 } else if (reinit) {
2560 repo_config_set_gently(repo, "extensions.objectstorage", NULL);
2561 }
2562
2563 if (reinit) {
2564 struct strbuf config = STRBUF_INIT;
2565 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
2566
2567 repo_common_path_append(repo, &config, "config");
2568 read_repository_format(&repo_fmt, config.buf);
2569
2570 if (repo_fmt.v1_only_extensions.nr)
2571 target_version = GIT_REPO_VERSION_READ;
2572
2573 strbuf_release(&config);
2574 clear_repository_format(&repo_fmt);
2575 }
2576
2577 repo_config_get_bool(repo, "init.defaultSubmodulePathConfig",
2578 &default_submodule_path_config);
2579 if (default_submodule_path_config) {
2580 /* extensions.submodulepathconfig requires at least version 1 */
2581 if (target_version == 0)
2582 target_version = 1;
2583 repo_config_set(repo, "extensions.submodulepathconfig", "true");
2584 }
2585
2586 strbuf_addf(&repo_version, "%d", target_version);
2587 repo_config_set(repo, "core.repositoryformatversion", repo_version.buf);
2588
2589 strbuf_release(&repo_version);
2590}
2591
2592static int is_reinit(struct repository *repo)
2593{
2594 struct strbuf buf = STRBUF_INIT;
2595 char junk[2];
2596 int ret;
2597
2598 repo_git_path_replace(repo, &buf, "HEAD");
2599 ret = !access(buf.buf, R_OK) || readlink(buf.buf, junk, sizeof(junk) - 1) != -1;
2600 strbuf_release(&buf);
2601 return ret;
2602}
2603
2604void create_reference_database(struct repository *repo,
2605 const char *initial_branch, int quiet)
2606{
2607 struct strbuf err = STRBUF_INIT;
2608 char *to_free = NULL;
2609 int reinit = is_reinit(repo);
2610
2611 if (ref_store_create_on_disk(get_main_ref_store(repo), 0, &err))
2612 die("failed to set up refs db: %s", err.buf);
2613
2614 /*
2615 * Point the HEAD symref to the initial branch with if HEAD does
2616 * not yet exist.
2617 */
2618 if (!reinit) {
2619 char *ref;
2620
2621 if (!initial_branch)
2622 initial_branch = to_free =
2623 repo_default_branch_name(repo, quiet);
2624
2625 ref = xstrfmt("refs/heads/%s", initial_branch);
2626 if (check_refname_format(ref, 0) < 0)
2627 die(_("invalid initial branch name: '%s'"),
2628 initial_branch);
2629
2630 if (refs_update_symref(get_main_ref_store(repo), "HEAD", ref, NULL) < 0)
2631 exit(1);
2632 free(ref);
2633 }
2634
2635 if (reinit && initial_branch)
2636 warning(_("re-init: ignored --initial-branch=%s"),
2637 initial_branch);
2638
2639 strbuf_release(&err);
2640 free(to_free);
2641}
2642
2643static int create_default_files(struct repository *repo,
2644 const char *template_path,
2645 const char *original_git_dir,
2646 const struct repository_format *fmt,
2647 int init_shared_repository)
2648{
2649 struct stat st1;
2650 struct strbuf path = STRBUF_INIT;
2651 int reinit;
2652 int filemode;
2653 const char *work_tree = repo_get_work_tree(repo);
2654
2655 /*
2656 * First copy the templates -- we might have the default
2657 * config file there, in which case we would want to read
2658 * from it after installing.
2659 *
2660 * Before reading that config, we also need to clear out any cached
2661 * values (since we've just potentially changed what's available on
2662 * disk).
2663 */
2664 copy_templates(repo, template_path);
2665 repo_config_clear(repo);
2666 repo_settings_reset_shared_repository(repo);
2667 repo_config(repo, git_default_config, NULL);
2668
2669 reinit = is_reinit(repo);
2670
2671 /*
2672 * We must make sure command-line options continue to override any
2673 * values we might have just re-read from the config.
2674 */
2675 if (init_shared_repository != -1)
2676 repo_settings_set_shared_repository(repo,
2677 init_shared_repository);
2678
2679 repo->bare_cfg = !work_tree;
2680
2681 /*
2682 * We would have created the above under user's umask -- under
2683 * shared-repository settings, we would need to fix them up.
2684 */
2685 if (repo_settings_get_shared_repository(repo)) {
2686 adjust_shared_perm(repo, repo_get_git_dir(repo));
2687 }
2688
2689 initialize_repository_version(repo, fmt->hash_algo, fmt->ref_storage_format,
2690 fmt->object_storage_format, reinit);
2691
2692 /* Check filemode trustability */
2693 repo_git_path_replace(repo, &path, "config");
2694 filemode = TEST_FILEMODE;
2695 if (TEST_FILEMODE && !lstat(path.buf, &st1)) {
2696 struct stat st2;
2697 filemode = (!chmod(path.buf, st1.st_mode ^ S_IXUSR) &&
2698 !lstat(path.buf, &st2) &&
2699 st1.st_mode != st2.st_mode &&
2700 !chmod(path.buf, st1.st_mode));
2701 if (filemode && !reinit && (st1.st_mode & S_IXUSR))
2702 filemode = 0;
2703 }
2704 repo_config_set(repo, "core.filemode", filemode ? "true" : "false");
2705
2706 if (is_bare_repository(repo))
2707 repo_config_set(repo, "core.bare", "true");
2708 else {
2709 const char *value;
2710
2711 repo_config_set(repo, "core.bare", "false");
2712
2713 /* allow template config file to override the default */
2714 if (repo_config_get_string_tmp(repo, "core.logallrefupdates", &value))
2715 repo_config_set(repo, "core.logallrefupdates", "true");
2716
2717 if (needs_work_tree_config(original_git_dir, work_tree))
2718 repo_config_set(repo, "core.worktree", work_tree);
2719 }
2720
2721 if (!reinit) {
2722 /* Check if symlink is supported in the work tree */
2723 repo_git_path_replace(repo, &path, "tXXXXXX");
2724 if (!close(xmkstemp(path.buf)) &&
2725 !unlink(path.buf) &&
2726 !symlink("testing", path.buf) &&
2727 !lstat(path.buf, &st1) &&
2728 S_ISLNK(st1.st_mode))
2729 unlink(path.buf); /* good */
2730 else
2731 repo_config_set(repo, "core.symlinks", "false");
2732
2733 /* Check if the filesystem is case-insensitive */
2734 repo_git_path_replace(repo, &path, "CoNfIg");
2735 if (!access(path.buf, F_OK))
2736 repo_config_set(repo, "core.ignorecase", "true");
2737 probe_utf8_pathname_composition();
2738 }
2739
2740 strbuf_release(&path);
2741 return reinit;
2742}
2743
2744void create_object_database(struct repository *repo,
2745 const struct strvec *alternates)
2746{
2747 struct odb_create_on_disk_options opts = {
2748 .alternates = alternates,
2749 };
2750
2751 /*
2752 * Create the "objects" directory in the common directory. This is done
2753 * so that the repository can be discovered regardless of the backend
2754 * used.
2755 *
2756 * Note that we only do this in case the object directory wasn't
2757 * overwritten via an environment variable. If it _is_ being overridden
2758 * then we skip this step, as the repository won't be discoverable
2759 * anyway without the environment variable.
2760 */
2761 if (!getenv(DB_ENVIRONMENT)) {
2762 struct strbuf objects_dir = STRBUF_INIT;
2763 repo_common_path_append(repo, &objects_dir, "objects");
2764 safe_create_dir(repo, objects_dir.buf, 1);
2765 strbuf_release(&objects_dir);
2766 }
2767
2768 repo->objects = odb_new(repo, ODB_NEW_HONOR_ENV);
2769
2770 if (odb_source_create_on_disk(repo->objects->source, &opts) < 0)
2771 die(_("failed creating object database"));
2772}
2773
2774static void separate_git_dir(struct repository *repo,
2775 const char *git_dir, const char *git_link)
2776{
2777 struct stat st;
2778
2779 if (!stat(git_link, &st)) {
2780 const char *src;
2781
2782 if (S_ISREG(st.st_mode))
2783 src = read_gitfile(git_link);
2784 else if (S_ISDIR(st.st_mode))
2785 src = git_link;
2786 else
2787 die(_("unable to handle file type %d"), (int)st.st_mode);
2788
2789 if (rename(src, git_dir))
2790 die_errno(_("unable to move %s to %s"), src, git_dir);
2791 repair_worktrees_after_gitdir_move(repo, src);
2792 }
2793
2794 write_file(git_link, "gitdir: %s", git_dir);
2795}
2796
2797struct default_format_config {
2798 int hash;
2799 enum ref_storage_format ref_storage_format;
2800 enum object_storage_format object_storage_format;
2801};
2802
2803static int read_default_format_config(const char *key, const char *value,
2804 const struct config_context *ctx UNUSED,
2805 void *payload)
2806{
2807 struct default_format_config *cfg = payload;
2808 char *str = NULL;
2809 int ret;
2810
2811 if (!strcmp(key, "init.defaultobjectformat")) {
2812 ret = git_config_string(&str, key, value);
2813 if (ret)
2814 goto out;
2815 cfg->hash = hash_algo_by_name(str);
2816 if (cfg->hash == GIT_HASH_UNKNOWN)
2817 warning(_("unknown hash algorithm '%s'"), str);
2818 goto out;
2819 }
2820
2821 if (!strcmp(key, "init.defaultrefstorageformat") ||
2822 !strcmp(key, "init.defaultrefformat")) {
2823 ret = git_config_string(&str, key, value);
2824 if (ret)
2825 goto out;
2826 cfg->ref_storage_format = ref_storage_format_by_name(str);
2827 if (cfg->ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
2828 warning(_("unknown ref storage format '%s'"), str);
2829 goto out;
2830 }
2831
2832 if (!strcmp(key, "init.defaultobjectstorageformat")) {
2833 ret = git_config_string(&str, key, value);
2834 if (ret)
2835 goto out;
2836 cfg->object_storage_format = object_storage_format_by_name(str);
2837 if (cfg->object_storage_format == OBJECT_STORAGE_FORMAT_UNKNOWN)
2838 warning(_("unknown object storage format '%s'"), str);
2839 goto out;
2840 }
2841
2842 /*
2843 * Enable the reftable format when "features.experimental" is enabled.
2844 * "init.defaultRefStorageFormat" takes precedence over this setting.
2845 */
2846 if (!strcmp(key, "feature.experimental") &&
2847 cfg->ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN &&
2848 git_config_bool(key, value)) {
2849 cfg->ref_storage_format = REF_STORAGE_FORMAT_REFTABLE;
2850 ret = 0;
2851 goto out;
2852 }
2853
2854 ret = 0;
2855out:
2856 free(str);
2857 return ret;
2858}
2859
2860static void repository_format_configure(struct repository_format *repo_fmt,
2861 int hash,
2862 const char *ref_storage_format_uri,
2863 const char *object_storage_uri)
2864{
2865 struct default_format_config cfg = {
2866 .hash = GIT_HASH_UNKNOWN,
2867 .ref_storage_format = REF_STORAGE_FORMAT_UNKNOWN,
2868 };
2869 struct config_options opts = {
2870 .respect_includes = 1,
2871 .ignore_repo = 1,
2872 .ignore_worktree = 1,
2873 };
2874 enum object_storage_format object_storage_format;
2875 enum ref_storage_format ref_storage_format;
2876 char *object_storage_payload = NULL;
2877 char *ref_storage_payload = NULL;
2878 const char *env;
2879
2880 config_with_options(read_default_format_config, &cfg, NULL, NULL, &opts);
2881
2882 /*
2883 * If we already have an initialized repo, don't allow the user to
2884 * specify a different algorithm, as that could cause corruption.
2885 * Otherwise, if the user has specified one on the command line, use it.
2886 */
2887 env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT);
2888 if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo)
2889 die(_("attempt to reinitialize repository with different hash"));
2890 else if (hash != GIT_HASH_UNKNOWN)
2891 repo_fmt->hash_algo = hash;
2892 else if (env) {
2893 int env_algo = hash_algo_by_name(env);
2894 if (env_algo == GIT_HASH_UNKNOWN)
2895 die(_("unknown hash algorithm '%s'"), env);
2896 if (repo_fmt->version < 0 ||
2897 repo_fmt->hash_algo == GIT_HASH_UNKNOWN)
2898 repo_fmt->hash_algo = env_algo;
2899 } else if (cfg.hash != GIT_HASH_UNKNOWN) {
2900 repo_fmt->hash_algo = cfg.hash;
2901 }
2902
2903 /*
2904 * We have the following order of preference when configuring the ref
2905 * storage format:
2906 *
2907 * 1. Explicit override via the command line, like in `git init
2908 * --ref-storage-format=`.
2909 *
2910 * 2. Explicit override via the environment with
2911 * "GIT_REF_STORAGE_FORMAT".
2912 *
2913 * 3. Its deprecated equivalent "GIT_REFERENCE_BACKEND".
2914 *
2915 * 4. Existing repository format. All the subsequent sources only
2916 * kick in when there is no repository yet.
2917 *
2918 * 4. The default ref storage format for new repositories as
2919 * configured via "GIT_DEFAULT_REF_STORAGE_FORMAT".
2920 *
2921 * 5. Its deprecated equivalent "GIT_DEFAULT_REF_FORMAT".
2922 *
2923 * 6. The default ref storage format for new repositories as
2924 * configured via "init.defaultRefStorageFormat" or its deprecated
2925 * equivalent "init.defaultRefFormat".
2926 *
2927 * 7. Otherwise, we fall back to the default ref storage format
2928 * compiled into Git.
2929 */
2930 if (ref_storage_format_uri) {
2931 ref_storage_format = ref_storage_format_by_uri(ref_storage_format_uri,
2932 &ref_storage_payload);
2933 if (ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
2934 die(_("unknown ref storage format specified via command line: '%s'"),
2935 ref_storage_format_uri);
2936 } else if ((env = getenv(GIT_REF_STORAGE_FORMAT_ENVIRONMENT))) {
2937 ref_storage_format = ref_storage_format_by_uri(env, &ref_storage_payload);
2938 if (ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
2939 die(_("unknown ref storage format specified via %s: '%s'"),
2940 GIT_REF_STORAGE_FORMAT_ENVIRONMENT, env);
2941 } else if ((env = getenv(GIT_REFERENCE_BACKEND_ENVIRONMENT))) {
2942 ref_storage_format = ref_storage_format_by_uri(env, &ref_storage_payload);
2943 if (ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
2944 die(_("unknown ref storage format specified via %s: '%s'"),
2945 GIT_REFERENCE_BACKEND_ENVIRONMENT, env);
2946 } else if (repo_fmt->version >= 0) {
2947 ref_storage_format = repo_fmt->ref_storage_format;
2948 ref_storage_payload = xstrdup_or_null(repo_fmt->ref_storage_payload);
2949 } else if ((env = getenv("GIT_DEFAULT_REF_STORAGE_FORMAT"))) {
2950 ref_storage_format = ref_storage_format_by_name(env);
2951 if (ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
2952 die(_("unknown ref storage format specified via %s: '%s'"),
2953 "GIT_DEFAULT_REF_STORAGE_FORMAT", env);
2954 } else if ((env = getenv("GIT_DEFAULT_REF_FORMAT"))) {
2955 ref_storage_format = ref_storage_format_by_name(env);
2956 if (ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
2957 die(_("unknown ref storage format specified via %s: '%s'"),
2958 "GIT_DEFAULT_REF_FORMAT", env);
2959 } else if (cfg.ref_storage_format != REF_STORAGE_FORMAT_UNKNOWN) {
2960 ref_storage_format = cfg.ref_storage_format;
2961 } else {
2962 ref_storage_format = REF_STORAGE_FORMAT_DEFAULT;
2963 }
2964
2965 /*
2966 * Determine the object storage format, with the same precedence as
2967 * for the ref storage format:
2968 *
2969 * 1. The format specified via the command line.
2970 *
2971 * 2. The format specified via "GIT_OBJECT_STORAGE_FORMAT".
2972 *
2973 * 3. The format of a preexisting repository when reinitializing.
2974 *
2975 * 4. The default format for new repositories as configured via
2976 * "GIT_DEFAULT_OBJECT_STORAGE_FORMAT".
2977 *
2978 * 5. The default format for new repositories as configured via
2979 * "init.defaultObjectStorageFormat".
2980 *
2981 * 6. The "files" format.
2982 */
2983 if (object_storage_uri) {
2984 object_storage_format = object_storage_format_by_uri(object_storage_uri,
2985 &object_storage_payload);
2986 if (object_storage_format == OBJECT_STORAGE_FORMAT_UNKNOWN)
2987 die(_("unknown object storage format specified via command line: '%s'"),
2988 object_storage_uri);
2989 } else if ((env = getenv(GIT_OBJECT_STORAGE_FORMAT_ENVIRONMENT))) {
2990 object_storage_format = object_storage_format_by_uri(env, &object_storage_payload);
2991 if (object_storage_format == OBJECT_STORAGE_FORMAT_UNKNOWN)
2992 die(_("unknown object storage format specified via %s: '%s'"),
2993 GIT_OBJECT_STORAGE_FORMAT_ENVIRONMENT, env);
2994 } else if (repo_fmt->version >= 0) {
2995 object_storage_format = repo_fmt->object_storage_format;
2996 object_storage_payload = xstrdup_or_null(repo_fmt->object_storage_payload);
2997 } else if ((env = getenv("GIT_DEFAULT_OBJECT_STORAGE_FORMAT"))) {
2998 object_storage_format = object_storage_format_by_name(env);
2999 if (object_storage_format == OBJECT_STORAGE_FORMAT_UNKNOWN)
3000 die(_("unknown object storage format specified via %s: '%s'"),
3001 "GIT_DEFAULT_OBJECT_STORAGE_FORMAT", env);
3002 } else if (cfg.object_storage_format != OBJECT_STORAGE_FORMAT_UNKNOWN) {
3003 object_storage_format = cfg.object_storage_format;
3004 } else {
3005 object_storage_format = OBJECT_STORAGE_FORMAT_FILES;
3006 }
3007
3008 /*
3009 * If we have a preexisting repository we need to verify that its
3010 * current storage formats do not change.
3011 */
3012 if (repo_fmt->version >= 0) {
3013 if (ref_storage_format != repo_fmt->ref_storage_format)
3014 die(_("attempt to reinitialize repository with different reference storage format"));
3015 if ((ref_storage_payload || repo_fmt->ref_storage_payload) &&
3016 strcmp(ref_storage_payload ? ref_storage_payload : "",
3017 repo_fmt->ref_storage_payload ? repo_fmt->ref_storage_payload : ""))
3018 die(_("attempt to reinitialize repository with different reference storage payload"));
3019 if (object_storage_format != repo_fmt->object_storage_format)
3020 die(_("attempt to reinitialize repository with different object storage format"));
3021 if ((object_storage_payload || repo_fmt->object_storage_payload) &&
3022 strcmp(object_storage_payload ? object_storage_payload : "",
3023 repo_fmt->object_storage_payload ? repo_fmt->object_storage_payload : ""))
3024 die(_("attempt to reinitialize repository with different object storage payload"));
3025 }
3026
3027 free(repo_fmt->ref_storage_payload);
3028 repo_fmt->ref_storage_format = ref_storage_format;
3029 repo_fmt->ref_storage_payload = ref_storage_payload;
3030
3031 free(repo_fmt->object_storage_payload);
3032 repo_fmt->object_storage_format = object_storage_format;
3033 repo_fmt->object_storage_payload = object_storage_payload;
3034}
3035
3036void create_repository(struct repository *repo,
3037 const char *git_dir,
3038 const char *real_git_dir,
3039 const char *worktree,
3040 const char *template_dir,
3041 int hash,
3042 const char *ref_storage_format_uri,
3043 const char *object_storage_format_uri,
3044 int init_shared_repository,
3045 int *reinit_ok)
3046{
3047 int reinit_ignored;
3048 char *original_git_dir = real_pathdup(git_dir, 1);
3049 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
3050 struct strbuf err = STRBUF_INIT;
3051
3052 repo_clear(repo);
3053 initialize_repository(repo);
3054
3055 if (real_git_dir) {
3056 struct stat st;
3057
3058 if (!reinit_ok && !stat(git_dir, &st))
3059 die(_("%s already exists"), git_dir);
3060
3061 if (!reinit_ok && !stat(real_git_dir, &st))
3062 die(_("%s already exists"), real_git_dir);
3063
3064 apply_and_export_relative_gitdir(repo, real_git_dir, 1);
3065 git_dir = repo_get_git_dir(repo);
3066 separate_git_dir(repo, git_dir, original_git_dir);
3067 } else {
3068 apply_and_export_relative_gitdir(repo, git_dir, 1);
3069 git_dir = repo_get_git_dir(repo);
3070 }
3071
3072 if (worktree)
3073 set_git_work_tree(repo, worktree);
3074
3075 /*
3076 * Check to see if the repository version is right.
3077 * Note that a newly created repository does not have
3078 * config file, so this will not fail. What we are catching
3079 * is an attempt to reinitialize new repository with an old tool.
3080 */
3081 read_and_verify_repository_format(&repo_fmt, repo_get_git_dir(repo), NULL);
3082 repository_format_configure(&repo_fmt, hash, ref_storage_format_uri, object_storage_format_uri);
3083 if (apply_repository_format(repo, &repo_fmt, APPLY_REPOSITORY_FORMAT_HONOR_ENV, &err) < 0)
3084 die("%s", err.buf);
3085
3086 /*
3087 * Ensure `core.hidedotfiles` is processed. This must happen after we
3088 * have set up the repository format such that we can evaluate
3089 * includeIf conditions correctly in the case of re-initialization.
3090 */
3091 repo_config(repo, git_default_core_config, NULL);
3092
3093 if (init_shared_repository != -1)
3094 repo_settings_set_shared_repository(repo, init_shared_repository);
3095
3096 safe_create_dir(repo, git_dir, 0);
3097
3098 if (!reinit_ok)
3099 reinit_ok = &reinit_ignored;
3100 *reinit_ok = create_default_files(repo, template_dir, original_git_dir,
3101 &repo_fmt, init_shared_repository);
3102
3103 if (repo_settings_get_shared_repository(repo)) {
3104 char buf[10];
3105 /* We do not spell "group" and such, so that
3106 * the configuration can be read by older version
3107 * of git. Note, we use octal numbers for new share modes,
3108 * and compatibility values for PERM_GROUP and
3109 * PERM_EVERYBODY.
3110 */
3111 if (repo_settings_get_shared_repository(repo) < 0)
3112 /* force to the mode value */
3113 xsnprintf(buf, sizeof(buf), "0%o", -repo_settings_get_shared_repository(repo));
3114 else if (repo_settings_get_shared_repository(repo) == PERM_GROUP)
3115 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
3116 else if (repo_settings_get_shared_repository(repo) == PERM_EVERYBODY)
3117 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
3118 else
3119 BUG("invalid value for shared_repository");
3120 repo_config_set(repo, "core.sharedrepository", buf);
3121 repo_config_set(repo, "receive.denyNonFastforwards", "true");
3122 }
3123
3124 clear_repository_format(&repo_fmt);
3125 strbuf_release(&err);
3126 free(original_git_dir);
3127}