]> git.ipfire.org Git - thirdparty/git.git/blob - setup.c
use xstrncmpz()
[thirdparty/git.git] / setup.c
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "copy.h"
4 #include "environment.h"
5 #include "exec-cmd.h"
6 #include "gettext.h"
7 #include "object-name.h"
8 #include "refs.h"
9 #include "repository.h"
10 #include "config.h"
11 #include "dir.h"
12 #include "setup.h"
13 #include "string-list.h"
14 #include "chdir-notify.h"
15 #include "path.h"
16 #include "quote.h"
17 #include "trace2.h"
18 #include "worktree.h"
19
20 static int inside_git_dir = -1;
21 static int inside_work_tree = -1;
22 static int work_tree_config_is_bogus;
23 enum allowed_bare_repo {
24 ALLOWED_BARE_REPO_EXPLICIT = 0,
25 ALLOWED_BARE_REPO_ALL,
26 };
27
28 static struct startup_info the_startup_info;
29 struct startup_info *startup_info = &the_startup_info;
30 const char *tmp_original_cwd;
31
32 /*
33 * The input parameter must contain an absolute path, and it must already be
34 * normalized.
35 *
36 * Find the part of an absolute path that lies inside the work tree by
37 * dereferencing symlinks outside the work tree, for example:
38 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
39 * /dir/file (work tree is /) -> dir/file
40 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
41 * /dir/repolink/file (repolink points to /dir/repo) -> file
42 * /dir/repo (exactly equal to work tree) -> (empty string)
43 */
44 static int abspath_part_inside_repo(char *path)
45 {
46 size_t len;
47 size_t wtlen;
48 char *path0;
49 int off;
50 const char *work_tree = get_git_work_tree();
51 struct strbuf realpath = STRBUF_INIT;
52
53 if (!work_tree)
54 return -1;
55 wtlen = strlen(work_tree);
56 len = strlen(path);
57 off = offset_1st_component(path);
58
59 /* check if work tree is already the prefix */
60 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
61 if (path[wtlen] == '/') {
62 memmove(path, path + wtlen + 1, len - wtlen);
63 return 0;
64 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
65 /* work tree is the root, or the whole path */
66 memmove(path, path + wtlen, len - wtlen + 1);
67 return 0;
68 }
69 /* work tree might match beginning of a symlink to work tree */
70 off = wtlen;
71 }
72 path0 = path;
73 path += off;
74
75 /* check each '/'-terminated level */
76 while (*path) {
77 path++;
78 if (*path == '/') {
79 *path = '\0';
80 strbuf_realpath(&realpath, path0, 1);
81 if (fspathcmp(realpath.buf, work_tree) == 0) {
82 memmove(path0, path + 1, len - (path - path0));
83 strbuf_release(&realpath);
84 return 0;
85 }
86 *path = '/';
87 }
88 }
89
90 /* check whole path */
91 strbuf_realpath(&realpath, path0, 1);
92 if (fspathcmp(realpath.buf, work_tree) == 0) {
93 *path0 = '\0';
94 strbuf_release(&realpath);
95 return 0;
96 }
97
98 strbuf_release(&realpath);
99 return -1;
100 }
101
102 /*
103 * Normalize "path", prepending the "prefix" for relative paths. If
104 * remaining_prefix is not NULL, return the actual prefix still
105 * remains in the path. For example, prefix = sub1/sub2/ and path is
106 *
107 * foo -> sub1/sub2/foo (full prefix)
108 * ../foo -> sub1/foo (remaining prefix is sub1/)
109 * ../../bar -> bar (no remaining prefix)
110 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
111 * `pwd`/../bar -> sub1/bar (no remaining prefix)
112 */
113 char *prefix_path_gently(const char *prefix, int len,
114 int *remaining_prefix, const char *path)
115 {
116 const char *orig = path;
117 char *sanitized;
118 if (is_absolute_path(orig)) {
119 sanitized = xmallocz(strlen(path));
120 if (remaining_prefix)
121 *remaining_prefix = 0;
122 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
123 free(sanitized);
124 return NULL;
125 }
126 if (abspath_part_inside_repo(sanitized)) {
127 free(sanitized);
128 return NULL;
129 }
130 } else {
131 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
132 if (remaining_prefix)
133 *remaining_prefix = len;
134 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
135 free(sanitized);
136 return NULL;
137 }
138 }
139 return sanitized;
140 }
141
142 char *prefix_path(const char *prefix, int len, const char *path)
143 {
144 char *r = prefix_path_gently(prefix, len, NULL, path);
145 if (!r) {
146 const char *hint_path = get_git_work_tree();
147 if (!hint_path)
148 hint_path = get_git_dir();
149 die(_("'%s' is outside repository at '%s'"), path,
150 absolute_path(hint_path));
151 }
152 return r;
153 }
154
155 int path_inside_repo(const char *prefix, const char *path)
156 {
157 int len = prefix ? strlen(prefix) : 0;
158 char *r = prefix_path_gently(prefix, len, NULL, path);
159 if (r) {
160 free(r);
161 return 1;
162 }
163 return 0;
164 }
165
166 int check_filename(const char *prefix, const char *arg)
167 {
168 char *to_free = NULL;
169 struct stat st;
170
171 if (skip_prefix(arg, ":/", &arg)) {
172 if (!*arg) /* ":/" is root dir, always exists */
173 return 1;
174 prefix = NULL;
175 } else if (skip_prefix(arg, ":!", &arg) ||
176 skip_prefix(arg, ":^", &arg)) {
177 if (!*arg) /* excluding everything is silly, but allowed */
178 return 1;
179 }
180
181 if (prefix)
182 arg = to_free = prefix_filename(prefix, arg);
183
184 if (!lstat(arg, &st)) {
185 free(to_free);
186 return 1; /* file exists */
187 }
188 if (is_missing_file_error(errno)) {
189 free(to_free);
190 return 0; /* file does not exist */
191 }
192 die_errno(_("failed to stat '%s'"), arg);
193 }
194
195 static void NORETURN die_verify_filename(struct repository *r,
196 const char *prefix,
197 const char *arg,
198 int diagnose_misspelt_rev)
199 {
200 if (!diagnose_misspelt_rev)
201 die(_("%s: no such path in the working tree.\n"
202 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
203 arg);
204 /*
205 * Saying "'(icase)foo' does not exist in the index" when the
206 * user gave us ":(icase)foo" is just stupid. A magic pathspec
207 * begins with a colon and is followed by a non-alnum; do not
208 * let maybe_die_on_misspelt_object_name() even trigger.
209 */
210 if (!(arg[0] == ':' && !isalnum(arg[1])))
211 maybe_die_on_misspelt_object_name(r, arg, prefix);
212
213 /* ... or fall back the most general message. */
214 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
215 "Use '--' to separate paths from revisions, like this:\n"
216 "'git <command> [<revision>...] -- [<file>...]'"), arg);
217
218 }
219
220 /*
221 * Check for arguments that don't resolve as actual files,
222 * but which look sufficiently like pathspecs that we'll consider
223 * them such for the purposes of rev/pathspec DWIM parsing.
224 */
225 static int looks_like_pathspec(const char *arg)
226 {
227 const char *p;
228 int escaped = 0;
229
230 /*
231 * Wildcard characters imply the user is looking to match pathspecs
232 * that aren't in the filesystem. Note that this doesn't include
233 * backslash even though it's a glob special; by itself it doesn't
234 * cause any increase in the match. Likewise ignore backslash-escaped
235 * wildcard characters.
236 */
237 for (p = arg; *p; p++) {
238 if (escaped) {
239 escaped = 0;
240 } else if (is_glob_special(*p)) {
241 if (*p == '\\')
242 escaped = 1;
243 else
244 return 1;
245 }
246 }
247
248 /* long-form pathspec magic */
249 if (starts_with(arg, ":("))
250 return 1;
251
252 return 0;
253 }
254
255 /*
256 * Verify a filename that we got as an argument for a pathspec
257 * entry. Note that a filename that begins with "-" never verifies
258 * as true, because even if such a filename were to exist, we want
259 * it to be preceded by the "--" marker (or we want the user to
260 * use a format like "./-filename")
261 *
262 * The "diagnose_misspelt_rev" is used to provide a user-friendly
263 * diagnosis when dying upon finding that "name" is not a pathname.
264 * If set to 1, the diagnosis will try to diagnose "name" as an
265 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
266 * will only complain about an inexisting file.
267 *
268 * This function is typically called to check that a "file or rev"
269 * argument is unambiguous. In this case, the caller will want
270 * diagnose_misspelt_rev == 1 when verifying the first non-rev
271 * argument (which could have been a revision), and
272 * diagnose_misspelt_rev == 0 for the next ones (because we already
273 * saw a filename, there's not ambiguity anymore).
274 */
275 void verify_filename(const char *prefix,
276 const char *arg,
277 int diagnose_misspelt_rev)
278 {
279 if (*arg == '-')
280 die(_("option '%s' must come before non-option arguments"), arg);
281 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
282 return;
283 die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
284 }
285
286 /*
287 * Opposite of the above: the command line did not have -- marker
288 * and we parsed the arg as a refname. It should not be interpretable
289 * as a filename.
290 */
291 void verify_non_filename(const char *prefix, const char *arg)
292 {
293 if (!is_inside_work_tree() || is_inside_git_dir())
294 return;
295 if (*arg == '-')
296 return; /* flag */
297 if (!check_filename(prefix, arg))
298 return;
299 die(_("ambiguous argument '%s': both revision and filename\n"
300 "Use '--' to separate paths from revisions, like this:\n"
301 "'git <command> [<revision>...] -- [<file>...]'"), arg);
302 }
303
304 int get_common_dir(struct strbuf *sb, const char *gitdir)
305 {
306 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
307 if (git_env_common_dir) {
308 strbuf_addstr(sb, git_env_common_dir);
309 return 1;
310 } else {
311 return get_common_dir_noenv(sb, gitdir);
312 }
313 }
314
315 int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
316 {
317 struct strbuf data = STRBUF_INIT;
318 struct strbuf path = STRBUF_INIT;
319 int ret = 0;
320
321 strbuf_addf(&path, "%s/commondir", gitdir);
322 if (file_exists(path.buf)) {
323 if (strbuf_read_file(&data, path.buf, 0) <= 0)
324 die_errno(_("failed to read %s"), path.buf);
325 while (data.len && (data.buf[data.len - 1] == '\n' ||
326 data.buf[data.len - 1] == '\r'))
327 data.len--;
328 data.buf[data.len] = '\0';
329 strbuf_reset(&path);
330 if (!is_absolute_path(data.buf))
331 strbuf_addf(&path, "%s/", gitdir);
332 strbuf_addbuf(&path, &data);
333 strbuf_add_real_path(sb, path.buf);
334 ret = 1;
335 } else {
336 strbuf_addstr(sb, gitdir);
337 }
338
339 strbuf_release(&data);
340 strbuf_release(&path);
341 return ret;
342 }
343
344 /*
345 * Test if it looks like we're at a git directory.
346 * We want to see:
347 *
348 * - either an objects/ directory _or_ the proper
349 * GIT_OBJECT_DIRECTORY environment variable
350 * - a refs/ directory
351 * - either a HEAD symlink or a HEAD file that is formatted as
352 * a proper "ref:", or a regular file HEAD that has a properly
353 * formatted sha1 object name.
354 */
355 int is_git_directory(const char *suspect)
356 {
357 struct strbuf path = STRBUF_INIT;
358 int ret = 0;
359 size_t len;
360
361 /* Check worktree-related signatures */
362 strbuf_addstr(&path, suspect);
363 strbuf_complete(&path, '/');
364 strbuf_addstr(&path, "HEAD");
365 if (validate_headref(path.buf))
366 goto done;
367
368 strbuf_reset(&path);
369 get_common_dir(&path, suspect);
370 len = path.len;
371
372 /* Check non-worktree-related signatures */
373 if (getenv(DB_ENVIRONMENT)) {
374 if (access(getenv(DB_ENVIRONMENT), X_OK))
375 goto done;
376 }
377 else {
378 strbuf_setlen(&path, len);
379 strbuf_addstr(&path, "/objects");
380 if (access(path.buf, X_OK))
381 goto done;
382 }
383
384 strbuf_setlen(&path, len);
385 strbuf_addstr(&path, "/refs");
386 if (access(path.buf, X_OK))
387 goto done;
388
389 ret = 1;
390 done:
391 strbuf_release(&path);
392 return ret;
393 }
394
395 int is_nonbare_repository_dir(struct strbuf *path)
396 {
397 int ret = 0;
398 int gitfile_error;
399 size_t orig_path_len = path->len;
400 assert(orig_path_len != 0);
401 strbuf_complete(path, '/');
402 strbuf_addstr(path, ".git");
403 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
404 ret = 1;
405 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
406 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
407 ret = 1;
408 strbuf_setlen(path, orig_path_len);
409 return ret;
410 }
411
412 int is_inside_git_dir(void)
413 {
414 if (inside_git_dir < 0)
415 inside_git_dir = is_inside_dir(get_git_dir());
416 return inside_git_dir;
417 }
418
419 int is_inside_work_tree(void)
420 {
421 if (inside_work_tree < 0)
422 inside_work_tree = is_inside_dir(get_git_work_tree());
423 return inside_work_tree;
424 }
425
426 void setup_work_tree(void)
427 {
428 const char *work_tree;
429 static int initialized = 0;
430
431 if (initialized)
432 return;
433
434 if (work_tree_config_is_bogus)
435 die(_("unable to set up work tree using invalid config"));
436
437 work_tree = get_git_work_tree();
438 if (!work_tree || chdir_notify(work_tree))
439 die(_("this operation must be run in a work tree"));
440
441 /*
442 * Make sure subsequent git processes find correct worktree
443 * if $GIT_WORK_TREE is set relative
444 */
445 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
446 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
447
448 initialized = 1;
449 }
450
451 static void setup_original_cwd(void)
452 {
453 struct strbuf tmp = STRBUF_INIT;
454 const char *worktree = NULL;
455 int offset = -1;
456
457 if (!tmp_original_cwd)
458 return;
459
460 /*
461 * startup_info->original_cwd points to the current working
462 * directory we inherited from our parent process, which is a
463 * directory we want to avoid removing.
464 *
465 * For convience, we would like to have the path relative to the
466 * worktree instead of an absolute path.
467 *
468 * Yes, startup_info->original_cwd is usually the same as 'prefix',
469 * but differs in two ways:
470 * - prefix has a trailing '/'
471 * - if the user passes '-C' to git, that modifies the prefix but
472 * not startup_info->original_cwd.
473 */
474
475 /* Normalize the directory */
476 if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) {
477 trace2_data_string("setup", the_repository,
478 "realpath-path", tmp_original_cwd);
479 trace2_data_string("setup", the_repository,
480 "realpath-failure", strerror(errno));
481 free((char*)tmp_original_cwd);
482 tmp_original_cwd = NULL;
483 return;
484 }
485
486 free((char*)tmp_original_cwd);
487 tmp_original_cwd = NULL;
488 startup_info->original_cwd = strbuf_detach(&tmp, NULL);
489
490 /*
491 * Get our worktree; we only protect the current working directory
492 * if it's in the worktree.
493 */
494 worktree = get_git_work_tree();
495 if (!worktree)
496 goto no_prevention_needed;
497
498 offset = dir_inside_of(startup_info->original_cwd, worktree);
499 if (offset >= 0) {
500 /*
501 * If startup_info->original_cwd == worktree, that is already
502 * protected and we don't need original_cwd as a secondary
503 * protection measure.
504 */
505 if (!*(startup_info->original_cwd + offset))
506 goto no_prevention_needed;
507
508 /*
509 * original_cwd was inside worktree; precompose it just as
510 * we do prefix so that built up paths will match
511 */
512 startup_info->original_cwd = \
513 precompose_string_if_needed(startup_info->original_cwd
514 + offset);
515 return;
516 }
517
518 no_prevention_needed:
519 free((char*)startup_info->original_cwd);
520 startup_info->original_cwd = NULL;
521 }
522
523 static int read_worktree_config(const char *var, const char *value,
524 const struct config_context *ctx UNUSED,
525 void *vdata)
526 {
527 struct repository_format *data = vdata;
528
529 if (strcmp(var, "core.bare") == 0) {
530 data->is_bare = git_config_bool(var, value);
531 } else if (strcmp(var, "core.worktree") == 0) {
532 if (!value)
533 return config_error_nonbool(var);
534 free(data->work_tree);
535 data->work_tree = xstrdup(value);
536 }
537 return 0;
538 }
539
540 enum extension_result {
541 EXTENSION_ERROR = -1, /* compatible with error(), etc */
542 EXTENSION_UNKNOWN = 0,
543 EXTENSION_OK = 1
544 };
545
546 /*
547 * Do not add new extensions to this function. It handles extensions which are
548 * respected even in v0-format repositories for historical compatibility.
549 */
550 static enum extension_result handle_extension_v0(const char *var,
551 const char *value,
552 const char *ext,
553 struct repository_format *data)
554 {
555 if (!strcmp(ext, "noop")) {
556 return EXTENSION_OK;
557 } else if (!strcmp(ext, "preciousobjects")) {
558 data->precious_objects = git_config_bool(var, value);
559 return EXTENSION_OK;
560 } else if (!strcmp(ext, "partialclone")) {
561 if (!value)
562 return config_error_nonbool(var);
563 data->partial_clone = xstrdup(value);
564 return EXTENSION_OK;
565 } else if (!strcmp(ext, "worktreeconfig")) {
566 data->worktree_config = git_config_bool(var, value);
567 return EXTENSION_OK;
568 }
569
570 return EXTENSION_UNKNOWN;
571 }
572
573 /*
574 * Record any new extensions in this function.
575 */
576 static enum extension_result handle_extension(const char *var,
577 const char *value,
578 const char *ext,
579 struct repository_format *data)
580 {
581 if (!strcmp(ext, "noop-v1")) {
582 return EXTENSION_OK;
583 } else if (!strcmp(ext, "objectformat")) {
584 int format;
585
586 if (!value)
587 return config_error_nonbool(var);
588 format = hash_algo_by_name(value);
589 if (format == GIT_HASH_UNKNOWN)
590 return error(_("invalid value for '%s': '%s'"),
591 "extensions.objectformat", value);
592 data->hash_algo = format;
593 return EXTENSION_OK;
594 }
595 return EXTENSION_UNKNOWN;
596 }
597
598 static int check_repo_format(const char *var, const char *value,
599 const struct config_context *ctx, void *vdata)
600 {
601 struct repository_format *data = vdata;
602 const char *ext;
603
604 if (strcmp(var, "core.repositoryformatversion") == 0)
605 data->version = git_config_int(var, value, ctx->kvi);
606 else if (skip_prefix(var, "extensions.", &ext)) {
607 switch (handle_extension_v0(var, value, ext, data)) {
608 case EXTENSION_ERROR:
609 return -1;
610 case EXTENSION_OK:
611 return 0;
612 case EXTENSION_UNKNOWN:
613 break;
614 }
615
616 switch (handle_extension(var, value, ext, data)) {
617 case EXTENSION_ERROR:
618 return -1;
619 case EXTENSION_OK:
620 string_list_append(&data->v1_only_extensions, ext);
621 return 0;
622 case EXTENSION_UNKNOWN:
623 string_list_append(&data->unknown_extensions, ext);
624 return 0;
625 }
626 }
627
628 return read_worktree_config(var, value, ctx, vdata);
629 }
630
631 static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
632 {
633 struct strbuf sb = STRBUF_INIT;
634 struct strbuf err = STRBUF_INIT;
635 int has_common;
636
637 has_common = get_common_dir(&sb, gitdir);
638 strbuf_addstr(&sb, "/config");
639 read_repository_format(candidate, sb.buf);
640 strbuf_release(&sb);
641
642 /*
643 * For historical use of check_repository_format() in git-init,
644 * we treat a missing config as a silent "ok", even when nongit_ok
645 * is unset.
646 */
647 if (candidate->version < 0)
648 return 0;
649
650 if (verify_repository_format(candidate, &err) < 0) {
651 if (nongit_ok) {
652 warning("%s", err.buf);
653 strbuf_release(&err);
654 *nongit_ok = -1;
655 return -1;
656 }
657 die("%s", err.buf);
658 }
659
660 repository_format_precious_objects = candidate->precious_objects;
661 string_list_clear(&candidate->unknown_extensions, 0);
662 string_list_clear(&candidate->v1_only_extensions, 0);
663
664 if (candidate->worktree_config) {
665 /*
666 * pick up core.bare and core.worktree from per-worktree
667 * config if present
668 */
669 strbuf_addf(&sb, "%s/config.worktree", gitdir);
670 git_config_from_file(read_worktree_config, sb.buf, candidate);
671 strbuf_release(&sb);
672 has_common = 0;
673 }
674
675 if (!has_common) {
676 if (candidate->is_bare != -1) {
677 is_bare_repository_cfg = candidate->is_bare;
678 if (is_bare_repository_cfg == 1)
679 inside_work_tree = -1;
680 }
681 if (candidate->work_tree) {
682 free(git_work_tree_cfg);
683 git_work_tree_cfg = xstrdup(candidate->work_tree);
684 inside_work_tree = -1;
685 }
686 }
687
688 return 0;
689 }
690
691 int upgrade_repository_format(int target_version)
692 {
693 struct strbuf sb = STRBUF_INIT;
694 struct strbuf err = STRBUF_INIT;
695 struct strbuf repo_version = STRBUF_INIT;
696 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
697 int ret;
698
699 strbuf_git_common_path(&sb, the_repository, "config");
700 read_repository_format(&repo_fmt, sb.buf);
701 strbuf_release(&sb);
702
703 if (repo_fmt.version >= target_version) {
704 ret = 0;
705 goto out;
706 }
707
708 if (verify_repository_format(&repo_fmt, &err) < 0) {
709 ret = error("cannot upgrade repository format from %d to %d: %s",
710 repo_fmt.version, target_version, err.buf);
711 goto out;
712 }
713 if (!repo_fmt.version && repo_fmt.unknown_extensions.nr) {
714 ret = error("cannot upgrade repository format: "
715 "unknown extension %s",
716 repo_fmt.unknown_extensions.items[0].string);
717 goto out;
718 }
719
720 strbuf_addf(&repo_version, "%d", target_version);
721 git_config_set("core.repositoryformatversion", repo_version.buf);
722
723 ret = 1;
724
725 out:
726 clear_repository_format(&repo_fmt);
727 strbuf_release(&repo_version);
728 strbuf_release(&err);
729 return ret;
730 }
731
732 static void init_repository_format(struct repository_format *format)
733 {
734 const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
735
736 memcpy(format, &fresh, sizeof(fresh));
737 }
738
739 int read_repository_format(struct repository_format *format, const char *path)
740 {
741 clear_repository_format(format);
742 git_config_from_file(check_repo_format, path, format);
743 if (format->version == -1)
744 clear_repository_format(format);
745 return format->version;
746 }
747
748 void clear_repository_format(struct repository_format *format)
749 {
750 string_list_clear(&format->unknown_extensions, 0);
751 string_list_clear(&format->v1_only_extensions, 0);
752 free(format->work_tree);
753 free(format->partial_clone);
754 init_repository_format(format);
755 }
756
757 int verify_repository_format(const struct repository_format *format,
758 struct strbuf *err)
759 {
760 if (GIT_REPO_VERSION_READ < format->version) {
761 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
762 GIT_REPO_VERSION_READ, format->version);
763 return -1;
764 }
765
766 if (format->version >= 1 && format->unknown_extensions.nr) {
767 int i;
768
769 strbuf_addstr(err, Q_("unknown repository extension found:",
770 "unknown repository extensions found:",
771 format->unknown_extensions.nr));
772
773 for (i = 0; i < format->unknown_extensions.nr; i++)
774 strbuf_addf(err, "\n\t%s",
775 format->unknown_extensions.items[i].string);
776 return -1;
777 }
778
779 if (format->version == 0 && format->v1_only_extensions.nr) {
780 int i;
781
782 strbuf_addstr(err,
783 Q_("repo version is 0, but v1-only extension found:",
784 "repo version is 0, but v1-only extensions found:",
785 format->v1_only_extensions.nr));
786
787 for (i = 0; i < format->v1_only_extensions.nr; i++)
788 strbuf_addf(err, "\n\t%s",
789 format->v1_only_extensions.items[i].string);
790 return -1;
791 }
792
793 return 0;
794 }
795
796 void read_gitfile_error_die(int error_code, const char *path, const char *dir)
797 {
798 switch (error_code) {
799 case READ_GITFILE_ERR_STAT_FAILED:
800 case READ_GITFILE_ERR_NOT_A_FILE:
801 /* non-fatal; follow return path */
802 break;
803 case READ_GITFILE_ERR_OPEN_FAILED:
804 die_errno(_("error opening '%s'"), path);
805 case READ_GITFILE_ERR_TOO_LARGE:
806 die(_("too large to be a .git file: '%s'"), path);
807 case READ_GITFILE_ERR_READ_FAILED:
808 die(_("error reading %s"), path);
809 case READ_GITFILE_ERR_INVALID_FORMAT:
810 die(_("invalid gitfile format: %s"), path);
811 case READ_GITFILE_ERR_NO_PATH:
812 die(_("no path in gitfile: %s"), path);
813 case READ_GITFILE_ERR_NOT_A_REPO:
814 die(_("not a git repository: %s"), dir);
815 default:
816 BUG("unknown error code");
817 }
818 }
819
820 /*
821 * Try to read the location of the git directory from the .git file,
822 * return path to git directory if found. The return value comes from
823 * a shared buffer.
824 *
825 * On failure, if return_error_code is not NULL, return_error_code
826 * will be set to an error code and NULL will be returned. If
827 * return_error_code is NULL the function will die instead (for most
828 * cases).
829 */
830 const char *read_gitfile_gently(const char *path, int *return_error_code)
831 {
832 const int max_file_size = 1 << 20; /* 1MB */
833 int error_code = 0;
834 char *buf = NULL;
835 char *dir = NULL;
836 const char *slash;
837 struct stat st;
838 int fd;
839 ssize_t len;
840 static struct strbuf realpath = STRBUF_INIT;
841
842 if (stat(path, &st)) {
843 /* NEEDSWORK: discern between ENOENT vs other errors */
844 error_code = READ_GITFILE_ERR_STAT_FAILED;
845 goto cleanup_return;
846 }
847 if (!S_ISREG(st.st_mode)) {
848 error_code = READ_GITFILE_ERR_NOT_A_FILE;
849 goto cleanup_return;
850 }
851 if (st.st_size > max_file_size) {
852 error_code = READ_GITFILE_ERR_TOO_LARGE;
853 goto cleanup_return;
854 }
855 fd = open(path, O_RDONLY);
856 if (fd < 0) {
857 error_code = READ_GITFILE_ERR_OPEN_FAILED;
858 goto cleanup_return;
859 }
860 buf = xmallocz(st.st_size);
861 len = read_in_full(fd, buf, st.st_size);
862 close(fd);
863 if (len != st.st_size) {
864 error_code = READ_GITFILE_ERR_READ_FAILED;
865 goto cleanup_return;
866 }
867 if (!starts_with(buf, "gitdir: ")) {
868 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
869 goto cleanup_return;
870 }
871 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
872 len--;
873 if (len < 9) {
874 error_code = READ_GITFILE_ERR_NO_PATH;
875 goto cleanup_return;
876 }
877 buf[len] = '\0';
878 dir = buf + 8;
879
880 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
881 size_t pathlen = slash+1 - path;
882 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
883 (int)(len - 8), buf + 8);
884 free(buf);
885 buf = dir;
886 }
887 if (!is_git_directory(dir)) {
888 error_code = READ_GITFILE_ERR_NOT_A_REPO;
889 goto cleanup_return;
890 }
891
892 strbuf_realpath(&realpath, dir, 1);
893 path = realpath.buf;
894
895 cleanup_return:
896 if (return_error_code)
897 *return_error_code = error_code;
898 else if (error_code)
899 read_gitfile_error_die(error_code, path, dir);
900
901 free(buf);
902 return error_code ? NULL : path;
903 }
904
905 static const char *setup_explicit_git_dir(const char *gitdirenv,
906 struct strbuf *cwd,
907 struct repository_format *repo_fmt,
908 int *nongit_ok)
909 {
910 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
911 const char *worktree;
912 char *gitfile;
913 int offset;
914
915 if (PATH_MAX - 40 < strlen(gitdirenv))
916 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
917
918 gitfile = (char*)read_gitfile(gitdirenv);
919 if (gitfile) {
920 gitfile = xstrdup(gitfile);
921 gitdirenv = gitfile;
922 }
923
924 if (!is_git_directory(gitdirenv)) {
925 if (nongit_ok) {
926 *nongit_ok = 1;
927 free(gitfile);
928 return NULL;
929 }
930 die(_("not a git repository: '%s'"), gitdirenv);
931 }
932
933 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
934 free(gitfile);
935 return NULL;
936 }
937
938 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
939 if (work_tree_env)
940 set_git_work_tree(work_tree_env);
941 else if (is_bare_repository_cfg > 0) {
942 if (git_work_tree_cfg) {
943 /* #22.2, #30 */
944 warning("core.bare and core.worktree do not make sense");
945 work_tree_config_is_bogus = 1;
946 }
947
948 /* #18, #26 */
949 set_git_dir(gitdirenv, 0);
950 free(gitfile);
951 return NULL;
952 }
953 else if (git_work_tree_cfg) { /* #6, #14 */
954 if (is_absolute_path(git_work_tree_cfg))
955 set_git_work_tree(git_work_tree_cfg);
956 else {
957 char *core_worktree;
958 if (chdir(gitdirenv))
959 die_errno(_("cannot chdir to '%s'"), gitdirenv);
960 if (chdir(git_work_tree_cfg))
961 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
962 core_worktree = xgetcwd();
963 if (chdir(cwd->buf))
964 die_errno(_("cannot come back to cwd"));
965 set_git_work_tree(core_worktree);
966 free(core_worktree);
967 }
968 }
969 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
970 /* #16d */
971 set_git_dir(gitdirenv, 0);
972 free(gitfile);
973 return NULL;
974 }
975 else /* #2, #10 */
976 set_git_work_tree(".");
977
978 /* set_git_work_tree() must have been called by now */
979 worktree = get_git_work_tree();
980
981 /* both get_git_work_tree() and cwd are already normalized */
982 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
983 set_git_dir(gitdirenv, 0);
984 free(gitfile);
985 return NULL;
986 }
987
988 offset = dir_inside_of(cwd->buf, worktree);
989 if (offset >= 0) { /* cwd inside worktree? */
990 set_git_dir(gitdirenv, 1);
991 if (chdir(worktree))
992 die_errno(_("cannot chdir to '%s'"), worktree);
993 strbuf_addch(cwd, '/');
994 free(gitfile);
995 return cwd->buf + offset;
996 }
997
998 /* cwd outside worktree */
999 set_git_dir(gitdirenv, 0);
1000 free(gitfile);
1001 return NULL;
1002 }
1003
1004 static const char *setup_discovered_git_dir(const char *gitdir,
1005 struct strbuf *cwd, int offset,
1006 struct repository_format *repo_fmt,
1007 int *nongit_ok)
1008 {
1009 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
1010 return NULL;
1011
1012 /* --work-tree is set without --git-dir; use discovered one */
1013 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1014 char *to_free = NULL;
1015 const char *ret;
1016
1017 if (offset != cwd->len && !is_absolute_path(gitdir))
1018 gitdir = to_free = real_pathdup(gitdir, 1);
1019 if (chdir(cwd->buf))
1020 die_errno(_("cannot come back to cwd"));
1021 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1022 free(to_free);
1023 return ret;
1024 }
1025
1026 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1027 if (is_bare_repository_cfg > 0) {
1028 set_git_dir(gitdir, (offset != cwd->len));
1029 if (chdir(cwd->buf))
1030 die_errno(_("cannot come back to cwd"));
1031 return NULL;
1032 }
1033
1034 /* #0, #1, #5, #8, #9, #12, #13 */
1035 set_git_work_tree(".");
1036 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
1037 set_git_dir(gitdir, 0);
1038 inside_git_dir = 0;
1039 inside_work_tree = 1;
1040 if (offset >= cwd->len)
1041 return NULL;
1042
1043 /* Make "offset" point past the '/' (already the case for root dirs) */
1044 if (offset != offset_1st_component(cwd->buf))
1045 offset++;
1046 /* Add a '/' at the end */
1047 strbuf_addch(cwd, '/');
1048 return cwd->buf + offset;
1049 }
1050
1051 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1052 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
1053 struct repository_format *repo_fmt,
1054 int *nongit_ok)
1055 {
1056 int root_len;
1057
1058 if (check_repository_format_gently(".", repo_fmt, nongit_ok))
1059 return NULL;
1060
1061 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
1062
1063 /* --work-tree is set without --git-dir; use discovered one */
1064 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1065 static const char *gitdir;
1066
1067 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
1068 if (chdir(cwd->buf))
1069 die_errno(_("cannot come back to cwd"));
1070 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1071 }
1072
1073 inside_git_dir = 1;
1074 inside_work_tree = 0;
1075 if (offset != cwd->len) {
1076 if (chdir(cwd->buf))
1077 die_errno(_("cannot come back to cwd"));
1078 root_len = offset_1st_component(cwd->buf);
1079 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
1080 set_git_dir(cwd->buf, 0);
1081 }
1082 else
1083 set_git_dir(".", 0);
1084 return NULL;
1085 }
1086
1087 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
1088 {
1089 struct stat buf;
1090 if (stat(path, &buf)) {
1091 die_errno(_("failed to stat '%*s%s%s'"),
1092 prefix_len,
1093 prefix ? prefix : "",
1094 prefix ? "/" : "", path);
1095 }
1096 return buf.st_dev;
1097 }
1098
1099 /*
1100 * A "string_list_each_func_t" function that canonicalizes an entry
1101 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1102 * discards it if unusable. The presence of an empty entry in
1103 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1104 * subsequent entries.
1105 */
1106 static int canonicalize_ceiling_entry(struct string_list_item *item,
1107 void *cb_data)
1108 {
1109 int *empty_entry_found = cb_data;
1110 char *ceil = item->string;
1111
1112 if (!*ceil) {
1113 *empty_entry_found = 1;
1114 return 0;
1115 } else if (!is_absolute_path(ceil)) {
1116 return 0;
1117 } else if (*empty_entry_found) {
1118 /* Keep entry but do not canonicalize it */
1119 return 1;
1120 } else {
1121 char *real_path = real_pathdup(ceil, 0);
1122 if (!real_path) {
1123 return 0;
1124 }
1125 free(item->string);
1126 item->string = real_path;
1127 return 1;
1128 }
1129 }
1130
1131 struct safe_directory_data {
1132 const char *path;
1133 int is_safe;
1134 };
1135
1136 static int safe_directory_cb(const char *key, const char *value,
1137 const struct config_context *ctx UNUSED, void *d)
1138 {
1139 struct safe_directory_data *data = d;
1140
1141 if (strcmp(key, "safe.directory"))
1142 return 0;
1143
1144 if (!value || !*value) {
1145 data->is_safe = 0;
1146 } else if (!strcmp(value, "*")) {
1147 data->is_safe = 1;
1148 } else {
1149 const char *interpolated = NULL;
1150
1151 if (!git_config_pathname(&interpolated, key, value) &&
1152 !fspathcmp(data->path, interpolated ? interpolated : value))
1153 data->is_safe = 1;
1154
1155 free((char *)interpolated);
1156 }
1157
1158 return 0;
1159 }
1160
1161 /*
1162 * Check if a repository is safe, by verifying the ownership of the
1163 * worktree (if any), the git directory, and the gitfile (if any).
1164 *
1165 * Exemptions for known-safe repositories can be added via `safe.directory`
1166 * config settings; for non-bare repositories, their worktree needs to be
1167 * added, for bare ones their git directory.
1168 */
1169 static int ensure_valid_ownership(const char *gitfile,
1170 const char *worktree, const char *gitdir,
1171 struct strbuf *report)
1172 {
1173 struct safe_directory_data data = {
1174 .path = worktree ? worktree : gitdir
1175 };
1176
1177 if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1178 (!gitfile || is_path_owned_by_current_user(gitfile, report)) &&
1179 (!worktree || is_path_owned_by_current_user(worktree, report)) &&
1180 (!gitdir || is_path_owned_by_current_user(gitdir, report)))
1181 return 1;
1182
1183 /*
1184 * data.path is the "path" that identifies the repository and it is
1185 * constant regardless of what failed above. data.is_safe should be
1186 * initialized to false, and might be changed by the callback.
1187 */
1188 git_protected_config(safe_directory_cb, &data);
1189
1190 return data.is_safe;
1191 }
1192
1193 static int allowed_bare_repo_cb(const char *key, const char *value,
1194 const struct config_context *ctx UNUSED,
1195 void *d)
1196 {
1197 enum allowed_bare_repo *allowed_bare_repo = d;
1198
1199 if (strcasecmp(key, "safe.bareRepository"))
1200 return 0;
1201
1202 if (!strcmp(value, "explicit")) {
1203 *allowed_bare_repo = ALLOWED_BARE_REPO_EXPLICIT;
1204 return 0;
1205 }
1206 if (!strcmp(value, "all")) {
1207 *allowed_bare_repo = ALLOWED_BARE_REPO_ALL;
1208 return 0;
1209 }
1210 return -1;
1211 }
1212
1213 static enum allowed_bare_repo get_allowed_bare_repo(void)
1214 {
1215 enum allowed_bare_repo result = ALLOWED_BARE_REPO_ALL;
1216 git_protected_config(allowed_bare_repo_cb, &result);
1217 return result;
1218 }
1219
1220 static const char *allowed_bare_repo_to_string(
1221 enum allowed_bare_repo allowed_bare_repo)
1222 {
1223 switch (allowed_bare_repo) {
1224 case ALLOWED_BARE_REPO_EXPLICIT:
1225 return "explicit";
1226 case ALLOWED_BARE_REPO_ALL:
1227 return "all";
1228 default:
1229 BUG("invalid allowed_bare_repo %d",
1230 allowed_bare_repo);
1231 }
1232 return NULL;
1233 }
1234
1235 /*
1236 * We cannot decide in this function whether we are in the work tree or
1237 * not, since the config can only be read _after_ this function was called.
1238 *
1239 * Also, we avoid changing any global state (such as the current working
1240 * directory) to allow early callers.
1241 *
1242 * The directory where the search should start needs to be passed in via the
1243 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1244 * the directory where the search ended, and `gitdir` will contain the path of
1245 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1246 * is relative to `dir` (i.e. *not* necessarily the cwd).
1247 */
1248 static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
1249 struct strbuf *gitdir,
1250 struct strbuf *report,
1251 int die_on_error)
1252 {
1253 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
1254 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
1255 const char *gitdirenv;
1256 int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
1257 dev_t current_device = 0;
1258 int one_filesystem = 1;
1259
1260 /*
1261 * If GIT_DIR is set explicitly, we're not going
1262 * to do any discovery, but we still do repository
1263 * validation.
1264 */
1265 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
1266 if (gitdirenv) {
1267 strbuf_addstr(gitdir, gitdirenv);
1268 return GIT_DIR_EXPLICIT;
1269 }
1270
1271 if (env_ceiling_dirs) {
1272 int empty_entry_found = 0;
1273
1274 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
1275 filter_string_list(&ceiling_dirs, 0,
1276 canonicalize_ceiling_entry, &empty_entry_found);
1277 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
1278 string_list_clear(&ceiling_dirs, 0);
1279 }
1280
1281 if (ceil_offset < 0)
1282 ceil_offset = min_offset - 2;
1283
1284 if (min_offset && min_offset == dir->len &&
1285 !is_dir_sep(dir->buf[min_offset - 1])) {
1286 strbuf_addch(dir, '/');
1287 min_offset++;
1288 }
1289
1290 /*
1291 * Test in the following order (relative to the dir):
1292 * - .git (file containing "gitdir: <path>")
1293 * - .git/
1294 * - ./ (bare)
1295 * - ../.git
1296 * - ../.git/
1297 * - ../ (bare)
1298 * - ../../.git
1299 * etc.
1300 */
1301 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1302 if (one_filesystem)
1303 current_device = get_device_or_die(dir->buf, NULL, 0);
1304 for (;;) {
1305 int offset = dir->len, error_code = 0;
1306 char *gitdir_path = NULL;
1307 char *gitfile = NULL;
1308
1309 if (offset > min_offset)
1310 strbuf_addch(dir, '/');
1311 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
1312 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
1313 NULL : &error_code);
1314 if (!gitdirenv) {
1315 if (die_on_error ||
1316 error_code == READ_GITFILE_ERR_NOT_A_FILE) {
1317 /* NEEDSWORK: fail if .git is not file nor dir */
1318 if (is_git_directory(dir->buf)) {
1319 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1320 gitdir_path = xstrdup(dir->buf);
1321 }
1322 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
1323 return GIT_DIR_INVALID_GITFILE;
1324 } else
1325 gitfile = xstrdup(dir->buf);
1326 /*
1327 * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1328 * to check that directory for a repository.
1329 * Now trim that tentative addition away, because we want to
1330 * focus on the real directory we are in.
1331 */
1332 strbuf_setlen(dir, offset);
1333 if (gitdirenv) {
1334 enum discovery_result ret;
1335 const char *gitdir_candidate =
1336 gitdir_path ? gitdir_path : gitdirenv;
1337
1338 if (ensure_valid_ownership(gitfile, dir->buf,
1339 gitdir_candidate, report)) {
1340 strbuf_addstr(gitdir, gitdirenv);
1341 ret = GIT_DIR_DISCOVERED;
1342 } else
1343 ret = GIT_DIR_INVALID_OWNERSHIP;
1344
1345 /*
1346 * Earlier, during discovery, we might have allocated
1347 * string copies for gitdir_path or gitfile so make
1348 * sure we don't leak by freeing them now, before
1349 * leaving the loop and function.
1350 *
1351 * Note: gitdirenv will be non-NULL whenever these are
1352 * allocated, therefore we need not take care of releasing
1353 * them outside of this conditional block.
1354 */
1355 free(gitdir_path);
1356 free(gitfile);
1357
1358 return ret;
1359 }
1360
1361 if (is_git_directory(dir->buf)) {
1362 trace2_data_string("setup", NULL, "implicit-bare-repository", dir->buf);
1363 if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT)
1364 return GIT_DIR_DISALLOWED_BARE;
1365 if (!ensure_valid_ownership(NULL, NULL, dir->buf, report))
1366 return GIT_DIR_INVALID_OWNERSHIP;
1367 strbuf_addstr(gitdir, ".");
1368 return GIT_DIR_BARE;
1369 }
1370
1371 if (offset <= min_offset)
1372 return GIT_DIR_HIT_CEILING;
1373
1374 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1375 ; /* continue */
1376 if (offset <= ceil_offset)
1377 return GIT_DIR_HIT_CEILING;
1378
1379 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
1380 if (one_filesystem &&
1381 current_device != get_device_or_die(dir->buf, NULL, offset))
1382 return GIT_DIR_HIT_MOUNT_POINT;
1383 }
1384 }
1385
1386 enum discovery_result discover_git_directory_reason(struct strbuf *commondir,
1387 struct strbuf *gitdir)
1388 {
1389 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1390 size_t gitdir_offset = gitdir->len, cwd_len;
1391 size_t commondir_offset = commondir->len;
1392 struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1393 enum discovery_result result;
1394
1395 if (strbuf_getcwd(&dir))
1396 return GIT_DIR_CWD_FAILURE;
1397
1398 cwd_len = dir.len;
1399 result = setup_git_directory_gently_1(&dir, gitdir, NULL, 0);
1400 if (result <= 0) {
1401 strbuf_release(&dir);
1402 return result;
1403 }
1404
1405 /*
1406 * The returned gitdir is relative to dir, and if dir does not reflect
1407 * the current working directory, we simply make the gitdir absolute.
1408 */
1409 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1410 /* Avoid a trailing "/." */
1411 if (!strcmp(".", gitdir->buf + gitdir_offset))
1412 strbuf_setlen(gitdir, gitdir_offset);
1413 else
1414 strbuf_addch(&dir, '/');
1415 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1416 }
1417
1418 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1419
1420 strbuf_reset(&dir);
1421 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1422 read_repository_format(&candidate, dir.buf);
1423 strbuf_release(&dir);
1424
1425 if (verify_repository_format(&candidate, &err) < 0) {
1426 warning("ignoring git dir '%s': %s",
1427 gitdir->buf + gitdir_offset, err.buf);
1428 strbuf_release(&err);
1429 strbuf_setlen(commondir, commondir_offset);
1430 strbuf_setlen(gitdir, gitdir_offset);
1431 clear_repository_format(&candidate);
1432 return GIT_DIR_INVALID_FORMAT;
1433 }
1434
1435 clear_repository_format(&candidate);
1436 return result;
1437 }
1438
1439 const char *setup_git_directory_gently(int *nongit_ok)
1440 {
1441 static struct strbuf cwd = STRBUF_INIT;
1442 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT;
1443 const char *prefix = NULL;
1444 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1445
1446 /*
1447 * We may have read an incomplete configuration before
1448 * setting-up the git directory. If so, clear the cache so
1449 * that the next queries to the configuration reload complete
1450 * configuration (including the per-repo config file that we
1451 * ignored previously).
1452 */
1453 git_config_clear();
1454
1455 /*
1456 * Let's assume that we are in a git repository.
1457 * If it turns out later that we are somewhere else, the value will be
1458 * updated accordingly.
1459 */
1460 if (nongit_ok)
1461 *nongit_ok = 0;
1462
1463 if (strbuf_getcwd(&cwd))
1464 die_errno(_("Unable to read current working directory"));
1465 strbuf_addbuf(&dir, &cwd);
1466
1467 switch (setup_git_directory_gently_1(&dir, &gitdir, &report, 1)) {
1468 case GIT_DIR_EXPLICIT:
1469 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1470 break;
1471 case GIT_DIR_DISCOVERED:
1472 if (dir.len < cwd.len && chdir(dir.buf))
1473 die(_("cannot change to '%s'"), dir.buf);
1474 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1475 &repo_fmt, nongit_ok);
1476 break;
1477 case GIT_DIR_BARE:
1478 if (dir.len < cwd.len && chdir(dir.buf))
1479 die(_("cannot change to '%s'"), dir.buf);
1480 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1481 break;
1482 case GIT_DIR_HIT_CEILING:
1483 if (!nongit_ok)
1484 die(_("not a git repository (or any of the parent directories): %s"),
1485 DEFAULT_GIT_DIR_ENVIRONMENT);
1486 *nongit_ok = 1;
1487 break;
1488 case GIT_DIR_HIT_MOUNT_POINT:
1489 if (!nongit_ok)
1490 die(_("not a git repository (or any parent up to mount point %s)\n"
1491 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1492 dir.buf);
1493 *nongit_ok = 1;
1494 break;
1495 case GIT_DIR_INVALID_OWNERSHIP:
1496 if (!nongit_ok) {
1497 struct strbuf quoted = STRBUF_INIT;
1498
1499 strbuf_complete(&report, '\n');
1500 sq_quote_buf_pretty(&quoted, dir.buf);
1501 die(_("detected dubious ownership in repository at '%s'\n"
1502 "%s"
1503 "To add an exception for this directory, call:\n"
1504 "\n"
1505 "\tgit config --global --add safe.directory %s"),
1506 dir.buf, report.buf, quoted.buf);
1507 }
1508 *nongit_ok = 1;
1509 break;
1510 case GIT_DIR_DISALLOWED_BARE:
1511 if (!nongit_ok) {
1512 die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
1513 dir.buf,
1514 allowed_bare_repo_to_string(get_allowed_bare_repo()));
1515 }
1516 *nongit_ok = 1;
1517 break;
1518 case GIT_DIR_CWD_FAILURE:
1519 case GIT_DIR_INVALID_FORMAT:
1520 /*
1521 * As a safeguard against setup_git_directory_gently_1 returning
1522 * these values, fallthrough to BUG. Otherwise it is possible to
1523 * set startup_info->have_repository to 1 when we did nothing to
1524 * find a repository.
1525 */
1526 default:
1527 BUG("unhandled setup_git_directory_gently_1() result");
1528 }
1529
1530 /*
1531 * At this point, nongit_ok is stable. If it is non-NULL and points
1532 * to a non-zero value, then this means that we haven't found a
1533 * repository and that the caller expects startup_info to reflect
1534 * this.
1535 *
1536 * Regardless of the state of nongit_ok, startup_info->prefix and
1537 * the GIT_PREFIX environment variable must always match. For details
1538 * see Documentation/config/alias.txt.
1539 */
1540 if (nongit_ok && *nongit_ok)
1541 startup_info->have_repository = 0;
1542 else
1543 startup_info->have_repository = 1;
1544
1545 /*
1546 * Not all paths through the setup code will call 'set_git_dir()' (which
1547 * directly sets up the environment) so in order to guarantee that the
1548 * environment is in a consistent state after setup, explicitly setup
1549 * the environment if we have a repository.
1550 *
1551 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1552 * code paths so we also need to explicitly setup the environment if
1553 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1554 * GIT_DIR values at some point in the future.
1555 */
1556 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1557 startup_info->have_repository ||
1558 /* GIT_DIR_EXPLICIT */
1559 getenv(GIT_DIR_ENVIRONMENT)) {
1560 if (!the_repository->gitdir) {
1561 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1562 if (!gitdir)
1563 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1564 setup_git_env(gitdir);
1565 }
1566 if (startup_info->have_repository) {
1567 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1568 the_repository->repository_format_worktree_config =
1569 repo_fmt.worktree_config;
1570 /* take ownership of repo_fmt.partial_clone */
1571 the_repository->repository_format_partial_clone =
1572 repo_fmt.partial_clone;
1573 repo_fmt.partial_clone = NULL;
1574 }
1575 }
1576 /*
1577 * Since precompose_string_if_needed() needs to look at
1578 * the core.precomposeunicode configuration, this
1579 * has to happen after the above block that finds
1580 * out where the repository is, i.e. a preparation
1581 * for calling git_config_get_bool().
1582 */
1583 if (prefix) {
1584 prefix = precompose_string_if_needed(prefix);
1585 startup_info->prefix = prefix;
1586 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1587 } else {
1588 startup_info->prefix = NULL;
1589 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1590 }
1591
1592 setup_original_cwd();
1593
1594 strbuf_release(&dir);
1595 strbuf_release(&gitdir);
1596 strbuf_release(&report);
1597 clear_repository_format(&repo_fmt);
1598
1599 return prefix;
1600 }
1601
1602 int git_config_perm(const char *var, const char *value)
1603 {
1604 int i;
1605 char *endptr;
1606
1607 if (!value)
1608 return PERM_GROUP;
1609
1610 if (!strcmp(value, "umask"))
1611 return PERM_UMASK;
1612 if (!strcmp(value, "group"))
1613 return PERM_GROUP;
1614 if (!strcmp(value, "all") ||
1615 !strcmp(value, "world") ||
1616 !strcmp(value, "everybody"))
1617 return PERM_EVERYBODY;
1618
1619 /* Parse octal numbers */
1620 i = strtol(value, &endptr, 8);
1621
1622 /* If not an octal number, maybe true/false? */
1623 if (*endptr != 0)
1624 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1625
1626 /*
1627 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1628 * a chmod value to restrict to.
1629 */
1630 switch (i) {
1631 case PERM_UMASK: /* 0 */
1632 return PERM_UMASK;
1633 case OLD_PERM_GROUP: /* 1 */
1634 return PERM_GROUP;
1635 case OLD_PERM_EVERYBODY: /* 2 */
1636 return PERM_EVERYBODY;
1637 }
1638
1639 /* A filemode value was given: 0xxx */
1640
1641 if ((i & 0600) != 0600)
1642 die(_("problem with core.sharedRepository filemode value "
1643 "(0%.3o).\nThe owner of files must always have "
1644 "read and write permissions."), i);
1645
1646 /*
1647 * Mask filemode value. Others can not get write permission.
1648 * x flags for directories are handled separately.
1649 */
1650 return -(i & 0666);
1651 }
1652
1653 void check_repository_format(struct repository_format *fmt)
1654 {
1655 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1656 if (!fmt)
1657 fmt = &repo_fmt;
1658 check_repository_format_gently(get_git_dir(), fmt, NULL);
1659 startup_info->have_repository = 1;
1660 repo_set_hash_algo(the_repository, fmt->hash_algo);
1661 the_repository->repository_format_worktree_config =
1662 fmt->worktree_config;
1663 the_repository->repository_format_partial_clone =
1664 xstrdup_or_null(fmt->partial_clone);
1665 clear_repository_format(&repo_fmt);
1666 }
1667
1668 /*
1669 * Returns the "prefix", a path to the current working directory
1670 * relative to the work tree root, or NULL, if the current working
1671 * directory is not a strict subdirectory of the work tree root. The
1672 * prefix always ends with a '/' character.
1673 */
1674 const char *setup_git_directory(void)
1675 {
1676 return setup_git_directory_gently(NULL);
1677 }
1678
1679 const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1680 {
1681 if (is_git_directory(suspect))
1682 return suspect;
1683 return read_gitfile_gently(suspect, return_error_code);
1684 }
1685
1686 /* if any standard file descriptor is missing open it to /dev/null */
1687 void sanitize_stdfds(void)
1688 {
1689 int fd = xopen("/dev/null", O_RDWR);
1690 while (fd < 2)
1691 fd = xdup(fd);
1692 if (fd > 2)
1693 close(fd);
1694 }
1695
1696 int daemonize(void)
1697 {
1698 #ifdef NO_POSIX_GOODIES
1699 errno = ENOSYS;
1700 return -1;
1701 #else
1702 switch (fork()) {
1703 case 0:
1704 break;
1705 case -1:
1706 die_errno(_("fork failed"));
1707 default:
1708 exit(0);
1709 }
1710 if (setsid() == -1)
1711 die_errno(_("setsid failed"));
1712 close(0);
1713 close(1);
1714 close(2);
1715 sanitize_stdfds();
1716 return 0;
1717 #endif
1718 }
1719
1720 #ifdef NO_TRUSTABLE_FILEMODE
1721 #define TEST_FILEMODE 0
1722 #else
1723 #define TEST_FILEMODE 1
1724 #endif
1725
1726 #define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
1727
1728 static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
1729 DIR *dir)
1730 {
1731 size_t path_baselen = path->len;
1732 size_t template_baselen = template_path->len;
1733 struct dirent *de;
1734
1735 /* Note: if ".git/hooks" file exists in the repository being
1736 * re-initialized, /etc/core-git/templates/hooks/update would
1737 * cause "git init" to fail here. I think this is sane but
1738 * it means that the set of templates we ship by default, along
1739 * with the way the namespace under .git/ is organized, should
1740 * be really carefully chosen.
1741 */
1742 safe_create_dir(path->buf, 1);
1743 while ((de = readdir(dir)) != NULL) {
1744 struct stat st_git, st_template;
1745 int exists = 0;
1746
1747 strbuf_setlen(path, path_baselen);
1748 strbuf_setlen(template_path, template_baselen);
1749
1750 if (de->d_name[0] == '.')
1751 continue;
1752 strbuf_addstr(path, de->d_name);
1753 strbuf_addstr(template_path, de->d_name);
1754 if (lstat(path->buf, &st_git)) {
1755 if (errno != ENOENT)
1756 die_errno(_("cannot stat '%s'"), path->buf);
1757 }
1758 else
1759 exists = 1;
1760
1761 if (lstat(template_path->buf, &st_template))
1762 die_errno(_("cannot stat template '%s'"), template_path->buf);
1763
1764 if (S_ISDIR(st_template.st_mode)) {
1765 DIR *subdir = opendir(template_path->buf);
1766 if (!subdir)
1767 die_errno(_("cannot opendir '%s'"), template_path->buf);
1768 strbuf_addch(path, '/');
1769 strbuf_addch(template_path, '/');
1770 copy_templates_1(path, template_path, subdir);
1771 closedir(subdir);
1772 }
1773 else if (exists)
1774 continue;
1775 else if (S_ISLNK(st_template.st_mode)) {
1776 struct strbuf lnk = STRBUF_INIT;
1777 if (strbuf_readlink(&lnk, template_path->buf,
1778 st_template.st_size) < 0)
1779 die_errno(_("cannot readlink '%s'"), template_path->buf);
1780 if (symlink(lnk.buf, path->buf))
1781 die_errno(_("cannot symlink '%s' '%s'"),
1782 lnk.buf, path->buf);
1783 strbuf_release(&lnk);
1784 }
1785 else if (S_ISREG(st_template.st_mode)) {
1786 if (copy_file(path->buf, template_path->buf, st_template.st_mode))
1787 die_errno(_("cannot copy '%s' to '%s'"),
1788 template_path->buf, path->buf);
1789 }
1790 else
1791 error(_("ignoring template %s"), template_path->buf);
1792 }
1793 }
1794
1795 static void copy_templates(const char *template_dir, const char *init_template_dir)
1796 {
1797 struct strbuf path = STRBUF_INIT;
1798 struct strbuf template_path = STRBUF_INIT;
1799 size_t template_len;
1800 struct repository_format template_format = REPOSITORY_FORMAT_INIT;
1801 struct strbuf err = STRBUF_INIT;
1802 DIR *dir;
1803 char *to_free = NULL;
1804
1805 if (!template_dir)
1806 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
1807 if (!template_dir)
1808 template_dir = init_template_dir;
1809 if (!template_dir)
1810 template_dir = to_free = system_path(DEFAULT_GIT_TEMPLATE_DIR);
1811 if (!template_dir[0]) {
1812 free(to_free);
1813 return;
1814 }
1815
1816 strbuf_addstr(&template_path, template_dir);
1817 strbuf_complete(&template_path, '/');
1818 template_len = template_path.len;
1819
1820 dir = opendir(template_path.buf);
1821 if (!dir) {
1822 warning(_("templates not found in %s"), template_dir);
1823 goto free_return;
1824 }
1825
1826 /* Make sure that template is from the correct vintage */
1827 strbuf_addstr(&template_path, "config");
1828 read_repository_format(&template_format, template_path.buf);
1829 strbuf_setlen(&template_path, template_len);
1830
1831 /*
1832 * No mention of version at all is OK, but anything else should be
1833 * verified.
1834 */
1835 if (template_format.version >= 0 &&
1836 verify_repository_format(&template_format, &err) < 0) {
1837 warning(_("not copying templates from '%s': %s"),
1838 template_dir, err.buf);
1839 strbuf_release(&err);
1840 goto close_free_return;
1841 }
1842
1843 strbuf_addstr(&path, get_git_common_dir());
1844 strbuf_complete(&path, '/');
1845 copy_templates_1(&path, &template_path, dir);
1846 close_free_return:
1847 closedir(dir);
1848 free_return:
1849 free(to_free);
1850 strbuf_release(&path);
1851 strbuf_release(&template_path);
1852 clear_repository_format(&template_format);
1853 }
1854
1855 /*
1856 * If the git_dir is not directly inside the working tree, then git will not
1857 * find it by default, and we need to set the worktree explicitly.
1858 */
1859 static int needs_work_tree_config(const char *git_dir, const char *work_tree)
1860 {
1861 if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
1862 return 0;
1863 if (skip_prefix(git_dir, work_tree, &git_dir) &&
1864 !strcmp(git_dir, "/.git"))
1865 return 0;
1866 return 1;
1867 }
1868
1869 void initialize_repository_version(int hash_algo, int reinit)
1870 {
1871 char repo_version_string[10];
1872 int repo_version = GIT_REPO_VERSION;
1873
1874 if (hash_algo != GIT_HASH_SHA1)
1875 repo_version = GIT_REPO_VERSION_READ;
1876
1877 /* This forces creation of new config file */
1878 xsnprintf(repo_version_string, sizeof(repo_version_string),
1879 "%d", repo_version);
1880 git_config_set("core.repositoryformatversion", repo_version_string);
1881
1882 if (hash_algo != GIT_HASH_SHA1)
1883 git_config_set("extensions.objectformat",
1884 hash_algos[hash_algo].name);
1885 else if (reinit)
1886 git_config_set_gently("extensions.objectformat", NULL);
1887 }
1888
1889 static int create_default_files(const char *template_path,
1890 const char *original_git_dir,
1891 const char *initial_branch,
1892 const struct repository_format *fmt,
1893 int prev_bare_repository,
1894 int init_shared_repository,
1895 int quiet)
1896 {
1897 struct stat st1;
1898 struct strbuf buf = STRBUF_INIT;
1899 char *path;
1900 char junk[2];
1901 int reinit;
1902 int filemode;
1903 struct strbuf err = STRBUF_INIT;
1904 const char *init_template_dir = NULL;
1905 const char *work_tree = get_git_work_tree();
1906
1907 /*
1908 * First copy the templates -- we might have the default
1909 * config file there, in which case we would want to read
1910 * from it after installing.
1911 *
1912 * Before reading that config, we also need to clear out any cached
1913 * values (since we've just potentially changed what's available on
1914 * disk).
1915 */
1916 git_config_get_pathname("init.templatedir", &init_template_dir);
1917 copy_templates(template_path, init_template_dir);
1918 free((char *)init_template_dir);
1919 git_config_clear();
1920 reset_shared_repository();
1921 git_config(git_default_config, NULL);
1922
1923 /*
1924 * We must make sure command-line options continue to override any
1925 * values we might have just re-read from the config.
1926 */
1927 if (init_shared_repository != -1)
1928 set_shared_repository(init_shared_repository);
1929 /*
1930 * TODO: heed core.bare from config file in templates if no
1931 * command-line override given
1932 */
1933 is_bare_repository_cfg = prev_bare_repository || !work_tree;
1934 /* TODO (continued):
1935 *
1936 * Unfortunately, the line above is equivalent to
1937 * is_bare_repository_cfg = !work_tree;
1938 * which ignores the config entirely even if no `--[no-]bare`
1939 * command line option was present.
1940 *
1941 * To see why, note that before this function, there was this call:
1942 * prev_bare_repository = is_bare_repository()
1943 * expanding the right hand side:
1944 * = is_bare_repository_cfg && !get_git_work_tree()
1945 * = is_bare_repository_cfg && !work_tree
1946 * note that the last simplification above is valid because nothing
1947 * calls repo_init() or set_git_work_tree() between any of the
1948 * relevant calls in the code, and thus the !get_git_work_tree()
1949 * calls will return the same result each time. So, what we are
1950 * interested in computing is the right hand side of the line of
1951 * code just above this comment:
1952 * prev_bare_repository || !work_tree
1953 * = is_bare_repository_cfg && !work_tree || !work_tree
1954 * = !work_tree
1955 * because "A && !B || !B == !B" for all boolean values of A & B.
1956 */
1957
1958 /*
1959 * We would have created the above under user's umask -- under
1960 * shared-repository settings, we would need to fix them up.
1961 */
1962 if (get_shared_repository()) {
1963 adjust_shared_perm(get_git_dir());
1964 }
1965
1966 /*
1967 * We need to create a "refs" dir in any case so that older
1968 * versions of git can tell that this is a repository.
1969 */
1970 safe_create_dir(git_path("refs"), 1);
1971 adjust_shared_perm(git_path("refs"));
1972
1973 if (refs_init_db(&err))
1974 die("failed to set up refs db: %s", err.buf);
1975
1976 /*
1977 * Point the HEAD symref to the initial branch with if HEAD does
1978 * not yet exist.
1979 */
1980 path = git_path_buf(&buf, "HEAD");
1981 reinit = (!access(path, R_OK)
1982 || readlink(path, junk, sizeof(junk)-1) != -1);
1983 if (!reinit) {
1984 char *ref;
1985
1986 if (!initial_branch)
1987 initial_branch = git_default_branch_name(quiet);
1988
1989 ref = xstrfmt("refs/heads/%s", initial_branch);
1990 if (check_refname_format(ref, 0) < 0)
1991 die(_("invalid initial branch name: '%s'"),
1992 initial_branch);
1993
1994 if (create_symref("HEAD", ref, NULL) < 0)
1995 exit(1);
1996 free(ref);
1997 }
1998
1999 initialize_repository_version(fmt->hash_algo, 0);
2000
2001 /* Check filemode trustability */
2002 path = git_path_buf(&buf, "config");
2003 filemode = TEST_FILEMODE;
2004 if (TEST_FILEMODE && !lstat(path, &st1)) {
2005 struct stat st2;
2006 filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
2007 !lstat(path, &st2) &&
2008 st1.st_mode != st2.st_mode &&
2009 !chmod(path, st1.st_mode));
2010 if (filemode && !reinit && (st1.st_mode & S_IXUSR))
2011 filemode = 0;
2012 }
2013 git_config_set("core.filemode", filemode ? "true" : "false");
2014
2015 if (is_bare_repository())
2016 git_config_set("core.bare", "true");
2017 else {
2018 git_config_set("core.bare", "false");
2019 /* allow template config file to override the default */
2020 if (log_all_ref_updates == LOG_REFS_UNSET)
2021 git_config_set("core.logallrefupdates", "true");
2022 if (needs_work_tree_config(original_git_dir, work_tree))
2023 git_config_set("core.worktree", work_tree);
2024 }
2025
2026 if (!reinit) {
2027 /* Check if symlink is supported in the work tree */
2028 path = git_path_buf(&buf, "tXXXXXX");
2029 if (!close(xmkstemp(path)) &&
2030 !unlink(path) &&
2031 !symlink("testing", path) &&
2032 !lstat(path, &st1) &&
2033 S_ISLNK(st1.st_mode))
2034 unlink(path); /* good */
2035 else
2036 git_config_set("core.symlinks", "false");
2037
2038 /* Check if the filesystem is case-insensitive */
2039 path = git_path_buf(&buf, "CoNfIg");
2040 if (!access(path, F_OK))
2041 git_config_set("core.ignorecase", "true");
2042 probe_utf8_pathname_composition();
2043 }
2044
2045 strbuf_release(&buf);
2046 return reinit;
2047 }
2048
2049 static void create_object_directory(void)
2050 {
2051 struct strbuf path = STRBUF_INIT;
2052 size_t baselen;
2053
2054 strbuf_addstr(&path, get_object_directory());
2055 baselen = path.len;
2056
2057 safe_create_dir(path.buf, 1);
2058
2059 strbuf_setlen(&path, baselen);
2060 strbuf_addstr(&path, "/pack");
2061 safe_create_dir(path.buf, 1);
2062
2063 strbuf_setlen(&path, baselen);
2064 strbuf_addstr(&path, "/info");
2065 safe_create_dir(path.buf, 1);
2066
2067 strbuf_release(&path);
2068 }
2069
2070 static void separate_git_dir(const char *git_dir, const char *git_link)
2071 {
2072 struct stat st;
2073
2074 if (!stat(git_link, &st)) {
2075 const char *src;
2076
2077 if (S_ISREG(st.st_mode))
2078 src = read_gitfile(git_link);
2079 else if (S_ISDIR(st.st_mode))
2080 src = git_link;
2081 else
2082 die(_("unable to handle file type %d"), (int)st.st_mode);
2083
2084 if (rename(src, git_dir))
2085 die_errno(_("unable to move %s to %s"), src, git_dir);
2086 repair_worktrees(NULL, NULL);
2087 }
2088
2089 write_file(git_link, "gitdir: %s", git_dir);
2090 }
2091
2092 static void validate_hash_algorithm(struct repository_format *repo_fmt, int hash)
2093 {
2094 const char *env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT);
2095 /*
2096 * If we already have an initialized repo, don't allow the user to
2097 * specify a different algorithm, as that could cause corruption.
2098 * Otherwise, if the user has specified one on the command line, use it.
2099 */
2100 if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo)
2101 die(_("attempt to reinitialize repository with different hash"));
2102 else if (hash != GIT_HASH_UNKNOWN)
2103 repo_fmt->hash_algo = hash;
2104 else if (env) {
2105 int env_algo = hash_algo_by_name(env);
2106 if (env_algo == GIT_HASH_UNKNOWN)
2107 die(_("unknown hash algorithm '%s'"), env);
2108 repo_fmt->hash_algo = env_algo;
2109 }
2110 }
2111
2112 int init_db(const char *git_dir, const char *real_git_dir,
2113 const char *template_dir, int hash, const char *initial_branch,
2114 int init_shared_repository, unsigned int flags)
2115 {
2116 int reinit;
2117 int exist_ok = flags & INIT_DB_EXIST_OK;
2118 char *original_git_dir = real_pathdup(git_dir, 1);
2119 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
2120 int prev_bare_repository;
2121
2122 if (real_git_dir) {
2123 struct stat st;
2124
2125 if (!exist_ok && !stat(git_dir, &st))
2126 die(_("%s already exists"), git_dir);
2127
2128 if (!exist_ok && !stat(real_git_dir, &st))
2129 die(_("%s already exists"), real_git_dir);
2130
2131 set_git_dir(real_git_dir, 1);
2132 git_dir = get_git_dir();
2133 separate_git_dir(git_dir, original_git_dir);
2134 }
2135 else {
2136 set_git_dir(git_dir, 1);
2137 git_dir = get_git_dir();
2138 }
2139 startup_info->have_repository = 1;
2140
2141 /* Ensure `core.hidedotfiles` is processed */
2142 git_config(platform_core_config, NULL);
2143
2144 safe_create_dir(git_dir, 0);
2145
2146 prev_bare_repository = is_bare_repository();
2147
2148 /* Check to see if the repository version is right.
2149 * Note that a newly created repository does not have
2150 * config file, so this will not fail. What we are catching
2151 * is an attempt to reinitialize new repository with an old tool.
2152 */
2153 check_repository_format(&repo_fmt);
2154
2155 validate_hash_algorithm(&repo_fmt, hash);
2156
2157 reinit = create_default_files(template_dir, original_git_dir,
2158 initial_branch, &repo_fmt,
2159 prev_bare_repository,
2160 init_shared_repository,
2161 flags & INIT_DB_QUIET);
2162 if (reinit && initial_branch)
2163 warning(_("re-init: ignored --initial-branch=%s"),
2164 initial_branch);
2165
2166 create_object_directory();
2167
2168 if (get_shared_repository()) {
2169 char buf[10];
2170 /* We do not spell "group" and such, so that
2171 * the configuration can be read by older version
2172 * of git. Note, we use octal numbers for new share modes,
2173 * and compatibility values for PERM_GROUP and
2174 * PERM_EVERYBODY.
2175 */
2176 if (get_shared_repository() < 0)
2177 /* force to the mode value */
2178 xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
2179 else if (get_shared_repository() == PERM_GROUP)
2180 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
2181 else if (get_shared_repository() == PERM_EVERYBODY)
2182 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
2183 else
2184 BUG("invalid value for shared_repository");
2185 git_config_set("core.sharedrepository", buf);
2186 git_config_set("receive.denyNonFastforwards", "true");
2187 }
2188
2189 if (!(flags & INIT_DB_QUIET)) {
2190 int len = strlen(git_dir);
2191
2192 if (reinit)
2193 printf(get_shared_repository()
2194 ? _("Reinitialized existing shared Git repository in %s%s\n")
2195 : _("Reinitialized existing Git repository in %s%s\n"),
2196 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2197 else
2198 printf(get_shared_repository()
2199 ? _("Initialized empty shared Git repository in %s%s\n")
2200 : _("Initialized empty Git repository in %s%s\n"),
2201 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2202 }
2203
2204 clear_repository_format(&repo_fmt);
2205 free(original_git_dir);
2206 return 0;
2207 }