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