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