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