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