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