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