Git fork
at reftables-rust 2665 lines 76 kB view raw
1#define USE_THE_REPOSITORY_VARIABLE 2#define DISABLE_SIGN_COMPARE_WARNINGS 3 4#include "git-compat-util.h" 5#include "abspath.h" 6#include "copy.h" 7#include "environment.h" 8#include "exec-cmd.h" 9#include "gettext.h" 10#include "hex.h" 11#include "object-file.h" 12#include "object-name.h" 13#include "refs.h" 14#include "replace-object.h" 15#include "repository.h" 16#include "config.h" 17#include "dir.h" 18#include "setup.h" 19#include "shallow.h" 20#include "string-list.h" 21#include "strvec.h" 22#include "chdir-notify.h" 23#include "path.h" 24#include "quote.h" 25#include "tmp-objdir.h" 26#include "trace.h" 27#include "trace2.h" 28#include "worktree.h" 29#include "exec-cmd.h" 30 31static int inside_git_dir = -1; 32static int inside_work_tree = -1; 33static int work_tree_config_is_bogus; 34enum allowed_bare_repo { 35 ALLOWED_BARE_REPO_EXPLICIT = 0, 36 ALLOWED_BARE_REPO_ALL, 37}; 38 39static struct startup_info the_startup_info; 40struct startup_info *startup_info = &the_startup_info; 41const char *tmp_original_cwd; 42 43/* 44 * The input parameter must contain an absolute path, and it must already be 45 * normalized. 46 * 47 * Find the part of an absolute path that lies inside the work tree by 48 * dereferencing symlinks outside the work tree, for example: 49 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file 50 * /dir/file (work tree is /) -> dir/file 51 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2 52 * /dir/repolink/file (repolink points to /dir/repo) -> file 53 * /dir/repo (exactly equal to work tree) -> (empty string) 54 */ 55static int abspath_part_inside_repo(char *path) 56{ 57 size_t len; 58 size_t wtlen; 59 char *path0; 60 int off; 61 const char *work_tree = precompose_string_if_needed(repo_get_work_tree(the_repository)); 62 struct strbuf realpath = STRBUF_INIT; 63 64 if (!work_tree) 65 return -1; 66 wtlen = strlen(work_tree); 67 len = strlen(path); 68 off = offset_1st_component(path); 69 70 /* check if work tree is already the prefix */ 71 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) { 72 if (path[wtlen] == '/') { 73 memmove(path, path + wtlen + 1, len - wtlen); 74 return 0; 75 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') { 76 /* work tree is the root, or the whole path */ 77 memmove(path, path + wtlen, len - wtlen + 1); 78 return 0; 79 } 80 /* work tree might match beginning of a symlink to work tree */ 81 off = wtlen; 82 } 83 path0 = path; 84 path += off; 85 86 /* check each '/'-terminated level */ 87 while (*path) { 88 path++; 89 if (*path == '/') { 90 *path = '\0'; 91 strbuf_realpath(&realpath, path0, 1); 92 if (fspathcmp(realpath.buf, work_tree) == 0) { 93 memmove(path0, path + 1, len - (path - path0)); 94 strbuf_release(&realpath); 95 return 0; 96 } 97 *path = '/'; 98 } 99 } 100 101 /* check whole path */ 102 strbuf_realpath(&realpath, path0, 1); 103 if (fspathcmp(realpath.buf, work_tree) == 0) { 104 *path0 = '\0'; 105 strbuf_release(&realpath); 106 return 0; 107 } 108 109 strbuf_release(&realpath); 110 return -1; 111} 112 113/* 114 * Normalize "path", prepending the "prefix" for relative paths. If 115 * remaining_prefix is not NULL, return the actual prefix still 116 * remains in the path. For example, prefix = sub1/sub2/ and path is 117 * 118 * foo -> sub1/sub2/foo (full prefix) 119 * ../foo -> sub1/foo (remaining prefix is sub1/) 120 * ../../bar -> bar (no remaining prefix) 121 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix) 122 * `pwd`/../bar -> sub1/bar (no remaining prefix) 123 */ 124char *prefix_path_gently(const char *prefix, int len, 125 int *remaining_prefix, const char *path) 126{ 127 const char *orig = path; 128 char *sanitized; 129 if (is_absolute_path(orig)) { 130 sanitized = xmallocz(strlen(path)); 131 if (remaining_prefix) 132 *remaining_prefix = 0; 133 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) { 134 free(sanitized); 135 return NULL; 136 } 137 if (abspath_part_inside_repo(sanitized)) { 138 free(sanitized); 139 return NULL; 140 } 141 } else { 142 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path); 143 if (remaining_prefix) 144 *remaining_prefix = len; 145 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) { 146 free(sanitized); 147 return NULL; 148 } 149 } 150 return sanitized; 151} 152 153char *prefix_path(const char *prefix, int len, const char *path) 154{ 155 char *r = prefix_path_gently(prefix, len, NULL, path); 156 if (!r) { 157 const char *hint_path = repo_get_work_tree(the_repository); 158 if (!hint_path) 159 hint_path = repo_get_git_dir(the_repository); 160 die(_("'%s' is outside repository at '%s'"), path, 161 absolute_path(hint_path)); 162 } 163 return r; 164} 165 166int path_inside_repo(const char *prefix, const char *path) 167{ 168 int len = prefix ? strlen(prefix) : 0; 169 char *r = prefix_path_gently(prefix, len, NULL, path); 170 if (r) { 171 free(r); 172 return 1; 173 } 174 return 0; 175} 176 177int check_filename(const char *prefix, const char *arg) 178{ 179 char *to_free = NULL; 180 struct stat st; 181 182 if (skip_prefix(arg, ":/", &arg)) { 183 if (!*arg) /* ":/" is root dir, always exists */ 184 return 1; 185 prefix = NULL; 186 } else if (skip_prefix(arg, ":!", &arg) || 187 skip_prefix(arg, ":^", &arg)) { 188 if (!*arg) /* excluding everything is silly, but allowed */ 189 return 1; 190 } 191 192 if (prefix) 193 arg = to_free = prefix_filename(prefix, arg); 194 195 if (!lstat(arg, &st)) { 196 free(to_free); 197 return 1; /* file exists */ 198 } 199 if (is_missing_file_error(errno)) { 200 free(to_free); 201 return 0; /* file does not exist */ 202 } 203 die_errno(_("failed to stat '%s'"), arg); 204} 205 206static void NORETURN die_verify_filename(struct repository *r, 207 const char *prefix, 208 const char *arg, 209 int diagnose_misspelt_rev) 210{ 211 if (!diagnose_misspelt_rev) 212 die(_("%s: no such path in the working tree.\n" 213 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."), 214 arg); 215 /* 216 * Saying "'(icase)foo' does not exist in the index" when the 217 * user gave us ":(icase)foo" is just stupid. A magic pathspec 218 * begins with a colon and is followed by a non-alnum; do not 219 * let maybe_die_on_misspelt_object_name() even trigger. 220 */ 221 if (!(arg[0] == ':' && !isalnum(arg[1]))) 222 maybe_die_on_misspelt_object_name(r, arg, prefix); 223 224 /* ... or fall back the most general message. */ 225 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n" 226 "Use '--' to separate paths from revisions, like this:\n" 227 "'git <command> [<revision>...] -- [<file>...]'"), arg); 228 229} 230 231/* 232 * Check for arguments that don't resolve as actual files, 233 * but which look sufficiently like pathspecs that we'll consider 234 * them such for the purposes of rev/pathspec DWIM parsing. 235 */ 236static int looks_like_pathspec(const char *arg) 237{ 238 const char *p; 239 int escaped = 0; 240 241 /* 242 * Wildcard characters imply the user is looking to match pathspecs 243 * that aren't in the filesystem. Note that this doesn't include 244 * backslash even though it's a glob special; by itself it doesn't 245 * cause any increase in the match. Likewise ignore backslash-escaped 246 * wildcard characters. 247 */ 248 for (p = arg; *p; p++) { 249 if (escaped) { 250 escaped = 0; 251 } else if (is_glob_special(*p)) { 252 if (*p == '\\') 253 escaped = 1; 254 else 255 return 1; 256 } 257 } 258 259 /* long-form pathspec magic */ 260 if (starts_with(arg, ":(")) 261 return 1; 262 263 return 0; 264} 265 266/* 267 * Verify a filename that we got as an argument for a pathspec 268 * entry. Note that a filename that begins with "-" never verifies 269 * as true, because even if such a filename were to exist, we want 270 * it to be preceded by the "--" marker (or we want the user to 271 * use a format like "./-filename") 272 * 273 * The "diagnose_misspelt_rev" is used to provide a user-friendly 274 * diagnosis when dying upon finding that "name" is not a pathname. 275 * If set to 1, the diagnosis will try to diagnose "name" as an 276 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis 277 * will only complain about an inexisting file. 278 * 279 * This function is typically called to check that a "file or rev" 280 * argument is unambiguous. In this case, the caller will want 281 * diagnose_misspelt_rev == 1 when verifying the first non-rev 282 * argument (which could have been a revision), and 283 * diagnose_misspelt_rev == 0 for the next ones (because we already 284 * saw a filename, there's not ambiguity anymore). 285 */ 286void verify_filename(const char *prefix, 287 const char *arg, 288 int diagnose_misspelt_rev) 289{ 290 if (*arg == '-') 291 die(_("option '%s' must come before non-option arguments"), arg); 292 if (looks_like_pathspec(arg) || check_filename(prefix, arg)) 293 return; 294 die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev); 295} 296 297/* 298 * Opposite of the above: the command line did not have -- marker 299 * and we parsed the arg as a refname. It should not be interpretable 300 * as a filename. 301 */ 302void verify_non_filename(const char *prefix, const char *arg) 303{ 304 if (!is_inside_work_tree() || is_inside_git_dir()) 305 return; 306 if (*arg == '-') 307 return; /* flag */ 308 if (!check_filename(prefix, arg)) 309 return; 310 die(_("ambiguous argument '%s': both revision and filename\n" 311 "Use '--' to separate paths from revisions, like this:\n" 312 "'git <command> [<revision>...] -- [<file>...]'"), arg); 313} 314 315int get_common_dir(struct strbuf *sb, const char *gitdir) 316{ 317 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT); 318 if (git_env_common_dir) { 319 strbuf_addstr(sb, git_env_common_dir); 320 return 1; 321 } else { 322 return get_common_dir_noenv(sb, gitdir); 323 } 324} 325 326int get_common_dir_noenv(struct strbuf *sb, const char *gitdir) 327{ 328 struct strbuf data = STRBUF_INIT; 329 struct strbuf path = STRBUF_INIT; 330 int ret = 0; 331 332 strbuf_addf(&path, "%s/commondir", gitdir); 333 if (file_exists(path.buf)) { 334 if (strbuf_read_file(&data, path.buf, 0) <= 0) 335 die_errno(_("failed to read %s"), path.buf); 336 while (data.len && (data.buf[data.len - 1] == '\n' || 337 data.buf[data.len - 1] == '\r')) 338 data.len--; 339 data.buf[data.len] = '\0'; 340 strbuf_reset(&path); 341 if (!is_absolute_path(data.buf)) 342 strbuf_addf(&path, "%s/", gitdir); 343 strbuf_addbuf(&path, &data); 344 strbuf_add_real_path(sb, path.buf); 345 ret = 1; 346 } else { 347 strbuf_addstr(sb, gitdir); 348 } 349 350 strbuf_release(&data); 351 strbuf_release(&path); 352 return ret; 353} 354 355static int validate_headref(const char *path) 356{ 357 struct stat st; 358 char buffer[256]; 359 const char *refname; 360 struct object_id oid; 361 int fd; 362 ssize_t len; 363 364 if (lstat(path, &st) < 0) 365 return -1; 366 367 /* Make sure it is a "refs/.." symlink */ 368 if (S_ISLNK(st.st_mode)) { 369 len = readlink(path, buffer, sizeof(buffer)-1); 370 if (len >= 5 && !memcmp("refs/", buffer, 5)) 371 return 0; 372 return -1; 373 } 374 375 /* 376 * Anything else, just open it and try to see if it is a symbolic ref. 377 */ 378 fd = open(path, O_RDONLY); 379 if (fd < 0) 380 return -1; 381 len = read_in_full(fd, buffer, sizeof(buffer)-1); 382 close(fd); 383 384 if (len < 0) 385 return -1; 386 buffer[len] = '\0'; 387 388 /* 389 * Is it a symbolic ref? 390 */ 391 if (skip_prefix(buffer, "ref:", &refname)) { 392 while (isspace(*refname)) 393 refname++; 394 if (starts_with(refname, "refs/")) 395 return 0; 396 } 397 398 /* 399 * Is this a detached HEAD? 400 */ 401 if (get_oid_hex_any(buffer, &oid) != GIT_HASH_UNKNOWN) 402 return 0; 403 404 return -1; 405} 406 407/* 408 * Test if it looks like we're at a git directory. 409 * We want to see: 410 * 411 * - either an objects/ directory _or_ the proper 412 * GIT_OBJECT_DIRECTORY environment variable 413 * - a refs/ directory 414 * - either a HEAD symlink or a HEAD file that is formatted as 415 * a proper "ref:", or a regular file HEAD that has a properly 416 * formatted sha1 object name. 417 */ 418int is_git_directory(const char *suspect) 419{ 420 struct strbuf path = STRBUF_INIT; 421 int ret = 0; 422 size_t len; 423 424 /* Check worktree-related signatures */ 425 strbuf_addstr(&path, suspect); 426 strbuf_complete(&path, '/'); 427 strbuf_addstr(&path, "HEAD"); 428 if (validate_headref(path.buf)) 429 goto done; 430 431 strbuf_reset(&path); 432 get_common_dir(&path, suspect); 433 len = path.len; 434 435 /* Check non-worktree-related signatures */ 436 if (getenv(DB_ENVIRONMENT)) { 437 if (access(getenv(DB_ENVIRONMENT), X_OK)) 438 goto done; 439 } 440 else { 441 strbuf_setlen(&path, len); 442 strbuf_addstr(&path, "/objects"); 443 if (access(path.buf, X_OK)) 444 goto done; 445 } 446 447 strbuf_setlen(&path, len); 448 strbuf_addstr(&path, "/refs"); 449 if (access(path.buf, X_OK)) 450 goto done; 451 452 ret = 1; 453done: 454 strbuf_release(&path); 455 return ret; 456} 457 458int is_nonbare_repository_dir(struct strbuf *path) 459{ 460 int ret = 0; 461 int gitfile_error; 462 size_t orig_path_len = path->len; 463 assert(orig_path_len != 0); 464 strbuf_complete(path, '/'); 465 strbuf_addstr(path, ".git"); 466 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf)) 467 ret = 1; 468 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED || 469 gitfile_error == READ_GITFILE_ERR_READ_FAILED) 470 ret = 1; 471 strbuf_setlen(path, orig_path_len); 472 return ret; 473} 474 475int is_inside_git_dir(void) 476{ 477 if (inside_git_dir < 0) 478 inside_git_dir = is_inside_dir(repo_get_git_dir(the_repository)); 479 return inside_git_dir; 480} 481 482int is_inside_work_tree(void) 483{ 484 if (inside_work_tree < 0) 485 inside_work_tree = is_inside_dir(repo_get_work_tree(the_repository)); 486 return inside_work_tree; 487} 488 489void setup_work_tree(void) 490{ 491 const char *work_tree; 492 static int initialized = 0; 493 494 if (initialized) 495 return; 496 497 if (work_tree_config_is_bogus) 498 die(_("unable to set up work tree using invalid config")); 499 500 work_tree = repo_get_work_tree(the_repository); 501 if (!work_tree || chdir_notify(work_tree)) 502 die(_("this operation must be run in a work tree")); 503 504 /* 505 * Make sure subsequent git processes find correct worktree 506 * if $GIT_WORK_TREE is set relative 507 */ 508 if (getenv(GIT_WORK_TREE_ENVIRONMENT)) 509 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1); 510 511 initialized = 1; 512} 513 514static void setup_original_cwd(void) 515{ 516 struct strbuf tmp = STRBUF_INIT; 517 const char *worktree = NULL; 518 int offset = -1; 519 520 if (!tmp_original_cwd) 521 return; 522 523 /* 524 * startup_info->original_cwd points to the current working 525 * directory we inherited from our parent process, which is a 526 * directory we want to avoid removing. 527 * 528 * For convenience, we would like to have the path relative to the 529 * worktree instead of an absolute path. 530 * 531 * Yes, startup_info->original_cwd is usually the same as 'prefix', 532 * but differs in two ways: 533 * - prefix has a trailing '/' 534 * - if the user passes '-C' to git, that modifies the prefix but 535 * not startup_info->original_cwd. 536 */ 537 538 /* Normalize the directory */ 539 if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) { 540 trace2_data_string("setup", the_repository, 541 "realpath-path", tmp_original_cwd); 542 trace2_data_string("setup", the_repository, 543 "realpath-failure", strerror(errno)); 544 free((char*)tmp_original_cwd); 545 tmp_original_cwd = NULL; 546 return; 547 } 548 549 free((char*)tmp_original_cwd); 550 tmp_original_cwd = NULL; 551 startup_info->original_cwd = strbuf_detach(&tmp, NULL); 552 553 /* 554 * Get our worktree; we only protect the current working directory 555 * if it's in the worktree. 556 */ 557 worktree = repo_get_work_tree(the_repository); 558 if (!worktree) 559 goto no_prevention_needed; 560 561 offset = dir_inside_of(startup_info->original_cwd, worktree); 562 if (offset >= 0) { 563 /* 564 * If startup_info->original_cwd == worktree, that is already 565 * protected and we don't need original_cwd as a secondary 566 * protection measure. 567 */ 568 if (!*(startup_info->original_cwd + offset)) 569 goto no_prevention_needed; 570 571 /* 572 * original_cwd was inside worktree; precompose it just as 573 * we do prefix so that built up paths will match 574 */ 575 startup_info->original_cwd = \ 576 precompose_string_if_needed(startup_info->original_cwd 577 + offset); 578 return; 579 } 580 581no_prevention_needed: 582 free((char*)startup_info->original_cwd); 583 startup_info->original_cwd = NULL; 584} 585 586static int read_worktree_config(const char *var, const char *value, 587 const struct config_context *ctx UNUSED, 588 void *vdata) 589{ 590 struct repository_format *data = vdata; 591 592 if (strcmp(var, "core.bare") == 0) { 593 data->is_bare = git_config_bool(var, value); 594 } else if (strcmp(var, "core.worktree") == 0) { 595 if (!value) 596 return config_error_nonbool(var); 597 free(data->work_tree); 598 data->work_tree = xstrdup(value); 599 } 600 return 0; 601} 602 603enum extension_result { 604 EXTENSION_ERROR = -1, /* compatible with error(), etc */ 605 EXTENSION_UNKNOWN = 0, 606 EXTENSION_OK = 1 607}; 608 609/* 610 * Do not add new extensions to this function. It handles extensions which are 611 * respected even in v0-format repositories for historical compatibility. 612 */ 613static enum extension_result handle_extension_v0(const char *var, 614 const char *value, 615 const char *ext, 616 struct repository_format *data) 617{ 618 if (!strcmp(ext, "noop")) { 619 return EXTENSION_OK; 620 } else if (!strcmp(ext, "preciousobjects")) { 621 data->precious_objects = git_config_bool(var, value); 622 return EXTENSION_OK; 623 } else if (!strcmp(ext, "partialclone")) { 624 if (!value) 625 return config_error_nonbool(var); 626 data->partial_clone = xstrdup(value); 627 return EXTENSION_OK; 628 } else if (!strcmp(ext, "worktreeconfig")) { 629 data->worktree_config = git_config_bool(var, value); 630 return EXTENSION_OK; 631 } 632 633 return EXTENSION_UNKNOWN; 634} 635 636/* 637 * Record any new extensions in this function. 638 */ 639static enum extension_result handle_extension(const char *var, 640 const char *value, 641 const char *ext, 642 struct repository_format *data) 643{ 644 if (!strcmp(ext, "noop-v1")) { 645 return EXTENSION_OK; 646 } else if (!strcmp(ext, "objectformat")) { 647 int format; 648 649 if (!value) 650 return config_error_nonbool(var); 651 format = hash_algo_by_name(value); 652 if (format == GIT_HASH_UNKNOWN) 653 return error(_("invalid value for '%s': '%s'"), 654 "extensions.objectformat", value); 655 data->hash_algo = format; 656 return EXTENSION_OK; 657 } else if (!strcmp(ext, "compatobjectformat")) { 658 struct string_list_item *item; 659 int format; 660 661 if (!value) 662 return config_error_nonbool(var); 663 format = hash_algo_by_name(value); 664 if (format == GIT_HASH_UNKNOWN) 665 return error(_("invalid value for '%s': '%s'"), 666 "extensions.compatobjectformat", value); 667 /* For now only support compatObjectFormat being specified once. */ 668 for_each_string_list_item(item, &data->v1_only_extensions) { 669 if (!strcmp(item->string, "compatobjectformat")) 670 return error(_("'%s' already specified as '%s'"), 671 "extensions.compatobjectformat", 672 hash_algos[data->compat_hash_algo].name); 673 } 674 data->compat_hash_algo = format; 675 return EXTENSION_OK; 676 } else if (!strcmp(ext, "refstorage")) { 677 unsigned int format; 678 679 if (!value) 680 return config_error_nonbool(var); 681 format = ref_storage_format_by_name(value); 682 if (format == REF_STORAGE_FORMAT_UNKNOWN) 683 return error(_("invalid value for '%s': '%s'"), 684 "extensions.refstorage", value); 685 data->ref_storage_format = format; 686 return EXTENSION_OK; 687 } else if (!strcmp(ext, "relativeworktrees")) { 688 data->relative_worktrees = git_config_bool(var, value); 689 return EXTENSION_OK; 690 } 691 return EXTENSION_UNKNOWN; 692} 693 694static int check_repo_format(const char *var, const char *value, 695 const struct config_context *ctx, void *vdata) 696{ 697 struct repository_format *data = vdata; 698 const char *ext; 699 700 if (strcmp(var, "core.repositoryformatversion") == 0) 701 data->version = git_config_int(var, value, ctx->kvi); 702 else if (skip_prefix(var, "extensions.", &ext)) { 703 switch (handle_extension_v0(var, value, ext, data)) { 704 case EXTENSION_ERROR: 705 return -1; 706 case EXTENSION_OK: 707 return 0; 708 case EXTENSION_UNKNOWN: 709 break; 710 } 711 712 switch (handle_extension(var, value, ext, data)) { 713 case EXTENSION_ERROR: 714 return -1; 715 case EXTENSION_OK: 716 string_list_append(&data->v1_only_extensions, ext); 717 return 0; 718 case EXTENSION_UNKNOWN: 719 string_list_append(&data->unknown_extensions, ext); 720 return 0; 721 } 722 } 723 724 return read_worktree_config(var, value, ctx, vdata); 725} 726 727static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok) 728{ 729 struct strbuf sb = STRBUF_INIT; 730 struct strbuf err = STRBUF_INIT; 731 int has_common; 732 733 has_common = get_common_dir(&sb, gitdir); 734 strbuf_addstr(&sb, "/config"); 735 read_repository_format(candidate, sb.buf); 736 strbuf_release(&sb); 737 738 /* 739 * For historical use of check_repository_format() in git-init, 740 * we treat a missing config as a silent "ok", even when nongit_ok 741 * is unset. 742 */ 743 if (candidate->version < 0) 744 return 0; 745 746 if (verify_repository_format(candidate, &err) < 0) { 747 if (nongit_ok) { 748 warning("%s", err.buf); 749 strbuf_release(&err); 750 *nongit_ok = -1; 751 return -1; 752 } 753 die("%s", err.buf); 754 } 755 756 the_repository->repository_format_precious_objects = candidate->precious_objects; 757 758 string_list_clear(&candidate->unknown_extensions, 0); 759 string_list_clear(&candidate->v1_only_extensions, 0); 760 761 if (candidate->worktree_config) { 762 /* 763 * pick up core.bare and core.worktree from per-worktree 764 * config if present 765 */ 766 strbuf_addf(&sb, "%s/config.worktree", gitdir); 767 git_config_from_file(read_worktree_config, sb.buf, candidate); 768 strbuf_release(&sb); 769 has_common = 0; 770 } 771 772 if (!has_common) { 773 if (candidate->is_bare != -1) { 774 is_bare_repository_cfg = candidate->is_bare; 775 if (is_bare_repository_cfg == 1) 776 inside_work_tree = -1; 777 } 778 if (candidate->work_tree) { 779 free(git_work_tree_cfg); 780 git_work_tree_cfg = xstrdup(candidate->work_tree); 781 inside_work_tree = -1; 782 } 783 } 784 785 return 0; 786} 787 788int upgrade_repository_format(int target_version) 789{ 790 struct strbuf sb = STRBUF_INIT; 791 struct strbuf err = STRBUF_INIT; 792 struct strbuf repo_version = STRBUF_INIT; 793 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT; 794 int ret; 795 796 repo_common_path_append(the_repository, &sb, "config"); 797 read_repository_format(&repo_fmt, sb.buf); 798 strbuf_release(&sb); 799 800 if (repo_fmt.version >= target_version) { 801 ret = 0; 802 goto out; 803 } 804 805 if (verify_repository_format(&repo_fmt, &err) < 0) { 806 ret = error("cannot upgrade repository format from %d to %d: %s", 807 repo_fmt.version, target_version, err.buf); 808 goto out; 809 } 810 if (!repo_fmt.version && repo_fmt.unknown_extensions.nr) { 811 ret = error("cannot upgrade repository format: " 812 "unknown extension %s", 813 repo_fmt.unknown_extensions.items[0].string); 814 goto out; 815 } 816 817 strbuf_addf(&repo_version, "%d", target_version); 818 repo_config_set(the_repository, "core.repositoryformatversion", repo_version.buf); 819 820 ret = 1; 821 822out: 823 clear_repository_format(&repo_fmt); 824 strbuf_release(&repo_version); 825 strbuf_release(&err); 826 return ret; 827} 828 829static void init_repository_format(struct repository_format *format) 830{ 831 const struct repository_format fresh = REPOSITORY_FORMAT_INIT; 832 833 memcpy(format, &fresh, sizeof(fresh)); 834} 835 836int read_repository_format(struct repository_format *format, const char *path) 837{ 838 clear_repository_format(format); 839 format->hash_algo = GIT_HASH_SHA1_LEGACY; 840 git_config_from_file(check_repo_format, path, format); 841 if (format->version == -1) { 842 clear_repository_format(format); 843 format->hash_algo = GIT_HASH_SHA1_LEGACY; 844 } 845 return format->version; 846} 847 848void clear_repository_format(struct repository_format *format) 849{ 850 string_list_clear(&format->unknown_extensions, 0); 851 string_list_clear(&format->v1_only_extensions, 0); 852 free(format->work_tree); 853 free(format->partial_clone); 854 init_repository_format(format); 855} 856 857int verify_repository_format(const struct repository_format *format, 858 struct strbuf *err) 859{ 860 if (GIT_REPO_VERSION_READ < format->version) { 861 strbuf_addf(err, _("Expected git repo version <= %d, found %d"), 862 GIT_REPO_VERSION_READ, format->version); 863 return -1; 864 } 865 866 if (format->version >= 1 && format->unknown_extensions.nr) { 867 int i; 868 869 strbuf_addstr(err, Q_("unknown repository extension found:", 870 "unknown repository extensions found:", 871 format->unknown_extensions.nr)); 872 873 for (i = 0; i < format->unknown_extensions.nr; i++) 874 strbuf_addf(err, "\n\t%s", 875 format->unknown_extensions.items[i].string); 876 return -1; 877 } 878 879 if (format->version == 0 && format->v1_only_extensions.nr) { 880 int i; 881 882 strbuf_addstr(err, 883 Q_("repo version is 0, but v1-only extension found:", 884 "repo version is 0, but v1-only extensions found:", 885 format->v1_only_extensions.nr)); 886 887 for (i = 0; i < format->v1_only_extensions.nr; i++) 888 strbuf_addf(err, "\n\t%s", 889 format->v1_only_extensions.items[i].string); 890 return -1; 891 } 892 893 return 0; 894} 895 896void read_gitfile_error_die(int error_code, const char *path, const char *dir) 897{ 898 switch (error_code) { 899 case READ_GITFILE_ERR_STAT_FAILED: 900 case READ_GITFILE_ERR_NOT_A_FILE: 901 /* non-fatal; follow return path */ 902 break; 903 case READ_GITFILE_ERR_OPEN_FAILED: 904 die_errno(_("error opening '%s'"), path); 905 case READ_GITFILE_ERR_TOO_LARGE: 906 die(_("too large to be a .git file: '%s'"), path); 907 case READ_GITFILE_ERR_READ_FAILED: 908 die(_("error reading %s"), path); 909 case READ_GITFILE_ERR_INVALID_FORMAT: 910 die(_("invalid gitfile format: %s"), path); 911 case READ_GITFILE_ERR_NO_PATH: 912 die(_("no path in gitfile: %s"), path); 913 case READ_GITFILE_ERR_NOT_A_REPO: 914 die(_("not a git repository: %s"), dir); 915 default: 916 BUG("unknown error code"); 917 } 918} 919 920/* 921 * Try to read the location of the git directory from the .git file, 922 * return path to git directory if found. The return value comes from 923 * a shared buffer. 924 * 925 * On failure, if return_error_code is not NULL, return_error_code 926 * will be set to an error code and NULL will be returned. If 927 * return_error_code is NULL the function will die instead (for most 928 * cases). 929 */ 930const char *read_gitfile_gently(const char *path, int *return_error_code) 931{ 932 const int max_file_size = 1 << 20; /* 1MB */ 933 int error_code = 0; 934 char *buf = NULL; 935 char *dir = NULL; 936 const char *slash; 937 struct stat st; 938 int fd; 939 ssize_t len; 940 static struct strbuf realpath = STRBUF_INIT; 941 942 if (stat(path, &st)) { 943 /* NEEDSWORK: discern between ENOENT vs other errors */ 944 error_code = READ_GITFILE_ERR_STAT_FAILED; 945 goto cleanup_return; 946 } 947 if (!S_ISREG(st.st_mode)) { 948 error_code = READ_GITFILE_ERR_NOT_A_FILE; 949 goto cleanup_return; 950 } 951 if (st.st_size > max_file_size) { 952 error_code = READ_GITFILE_ERR_TOO_LARGE; 953 goto cleanup_return; 954 } 955 fd = open(path, O_RDONLY); 956 if (fd < 0) { 957 error_code = READ_GITFILE_ERR_OPEN_FAILED; 958 goto cleanup_return; 959 } 960 buf = xmallocz(st.st_size); 961 len = read_in_full(fd, buf, st.st_size); 962 close(fd); 963 if (len != st.st_size) { 964 error_code = READ_GITFILE_ERR_READ_FAILED; 965 goto cleanup_return; 966 } 967 if (!starts_with(buf, "gitdir: ")) { 968 error_code = READ_GITFILE_ERR_INVALID_FORMAT; 969 goto cleanup_return; 970 } 971 while (buf[len - 1] == '\n' || buf[len - 1] == '\r') 972 len--; 973 if (len < 9) { 974 error_code = READ_GITFILE_ERR_NO_PATH; 975 goto cleanup_return; 976 } 977 buf[len] = '\0'; 978 dir = buf + 8; 979 980 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) { 981 size_t pathlen = slash+1 - path; 982 dir = xstrfmt("%.*s%.*s", (int)pathlen, path, 983 (int)(len - 8), buf + 8); 984 free(buf); 985 buf = dir; 986 } 987 if (!is_git_directory(dir)) { 988 error_code = READ_GITFILE_ERR_NOT_A_REPO; 989 goto cleanup_return; 990 } 991 992 strbuf_realpath(&realpath, dir, 1); 993 path = realpath.buf; 994 995cleanup_return: 996 if (return_error_code) 997 *return_error_code = error_code; 998 else if (error_code) 999 read_gitfile_error_die(error_code, path, dir); 1000 1001 free(buf); 1002 return error_code ? NULL : path; 1003} 1004 1005static const char *setup_explicit_git_dir(const char *gitdirenv, 1006 struct strbuf *cwd, 1007 struct repository_format *repo_fmt, 1008 int *nongit_ok) 1009{ 1010 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT); 1011 const char *worktree; 1012 char *gitfile; 1013 int offset; 1014 1015 if (PATH_MAX - 40 < strlen(gitdirenv)) 1016 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT); 1017 1018 gitfile = (char*)read_gitfile(gitdirenv); 1019 if (gitfile) { 1020 gitfile = xstrdup(gitfile); 1021 gitdirenv = gitfile; 1022 } 1023 1024 if (!is_git_directory(gitdirenv)) { 1025 if (nongit_ok) { 1026 *nongit_ok = 1; 1027 free(gitfile); 1028 return NULL; 1029 } 1030 die(_("not a git repository: '%s'"), gitdirenv); 1031 } 1032 1033 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) { 1034 free(gitfile); 1035 return NULL; 1036 } 1037 1038 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */ 1039 if (work_tree_env) 1040 set_git_work_tree(work_tree_env); 1041 else if (is_bare_repository_cfg > 0) { 1042 if (git_work_tree_cfg) { 1043 /* #22.2, #30 */ 1044 warning("core.bare and core.worktree do not make sense"); 1045 work_tree_config_is_bogus = 1; 1046 } 1047 1048 /* #18, #26 */ 1049 set_git_dir(gitdirenv, 0); 1050 free(gitfile); 1051 return NULL; 1052 } 1053 else if (git_work_tree_cfg) { /* #6, #14 */ 1054 if (is_absolute_path(git_work_tree_cfg)) 1055 set_git_work_tree(git_work_tree_cfg); 1056 else { 1057 char *core_worktree; 1058 if (chdir(gitdirenv)) 1059 die_errno(_("cannot chdir to '%s'"), gitdirenv); 1060 if (chdir(git_work_tree_cfg)) 1061 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg); 1062 core_worktree = xgetcwd(); 1063 if (chdir(cwd->buf)) 1064 die_errno(_("cannot come back to cwd")); 1065 set_git_work_tree(core_worktree); 1066 free(core_worktree); 1067 } 1068 } 1069 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) { 1070 /* #16d */ 1071 set_git_dir(gitdirenv, 0); 1072 free(gitfile); 1073 return NULL; 1074 } 1075 else /* #2, #10 */ 1076 set_git_work_tree("."); 1077 1078 /* set_git_work_tree() must have been called by now */ 1079 worktree = repo_get_work_tree(the_repository); 1080 1081 /* both repo_get_work_tree() and cwd are already normalized */ 1082 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */ 1083 set_git_dir(gitdirenv, 0); 1084 free(gitfile); 1085 return NULL; 1086 } 1087 1088 offset = dir_inside_of(cwd->buf, worktree); 1089 if (offset >= 0) { /* cwd inside worktree? */ 1090 set_git_dir(gitdirenv, 1); 1091 if (chdir(worktree)) 1092 die_errno(_("cannot chdir to '%s'"), worktree); 1093 strbuf_addch(cwd, '/'); 1094 free(gitfile); 1095 return cwd->buf + offset; 1096 } 1097 1098 /* cwd outside worktree */ 1099 set_git_dir(gitdirenv, 0); 1100 free(gitfile); 1101 return NULL; 1102} 1103 1104static const char *setup_discovered_git_dir(const char *gitdir, 1105 struct strbuf *cwd, int offset, 1106 struct repository_format *repo_fmt, 1107 int *nongit_ok) 1108{ 1109 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok)) 1110 return NULL; 1111 1112 /* --work-tree is set without --git-dir; use discovered one */ 1113 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) { 1114 char *to_free = NULL; 1115 const char *ret; 1116 1117 if (offset != cwd->len && !is_absolute_path(gitdir)) 1118 gitdir = to_free = real_pathdup(gitdir, 1); 1119 if (chdir(cwd->buf)) 1120 die_errno(_("cannot come back to cwd")); 1121 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok); 1122 free(to_free); 1123 return ret; 1124 } 1125 1126 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */ 1127 if (is_bare_repository_cfg > 0) { 1128 set_git_dir(gitdir, (offset != cwd->len)); 1129 if (chdir(cwd->buf)) 1130 die_errno(_("cannot come back to cwd")); 1131 return NULL; 1132 } 1133 1134 /* #0, #1, #5, #8, #9, #12, #13 */ 1135 set_git_work_tree("."); 1136 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT)) 1137 set_git_dir(gitdir, 0); 1138 inside_git_dir = 0; 1139 inside_work_tree = 1; 1140 if (offset >= cwd->len) 1141 return NULL; 1142 1143 /* Make "offset" point past the '/' (already the case for root dirs) */ 1144 if (offset != offset_1st_component(cwd->buf)) 1145 offset++; 1146 /* Add a '/' at the end */ 1147 strbuf_addch(cwd, '/'); 1148 return cwd->buf + offset; 1149} 1150 1151/* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */ 1152static const char *setup_bare_git_dir(struct strbuf *cwd, int offset, 1153 struct repository_format *repo_fmt, 1154 int *nongit_ok) 1155{ 1156 int root_len; 1157 1158 if (check_repository_format_gently(".", repo_fmt, nongit_ok)) 1159 return NULL; 1160 1161 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1); 1162 1163 /* --work-tree is set without --git-dir; use discovered one */ 1164 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) { 1165 static const char *gitdir; 1166 1167 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset); 1168 if (chdir(cwd->buf)) 1169 die_errno(_("cannot come back to cwd")); 1170 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok); 1171 } 1172 1173 inside_git_dir = 1; 1174 inside_work_tree = 0; 1175 if (offset != cwd->len) { 1176 if (chdir(cwd->buf)) 1177 die_errno(_("cannot come back to cwd")); 1178 root_len = offset_1st_component(cwd->buf); 1179 strbuf_setlen(cwd, offset > root_len ? offset : root_len); 1180 set_git_dir(cwd->buf, 0); 1181 } 1182 else 1183 set_git_dir(".", 0); 1184 return NULL; 1185} 1186 1187static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len) 1188{ 1189 struct stat buf; 1190 if (stat(path, &buf)) { 1191 die_errno(_("failed to stat '%*s%s%s'"), 1192 prefix_len, 1193 prefix ? prefix : "", 1194 prefix ? "/" : "", path); 1195 } 1196 return buf.st_dev; 1197} 1198 1199/* 1200 * A "string_list_each_func_t" function that canonicalizes an entry 1201 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or 1202 * discards it if unusable. The presence of an empty entry in 1203 * GIT_CEILING_DIRECTORIES turns off canonicalization for all 1204 * subsequent entries. 1205 */ 1206static int canonicalize_ceiling_entry(struct string_list_item *item, 1207 void *cb_data) 1208{ 1209 int *empty_entry_found = cb_data; 1210 char *ceil = item->string; 1211 1212 if (!*ceil) { 1213 *empty_entry_found = 1; 1214 return 0; 1215 } else if (!is_absolute_path(ceil)) { 1216 return 0; 1217 } else if (*empty_entry_found) { 1218 /* Keep entry but do not canonicalize it */ 1219 return 1; 1220 } else { 1221 char *real_path = real_pathdup(ceil, 0); 1222 if (!real_path) { 1223 return 0; 1224 } 1225 free(item->string); 1226 item->string = real_path; 1227 return 1; 1228 } 1229} 1230 1231struct safe_directory_data { 1232 char *path; 1233 int is_safe; 1234}; 1235 1236static int safe_directory_cb(const char *key, const char *value, 1237 const struct config_context *ctx UNUSED, void *d) 1238{ 1239 struct safe_directory_data *data = d; 1240 1241 if (strcmp(key, "safe.directory")) 1242 return 0; 1243 1244 if (!value || !*value) { 1245 data->is_safe = 0; 1246 } else if (!strcmp(value, "*")) { 1247 data->is_safe = 1; 1248 } else { 1249 char *allowed = NULL; 1250 1251 if (!git_config_pathname(&allowed, key, value)) { 1252 char *normalized = NULL; 1253 1254 /* 1255 * Setting safe.directory to a non-absolute path 1256 * makes little sense---it won't be relative to 1257 * the configuration file the item is defined in. 1258 * Except for ".", which means "if we are at the top 1259 * level of a repository, then it is OK", which is 1260 * slightly tighter than "*" that allows discovery. 1261 */ 1262 if (!is_absolute_path(allowed) && strcmp(allowed, ".")) { 1263 warning(_("safe.directory '%s' not absolute"), 1264 allowed); 1265 goto next; 1266 } 1267 1268 /* 1269 * A .gitconfig in $HOME may be shared across 1270 * different machines and safe.directory entries 1271 * may or may not exist as paths on all of these 1272 * machines. In other words, it is not a warning 1273 * worthy event when there is no such path on this 1274 * machine---the entry may be useful elsewhere. 1275 */ 1276 normalized = real_pathdup(allowed, 0); 1277 if (!normalized) 1278 goto next; 1279 1280 if (ends_with(normalized, "/*")) { 1281 size_t len = strlen(normalized); 1282 if (!fspathncmp(normalized, data->path, len - 1)) 1283 data->is_safe = 1; 1284 } else if (!fspathcmp(data->path, normalized)) { 1285 data->is_safe = 1; 1286 } 1287 next: 1288 free(normalized); 1289 free(allowed); 1290 } 1291 } 1292 1293 return 0; 1294} 1295 1296/* 1297 * Check if a repository is safe, by verifying the ownership of the 1298 * worktree (if any), the git directory, and the gitfile (if any). 1299 * 1300 * Exemptions for known-safe repositories can be added via `safe.directory` 1301 * config settings; for non-bare repositories, their worktree needs to be 1302 * added, for bare ones their git directory. 1303 */ 1304static int ensure_valid_ownership(const char *gitfile, 1305 const char *worktree, const char *gitdir, 1306 struct strbuf *report) 1307{ 1308 struct safe_directory_data data = { 0 }; 1309 1310 if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) && 1311 (!gitfile || is_path_owned_by_current_user(gitfile, report)) && 1312 (!worktree || is_path_owned_by_current_user(worktree, report)) && 1313 (!gitdir || is_path_owned_by_current_user(gitdir, report))) 1314 return 1; 1315 1316 /* 1317 * normalize the data.path for comparison with normalized paths 1318 * that come from the configuration file. The path is unsafe 1319 * if it cannot be normalized. 1320 */ 1321 data.path = real_pathdup(worktree ? worktree : gitdir, 0); 1322 if (!data.path) 1323 return 0; 1324 1325 /* 1326 * data.path is the "path" that identifies the repository and it is 1327 * constant regardless of what failed above. data.is_safe should be 1328 * initialized to false, and might be changed by the callback. 1329 */ 1330 git_protected_config(safe_directory_cb, &data); 1331 1332 free(data.path); 1333 return data.is_safe; 1334} 1335 1336void die_upon_dubious_ownership(const char *gitfile, const char *worktree, 1337 const char *gitdir) 1338{ 1339 struct strbuf report = STRBUF_INIT, quoted = STRBUF_INIT; 1340 const char *path; 1341 1342 if (ensure_valid_ownership(gitfile, worktree, gitdir, &report)) 1343 return; 1344 1345 strbuf_complete(&report, '\n'); 1346 path = gitfile ? gitfile : gitdir; 1347 sq_quote_buf_pretty(&quoted, path); 1348 1349 die(_("detected dubious ownership in repository at '%s'\n" 1350 "%s" 1351 "To add an exception for this directory, call:\n" 1352 "\n" 1353 "\tgit config --global --add safe.directory %s"), 1354 path, report.buf, quoted.buf); 1355} 1356 1357static int allowed_bare_repo_cb(const char *key, const char *value, 1358 const struct config_context *ctx UNUSED, 1359 void *d) 1360{ 1361 enum allowed_bare_repo *allowed_bare_repo = d; 1362 1363 if (strcasecmp(key, "safe.bareRepository")) 1364 return 0; 1365 1366 if (!strcmp(value, "explicit")) { 1367 *allowed_bare_repo = ALLOWED_BARE_REPO_EXPLICIT; 1368 return 0; 1369 } 1370 if (!strcmp(value, "all")) { 1371 *allowed_bare_repo = ALLOWED_BARE_REPO_ALL; 1372 return 0; 1373 } 1374 return -1; 1375} 1376 1377static enum allowed_bare_repo get_allowed_bare_repo(void) 1378{ 1379 enum allowed_bare_repo result = ALLOWED_BARE_REPO_ALL; 1380 git_protected_config(allowed_bare_repo_cb, &result); 1381 return result; 1382} 1383 1384static const char *allowed_bare_repo_to_string( 1385 enum allowed_bare_repo allowed_bare_repo) 1386{ 1387 switch (allowed_bare_repo) { 1388 case ALLOWED_BARE_REPO_EXPLICIT: 1389 return "explicit"; 1390 case ALLOWED_BARE_REPO_ALL: 1391 return "all"; 1392 default: 1393 BUG("invalid allowed_bare_repo %d", 1394 allowed_bare_repo); 1395 } 1396 return NULL; 1397} 1398 1399static int is_implicit_bare_repo(const char *path) 1400{ 1401 /* 1402 * what we found is a ".git" directory at the root of 1403 * the working tree. 1404 */ 1405 if (ends_with_path_components(path, ".git")) 1406 return 1; 1407 1408 /* 1409 * we are inside $GIT_DIR of a secondary worktree of a 1410 * non-bare repository. 1411 */ 1412 if (strstr(path, "/.git/worktrees/")) 1413 return 1; 1414 1415 /* 1416 * we are inside $GIT_DIR of a worktree of a non-embedded 1417 * submodule, whose superproject is not a bare repository. 1418 */ 1419 if (strstr(path, "/.git/modules/")) 1420 return 1; 1421 1422 return 0; 1423} 1424 1425/* 1426 * We cannot decide in this function whether we are in the work tree or 1427 * not, since the config can only be read _after_ this function was called. 1428 * 1429 * Also, we avoid changing any global state (such as the current working 1430 * directory) to allow early callers. 1431 * 1432 * The directory where the search should start needs to be passed in via the 1433 * `dir` parameter; upon return, the `dir` buffer will contain the path of 1434 * the directory where the search ended, and `gitdir` will contain the path of 1435 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it 1436 * is relative to `dir` (i.e. *not* necessarily the cwd). 1437 */ 1438static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir, 1439 struct strbuf *gitdir, 1440 struct strbuf *report, 1441 int die_on_error) 1442{ 1443 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT); 1444 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP; 1445 const char *gitdirenv; 1446 int ceil_offset = -1, min_offset = offset_1st_component(dir->buf); 1447 dev_t current_device = 0; 1448 int one_filesystem = 1; 1449 1450 /* 1451 * If GIT_DIR is set explicitly, we're not going 1452 * to do any discovery, but we still do repository 1453 * validation. 1454 */ 1455 gitdirenv = getenv(GIT_DIR_ENVIRONMENT); 1456 if (gitdirenv) { 1457 strbuf_addstr(gitdir, gitdirenv); 1458 return GIT_DIR_EXPLICIT; 1459 } 1460 1461 if (env_ceiling_dirs) { 1462 int empty_entry_found = 0; 1463 static const char path_sep[] = { PATH_SEP, '\0' }; 1464 1465 string_list_split(&ceiling_dirs, env_ceiling_dirs, path_sep, -1); 1466 filter_string_list(&ceiling_dirs, 0, 1467 canonicalize_ceiling_entry, &empty_entry_found); 1468 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs); 1469 string_list_clear(&ceiling_dirs, 0); 1470 } 1471 1472 if (ceil_offset < 0) 1473 ceil_offset = min_offset - 2; 1474 1475 if (min_offset && min_offset == dir->len && 1476 !is_dir_sep(dir->buf[min_offset - 1])) { 1477 strbuf_addch(dir, '/'); 1478 min_offset++; 1479 } 1480 1481 /* 1482 * Test in the following order (relative to the dir): 1483 * - .git (file containing "gitdir: <path>") 1484 * - .git/ 1485 * - ./ (bare) 1486 * - ../.git 1487 * - ../.git/ 1488 * - ../ (bare) 1489 * - ../../.git 1490 * etc. 1491 */ 1492 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0); 1493 if (one_filesystem) 1494 current_device = get_device_or_die(dir->buf, NULL, 0); 1495 for (;;) { 1496 int offset = dir->len, error_code = 0; 1497 char *gitdir_path = NULL; 1498 char *gitfile = NULL; 1499 1500 if (offset > min_offset) 1501 strbuf_addch(dir, '/'); 1502 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT); 1503 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ? 1504 NULL : &error_code); 1505 if (!gitdirenv) { 1506 if (die_on_error || 1507 error_code == READ_GITFILE_ERR_NOT_A_FILE) { 1508 /* NEEDSWORK: fail if .git is not file nor dir */ 1509 if (is_git_directory(dir->buf)) { 1510 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT; 1511 gitdir_path = xstrdup(dir->buf); 1512 } 1513 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED) 1514 return GIT_DIR_INVALID_GITFILE; 1515 } else 1516 gitfile = xstrdup(dir->buf); 1517 /* 1518 * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT 1519 * to check that directory for a repository. 1520 * Now trim that tentative addition away, because we want to 1521 * focus on the real directory we are in. 1522 */ 1523 strbuf_setlen(dir, offset); 1524 if (gitdirenv) { 1525 enum discovery_result ret; 1526 const char *gitdir_candidate = 1527 gitdir_path ? gitdir_path : gitdirenv; 1528 1529 if (ensure_valid_ownership(gitfile, dir->buf, 1530 gitdir_candidate, report)) { 1531 strbuf_addstr(gitdir, gitdirenv); 1532 ret = GIT_DIR_DISCOVERED; 1533 } else 1534 ret = GIT_DIR_INVALID_OWNERSHIP; 1535 1536 /* 1537 * Earlier, during discovery, we might have allocated 1538 * string copies for gitdir_path or gitfile so make 1539 * sure we don't leak by freeing them now, before 1540 * leaving the loop and function. 1541 * 1542 * Note: gitdirenv will be non-NULL whenever these are 1543 * allocated, therefore we need not take care of releasing 1544 * them outside of this conditional block. 1545 */ 1546 free(gitdir_path); 1547 free(gitfile); 1548 1549 return ret; 1550 } 1551 1552 if (is_git_directory(dir->buf)) { 1553 trace2_data_string("setup", NULL, "implicit-bare-repository", dir->buf); 1554 if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT && 1555 !is_implicit_bare_repo(dir->buf)) 1556 return GIT_DIR_DISALLOWED_BARE; 1557 if (!ensure_valid_ownership(NULL, NULL, dir->buf, report)) 1558 return GIT_DIR_INVALID_OWNERSHIP; 1559 strbuf_addstr(gitdir, "."); 1560 return GIT_DIR_BARE; 1561 } 1562 1563 if (offset <= min_offset) 1564 return GIT_DIR_HIT_CEILING; 1565 1566 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset])) 1567 ; /* continue */ 1568 if (offset <= ceil_offset) 1569 return GIT_DIR_HIT_CEILING; 1570 1571 strbuf_setlen(dir, offset > min_offset ? offset : min_offset); 1572 if (one_filesystem && 1573 current_device != get_device_or_die(dir->buf, NULL, offset)) 1574 return GIT_DIR_HIT_MOUNT_POINT; 1575 } 1576} 1577 1578enum discovery_result discover_git_directory_reason(struct strbuf *commondir, 1579 struct strbuf *gitdir) 1580{ 1581 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT; 1582 size_t gitdir_offset = gitdir->len, cwd_len; 1583 size_t commondir_offset = commondir->len; 1584 struct repository_format candidate = REPOSITORY_FORMAT_INIT; 1585 enum discovery_result result; 1586 1587 if (strbuf_getcwd(&dir)) 1588 return GIT_DIR_CWD_FAILURE; 1589 1590 cwd_len = dir.len; 1591 result = setup_git_directory_gently_1(&dir, gitdir, NULL, 0); 1592 if (result <= 0) { 1593 strbuf_release(&dir); 1594 return result; 1595 } 1596 1597 /* 1598 * The returned gitdir is relative to dir, and if dir does not reflect 1599 * the current working directory, we simply make the gitdir absolute. 1600 */ 1601 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) { 1602 /* Avoid a trailing "/." */ 1603 if (!strcmp(".", gitdir->buf + gitdir_offset)) 1604 strbuf_setlen(gitdir, gitdir_offset); 1605 else 1606 strbuf_addch(&dir, '/'); 1607 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len); 1608 } 1609 1610 get_common_dir(commondir, gitdir->buf + gitdir_offset); 1611 1612 strbuf_reset(&dir); 1613 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset); 1614 read_repository_format(&candidate, dir.buf); 1615 strbuf_release(&dir); 1616 1617 if (verify_repository_format(&candidate, &err) < 0) { 1618 warning("ignoring git dir '%s': %s", 1619 gitdir->buf + gitdir_offset, err.buf); 1620 strbuf_release(&err); 1621 strbuf_setlen(commondir, commondir_offset); 1622 strbuf_setlen(gitdir, gitdir_offset); 1623 clear_repository_format(&candidate); 1624 return GIT_DIR_INVALID_FORMAT; 1625 } 1626 1627 clear_repository_format(&candidate); 1628 return result; 1629} 1630 1631void setup_git_env(const char *git_dir) 1632{ 1633 char *git_replace_ref_base; 1634 const char *shallow_file; 1635 const char *replace_ref_base; 1636 struct set_gitdir_args args = { NULL }; 1637 struct strvec to_free = STRVEC_INIT; 1638 1639 args.commondir = getenv_safe(&to_free, GIT_COMMON_DIR_ENVIRONMENT); 1640 args.object_dir = getenv_safe(&to_free, DB_ENVIRONMENT); 1641 args.graft_file = getenv_safe(&to_free, GRAFT_ENVIRONMENT); 1642 args.index_file = getenv_safe(&to_free, INDEX_ENVIRONMENT); 1643 args.alternate_db = getenv_safe(&to_free, ALTERNATE_DB_ENVIRONMENT); 1644 if (getenv(GIT_QUARANTINE_ENVIRONMENT)) { 1645 args.disable_ref_updates = 1; 1646 } 1647 1648 repo_set_gitdir(the_repository, git_dir, &args); 1649 strvec_clear(&to_free); 1650 1651 if (getenv(NO_REPLACE_OBJECTS_ENVIRONMENT)) 1652 disable_replace_refs(); 1653 replace_ref_base = getenv(GIT_REPLACE_REF_BASE_ENVIRONMENT); 1654 git_replace_ref_base = xstrdup(replace_ref_base ? replace_ref_base 1655 : "refs/replace/"); 1656 update_ref_namespace(NAMESPACE_REPLACE, git_replace_ref_base); 1657 1658 shallow_file = getenv(GIT_SHALLOW_FILE_ENVIRONMENT); 1659 if (shallow_file) 1660 set_alternate_shallow_file(the_repository, shallow_file, 0); 1661 1662 if (git_env_bool(NO_LAZY_FETCH_ENVIRONMENT, 0)) 1663 fetch_if_missing = 0; 1664} 1665 1666static void set_git_dir_1(const char *path) 1667{ 1668 xsetenv(GIT_DIR_ENVIRONMENT, path, 1); 1669 setup_git_env(path); 1670} 1671 1672static void update_relative_gitdir(const char *name UNUSED, 1673 const char *old_cwd, 1674 const char *new_cwd, 1675 void *data UNUSED) 1676{ 1677 char *path = reparent_relative_path(old_cwd, new_cwd, 1678 repo_get_git_dir(the_repository)); 1679 struct tmp_objdir *tmp_objdir = tmp_objdir_unapply_primary_odb(); 1680 1681 trace_printf_key(&trace_setup_key, 1682 "setup: move $GIT_DIR to '%s'", 1683 path); 1684 set_git_dir_1(path); 1685 if (tmp_objdir) 1686 tmp_objdir_reapply_primary_odb(tmp_objdir, old_cwd, new_cwd); 1687 free(path); 1688} 1689 1690void set_git_dir(const char *path, int make_realpath) 1691{ 1692 struct strbuf realpath = STRBUF_INIT; 1693 1694 if (make_realpath) { 1695 strbuf_realpath(&realpath, path, 1); 1696 path = realpath.buf; 1697 } 1698 1699 set_git_dir_1(path); 1700 if (!is_absolute_path(path)) 1701 chdir_notify_register(NULL, update_relative_gitdir, NULL); 1702 1703 strbuf_release(&realpath); 1704} 1705 1706static int git_work_tree_initialized; 1707 1708/* 1709 * Note. This works only before you used a work tree. This was added 1710 * primarily to support git-clone to work in a new repository it just 1711 * created, and is not meant to flip between different work trees. 1712 */ 1713void set_git_work_tree(const char *new_work_tree) 1714{ 1715 if (git_work_tree_initialized) { 1716 struct strbuf realpath = STRBUF_INIT; 1717 1718 strbuf_realpath(&realpath, new_work_tree, 1); 1719 new_work_tree = realpath.buf; 1720 if (strcmp(new_work_tree, the_repository->worktree)) 1721 die("internal error: work tree has already been set\n" 1722 "Current worktree: %s\nNew worktree: %s", 1723 the_repository->worktree, new_work_tree); 1724 strbuf_release(&realpath); 1725 return; 1726 } 1727 git_work_tree_initialized = 1; 1728 repo_set_worktree(the_repository, new_work_tree); 1729} 1730 1731const char *setup_git_directory_gently(int *nongit_ok) 1732{ 1733 static struct strbuf cwd = STRBUF_INIT; 1734 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT; 1735 const char *prefix = NULL; 1736 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT; 1737 1738 /* 1739 * We may have read an incomplete configuration before 1740 * setting-up the git directory. If so, clear the cache so 1741 * that the next queries to the configuration reload complete 1742 * configuration (including the per-repo config file that we 1743 * ignored previously). 1744 */ 1745 repo_config_clear(the_repository); 1746 1747 /* 1748 * Let's assume that we are in a git repository. 1749 * If it turns out later that we are somewhere else, the value will be 1750 * updated accordingly. 1751 */ 1752 if (nongit_ok) 1753 *nongit_ok = 0; 1754 1755 if (strbuf_getcwd(&cwd)) 1756 die_errno(_("Unable to read current working directory")); 1757 strbuf_addbuf(&dir, &cwd); 1758 1759 switch (setup_git_directory_gently_1(&dir, &gitdir, &report, 1)) { 1760 case GIT_DIR_EXPLICIT: 1761 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok); 1762 break; 1763 case GIT_DIR_DISCOVERED: 1764 if (dir.len < cwd.len && chdir(dir.buf)) 1765 die(_("cannot change to '%s'"), dir.buf); 1766 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len, 1767 &repo_fmt, nongit_ok); 1768 break; 1769 case GIT_DIR_BARE: 1770 if (dir.len < cwd.len && chdir(dir.buf)) 1771 die(_("cannot change to '%s'"), dir.buf); 1772 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok); 1773 break; 1774 case GIT_DIR_HIT_CEILING: 1775 if (!nongit_ok) 1776 die(_("not a git repository (or any of the parent directories): %s"), 1777 DEFAULT_GIT_DIR_ENVIRONMENT); 1778 *nongit_ok = 1; 1779 break; 1780 case GIT_DIR_HIT_MOUNT_POINT: 1781 if (!nongit_ok) 1782 die(_("not a git repository (or any parent up to mount point %s)\n" 1783 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."), 1784 dir.buf); 1785 *nongit_ok = 1; 1786 break; 1787 case GIT_DIR_INVALID_OWNERSHIP: 1788 if (!nongit_ok) { 1789 struct strbuf quoted = STRBUF_INIT; 1790 1791 strbuf_complete(&report, '\n'); 1792 sq_quote_buf_pretty(&quoted, dir.buf); 1793 die(_("detected dubious ownership in repository at '%s'\n" 1794 "%s" 1795 "To add an exception for this directory, call:\n" 1796 "\n" 1797 "\tgit config --global --add safe.directory %s"), 1798 dir.buf, report.buf, quoted.buf); 1799 } 1800 *nongit_ok = 1; 1801 break; 1802 case GIT_DIR_DISALLOWED_BARE: 1803 if (!nongit_ok) { 1804 die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"), 1805 dir.buf, 1806 allowed_bare_repo_to_string(get_allowed_bare_repo())); 1807 } 1808 *nongit_ok = 1; 1809 break; 1810 case GIT_DIR_CWD_FAILURE: 1811 case GIT_DIR_INVALID_FORMAT: 1812 /* 1813 * As a safeguard against setup_git_directory_gently_1 returning 1814 * these values, fallthrough to BUG. Otherwise it is possible to 1815 * set startup_info->have_repository to 1 when we did nothing to 1816 * find a repository. 1817 */ 1818 default: 1819 BUG("unhandled setup_git_directory_gently_1() result"); 1820 } 1821 1822 /* 1823 * At this point, nongit_ok is stable. If it is non-NULL and points 1824 * to a non-zero value, then this means that we haven't found a 1825 * repository and that the caller expects startup_info to reflect 1826 * this. 1827 * 1828 * Regardless of the state of nongit_ok, startup_info->prefix and 1829 * the GIT_PREFIX environment variable must always match. For details 1830 * see Documentation/config/alias.adoc. 1831 */ 1832 if (nongit_ok && *nongit_ok) 1833 startup_info->have_repository = 0; 1834 else 1835 startup_info->have_repository = 1; 1836 1837 /* 1838 * Not all paths through the setup code will call 'set_git_dir()' (which 1839 * directly sets up the environment) so in order to guarantee that the 1840 * environment is in a consistent state after setup, explicitly setup 1841 * the environment if we have a repository. 1842 * 1843 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some 1844 * code paths so we also need to explicitly setup the environment if 1845 * the user has set GIT_DIR. It may be beneficial to disallow bogus 1846 * GIT_DIR values at some point in the future. 1847 */ 1848 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */ 1849 startup_info->have_repository || 1850 /* GIT_DIR_EXPLICIT */ 1851 getenv(GIT_DIR_ENVIRONMENT)) { 1852 if (!the_repository->gitdir) { 1853 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT); 1854 if (!gitdir) 1855 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT; 1856 setup_git_env(gitdir); 1857 } 1858 if (startup_info->have_repository) { 1859 repo_set_hash_algo(the_repository, repo_fmt.hash_algo); 1860 repo_set_compat_hash_algo(the_repository, 1861 repo_fmt.compat_hash_algo); 1862 repo_set_ref_storage_format(the_repository, 1863 repo_fmt.ref_storage_format); 1864 the_repository->repository_format_worktree_config = 1865 repo_fmt.worktree_config; 1866 the_repository->repository_format_relative_worktrees = 1867 repo_fmt.relative_worktrees; 1868 /* take ownership of repo_fmt.partial_clone */ 1869 the_repository->repository_format_partial_clone = 1870 repo_fmt.partial_clone; 1871 repo_fmt.partial_clone = NULL; 1872 the_repository->repository_format_precious_objects = 1873 repo_fmt.precious_objects; 1874 } 1875 } 1876 /* 1877 * Since precompose_string_if_needed() needs to look at 1878 * the core.precomposeunicode configuration, this 1879 * has to happen after the above block that finds 1880 * out where the repository is, i.e. a preparation 1881 * for calling repo_config_get_bool(). 1882 */ 1883 if (prefix) { 1884 prefix = precompose_string_if_needed(prefix); 1885 startup_info->prefix = prefix; 1886 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1); 1887 } else { 1888 startup_info->prefix = NULL; 1889 setenv(GIT_PREFIX_ENVIRONMENT, "", 1); 1890 } 1891 1892 setup_original_cwd(); 1893 1894 strbuf_release(&dir); 1895 strbuf_release(&gitdir); 1896 strbuf_release(&report); 1897 clear_repository_format(&repo_fmt); 1898 1899 return prefix; 1900} 1901 1902int git_config_perm(const char *var, const char *value) 1903{ 1904 int i; 1905 char *endptr; 1906 1907 if (!value) 1908 return PERM_GROUP; 1909 1910 if (!strcmp(value, "umask")) 1911 return PERM_UMASK; 1912 if (!strcmp(value, "group")) 1913 return PERM_GROUP; 1914 if (!strcmp(value, "all") || 1915 !strcmp(value, "world") || 1916 !strcmp(value, "everybody")) 1917 return PERM_EVERYBODY; 1918 1919 /* Parse octal numbers */ 1920 i = strtol(value, &endptr, 8); 1921 1922 /* If not an octal number, maybe true/false? */ 1923 if (*endptr != 0) 1924 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK; 1925 1926 /* 1927 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is 1928 * a chmod value to restrict to. 1929 */ 1930 switch (i) { 1931 case PERM_UMASK: /* 0 */ 1932 return PERM_UMASK; 1933 case OLD_PERM_GROUP: /* 1 */ 1934 return PERM_GROUP; 1935 case OLD_PERM_EVERYBODY: /* 2 */ 1936 return PERM_EVERYBODY; 1937 } 1938 1939 /* A filemode value was given: 0xxx */ 1940 1941 if ((i & 0600) != 0600) 1942 die(_("problem with core.sharedRepository filemode value " 1943 "(0%.3o).\nThe owner of files must always have " 1944 "read and write permissions."), i); 1945 1946 /* 1947 * Mask filemode value. Others can not get write permission. 1948 * x flags for directories are handled separately. 1949 */ 1950 return -(i & 0666); 1951} 1952 1953void check_repository_format(struct repository_format *fmt) 1954{ 1955 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT; 1956 if (!fmt) 1957 fmt = &repo_fmt; 1958 check_repository_format_gently(repo_get_git_dir(the_repository), fmt, NULL); 1959 startup_info->have_repository = 1; 1960 repo_set_hash_algo(the_repository, fmt->hash_algo); 1961 repo_set_compat_hash_algo(the_repository, fmt->compat_hash_algo); 1962 repo_set_ref_storage_format(the_repository, 1963 fmt->ref_storage_format); 1964 the_repository->repository_format_worktree_config = 1965 fmt->worktree_config; 1966 the_repository->repository_format_relative_worktrees = 1967 fmt->relative_worktrees; 1968 the_repository->repository_format_partial_clone = 1969 xstrdup_or_null(fmt->partial_clone); 1970 clear_repository_format(&repo_fmt); 1971} 1972 1973/* 1974 * Returns the "prefix", a path to the current working directory 1975 * relative to the work tree root, or NULL, if the current working 1976 * directory is not a strict subdirectory of the work tree root. The 1977 * prefix always ends with a '/' character. 1978 */ 1979const char *setup_git_directory(void) 1980{ 1981 return setup_git_directory_gently(NULL); 1982} 1983 1984const char *resolve_gitdir_gently(const char *suspect, int *return_error_code) 1985{ 1986 if (is_git_directory(suspect)) 1987 return suspect; 1988 return read_gitfile_gently(suspect, return_error_code); 1989} 1990 1991/* if any standard file descriptor is missing open it to /dev/null */ 1992void sanitize_stdfds(void) 1993{ 1994 int fd = xopen("/dev/null", O_RDWR); 1995 while (fd < 2) 1996 fd = xdup(fd); 1997 if (fd > 2) 1998 close(fd); 1999} 2000 2001int daemonize(void) 2002{ 2003#ifdef NO_POSIX_GOODIES 2004 errno = ENOSYS; 2005 return -1; 2006#else 2007 switch (fork()) { 2008 case 0: 2009 break; 2010 case -1: 2011 die_errno(_("fork failed")); 2012 default: 2013 exit(0); 2014 } 2015 if (setsid() == -1) 2016 die_errno(_("setsid failed")); 2017 close(0); 2018 close(1); 2019 close(2); 2020 sanitize_stdfds(); 2021 return 0; 2022#endif 2023} 2024 2025struct template_dir_cb_data { 2026 char *path; 2027 int initialized; 2028}; 2029 2030static int template_dir_cb(const char *key, const char *value, 2031 const struct config_context *ctx UNUSED, void *d) 2032{ 2033 struct template_dir_cb_data *data = d; 2034 2035 if (strcmp(key, "init.templatedir")) 2036 return 0; 2037 2038 if (!value) { 2039 data->path = NULL; 2040 } else { 2041 char *path = NULL; 2042 2043 FREE_AND_NULL(data->path); 2044 if (!git_config_pathname(&path, key, value)) 2045 data->path = path ? path : xstrdup(value); 2046 } 2047 2048 return 0; 2049} 2050 2051const char *get_template_dir(const char *option_template) 2052{ 2053 const char *template_dir = option_template; 2054 2055 if (!template_dir) 2056 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT); 2057 if (!template_dir) { 2058 static struct template_dir_cb_data data; 2059 2060 if (!data.initialized) { 2061 git_protected_config(template_dir_cb, &data); 2062 data.initialized = 1; 2063 } 2064 template_dir = data.path; 2065 } 2066 if (!template_dir) { 2067 static char *dir; 2068 2069 if (!dir) 2070 dir = system_path(DEFAULT_GIT_TEMPLATE_DIR); 2071 template_dir = dir; 2072 } 2073 return template_dir; 2074} 2075 2076#ifdef NO_TRUSTABLE_FILEMODE 2077#define TEST_FILEMODE 0 2078#else 2079#define TEST_FILEMODE 1 2080#endif 2081 2082#define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH" 2083 2084static void copy_templates_1(struct strbuf *path, struct strbuf *template_path, 2085 DIR *dir) 2086{ 2087 size_t path_baselen = path->len; 2088 size_t template_baselen = template_path->len; 2089 struct dirent *de; 2090 2091 /* Note: if ".git/hooks" file exists in the repository being 2092 * re-initialized, /etc/core-git/templates/hooks/update would 2093 * cause "git init" to fail here. I think this is sane but 2094 * it means that the set of templates we ship by default, along 2095 * with the way the namespace under .git/ is organized, should 2096 * be really carefully chosen. 2097 */ 2098 safe_create_dir(the_repository, path->buf, 1); 2099 while ((de = readdir(dir)) != NULL) { 2100 struct stat st_git, st_template; 2101 int exists = 0; 2102 2103 strbuf_setlen(path, path_baselen); 2104 strbuf_setlen(template_path, template_baselen); 2105 2106 if (de->d_name[0] == '.') 2107 continue; 2108 strbuf_addstr(path, de->d_name); 2109 strbuf_addstr(template_path, de->d_name); 2110 if (lstat(path->buf, &st_git)) { 2111 if (errno != ENOENT) 2112 die_errno(_("cannot stat '%s'"), path->buf); 2113 } 2114 else 2115 exists = 1; 2116 2117 if (lstat(template_path->buf, &st_template)) 2118 die_errno(_("cannot stat template '%s'"), template_path->buf); 2119 2120 if (S_ISDIR(st_template.st_mode)) { 2121 DIR *subdir = opendir(template_path->buf); 2122 if (!subdir) 2123 die_errno(_("cannot opendir '%s'"), template_path->buf); 2124 strbuf_addch(path, '/'); 2125 strbuf_addch(template_path, '/'); 2126 copy_templates_1(path, template_path, subdir); 2127 closedir(subdir); 2128 } 2129 else if (exists) 2130 continue; 2131 else if (S_ISLNK(st_template.st_mode)) { 2132 struct strbuf lnk = STRBUF_INIT; 2133 if (strbuf_readlink(&lnk, template_path->buf, 2134 st_template.st_size) < 0) 2135 die_errno(_("cannot readlink '%s'"), template_path->buf); 2136 if (symlink(lnk.buf, path->buf)) 2137 die_errno(_("cannot symlink '%s' '%s'"), 2138 lnk.buf, path->buf); 2139 strbuf_release(&lnk); 2140 } 2141 else if (S_ISREG(st_template.st_mode)) { 2142 if (copy_file(path->buf, template_path->buf, st_template.st_mode)) 2143 die_errno(_("cannot copy '%s' to '%s'"), 2144 template_path->buf, path->buf); 2145 } 2146 else 2147 error(_("ignoring template %s"), template_path->buf); 2148 } 2149} 2150 2151static void copy_templates(const char *option_template) 2152{ 2153 const char *template_dir = get_template_dir(option_template); 2154 struct strbuf path = STRBUF_INIT; 2155 struct strbuf template_path = STRBUF_INIT; 2156 size_t template_len; 2157 struct repository_format template_format = REPOSITORY_FORMAT_INIT; 2158 struct strbuf err = STRBUF_INIT; 2159 DIR *dir; 2160 char *to_free = NULL; 2161 2162 if (!template_dir || !*template_dir) 2163 return; 2164 2165 strbuf_addstr(&template_path, template_dir); 2166 strbuf_complete(&template_path, '/'); 2167 template_len = template_path.len; 2168 2169 dir = opendir(template_path.buf); 2170 if (!dir) { 2171 warning(_("templates not found in %s"), template_dir); 2172 goto free_return; 2173 } 2174 2175 /* Make sure that template is from the correct vintage */ 2176 strbuf_addstr(&template_path, "config"); 2177 read_repository_format(&template_format, template_path.buf); 2178 strbuf_setlen(&template_path, template_len); 2179 2180 /* 2181 * No mention of version at all is OK, but anything else should be 2182 * verified. 2183 */ 2184 if (template_format.version >= 0 && 2185 verify_repository_format(&template_format, &err) < 0) { 2186 warning(_("not copying templates from '%s': %s"), 2187 template_dir, err.buf); 2188 strbuf_release(&err); 2189 goto close_free_return; 2190 } 2191 2192 strbuf_addstr(&path, repo_get_common_dir(the_repository)); 2193 strbuf_complete(&path, '/'); 2194 copy_templates_1(&path, &template_path, dir); 2195close_free_return: 2196 closedir(dir); 2197free_return: 2198 free(to_free); 2199 strbuf_release(&path); 2200 strbuf_release(&template_path); 2201 clear_repository_format(&template_format); 2202} 2203 2204/* 2205 * If the git_dir is not directly inside the working tree, then git will not 2206 * find it by default, and we need to set the worktree explicitly. 2207 */ 2208static int needs_work_tree_config(const char *git_dir, const char *work_tree) 2209{ 2210 if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git")) 2211 return 0; 2212 if (skip_prefix(git_dir, work_tree, &git_dir) && 2213 !strcmp(git_dir, "/.git")) 2214 return 0; 2215 return 1; 2216} 2217 2218void initialize_repository_version(int hash_algo, 2219 enum ref_storage_format ref_storage_format, 2220 int reinit) 2221{ 2222 struct strbuf repo_version = STRBUF_INIT; 2223 int target_version = GIT_REPO_VERSION; 2224 2225 /* 2226 * Note that we initialize the repository version to 1 when the ref 2227 * storage format is unknown. This is on purpose so that we can add the 2228 * correct object format to the config during git-clone(1). The format 2229 * version will get adjusted by git-clone(1) once it has learned about 2230 * the remote repository's format. 2231 */ 2232 if (hash_algo != GIT_HASH_SHA1_LEGACY || 2233 ref_storage_format != REF_STORAGE_FORMAT_FILES) 2234 target_version = GIT_REPO_VERSION_READ; 2235 2236 if (hash_algo != GIT_HASH_SHA1_LEGACY && hash_algo != GIT_HASH_UNKNOWN) 2237 repo_config_set(the_repository, "extensions.objectformat", 2238 hash_algos[hash_algo].name); 2239 else if (reinit) 2240 repo_config_set_gently(the_repository, "extensions.objectformat", NULL); 2241 2242 if (ref_storage_format != REF_STORAGE_FORMAT_FILES) 2243 repo_config_set(the_repository, "extensions.refstorage", 2244 ref_storage_format_to_name(ref_storage_format)); 2245 else if (reinit) 2246 repo_config_set_gently(the_repository, "extensions.refstorage", NULL); 2247 2248 if (reinit) { 2249 struct strbuf config = STRBUF_INIT; 2250 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT; 2251 2252 repo_common_path_append(the_repository, &config, "config"); 2253 read_repository_format(&repo_fmt, config.buf); 2254 2255 if (repo_fmt.v1_only_extensions.nr) 2256 target_version = GIT_REPO_VERSION_READ; 2257 2258 strbuf_release(&config); 2259 clear_repository_format(&repo_fmt); 2260 } 2261 2262 strbuf_addf(&repo_version, "%d", target_version); 2263 repo_config_set(the_repository, "core.repositoryformatversion", repo_version.buf); 2264 2265 strbuf_release(&repo_version); 2266} 2267 2268static int is_reinit(void) 2269{ 2270 struct strbuf buf = STRBUF_INIT; 2271 char junk[2]; 2272 int ret; 2273 2274 repo_git_path_replace(the_repository, &buf, "HEAD"); 2275 ret = !access(buf.buf, R_OK) || readlink(buf.buf, junk, sizeof(junk) - 1) != -1; 2276 strbuf_release(&buf); 2277 return ret; 2278} 2279 2280void create_reference_database(enum ref_storage_format ref_storage_format, 2281 const char *initial_branch, int quiet) 2282{ 2283 struct strbuf err = STRBUF_INIT; 2284 char *to_free = NULL; 2285 int reinit = is_reinit(); 2286 2287 repo_set_ref_storage_format(the_repository, ref_storage_format); 2288 if (ref_store_create_on_disk(get_main_ref_store(the_repository), 0, &err)) 2289 die("failed to set up refs db: %s", err.buf); 2290 2291 /* 2292 * Point the HEAD symref to the initial branch with if HEAD does 2293 * not yet exist. 2294 */ 2295 if (!reinit) { 2296 char *ref; 2297 2298 if (!initial_branch) 2299 initial_branch = to_free = 2300 repo_default_branch_name(the_repository, quiet); 2301 2302 ref = xstrfmt("refs/heads/%s", initial_branch); 2303 if (check_refname_format(ref, 0) < 0) 2304 die(_("invalid initial branch name: '%s'"), 2305 initial_branch); 2306 2307 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", ref, NULL) < 0) 2308 exit(1); 2309 free(ref); 2310 } 2311 2312 if (reinit && initial_branch) 2313 warning(_("re-init: ignored --initial-branch=%s"), 2314 initial_branch); 2315 2316 strbuf_release(&err); 2317 free(to_free); 2318} 2319 2320static int create_default_files(const char *template_path, 2321 const char *original_git_dir, 2322 const struct repository_format *fmt, 2323 int init_shared_repository) 2324{ 2325 struct stat st1; 2326 struct strbuf path = STRBUF_INIT; 2327 int reinit; 2328 int filemode; 2329 const char *work_tree = repo_get_work_tree(the_repository); 2330 2331 /* 2332 * First copy the templates -- we might have the default 2333 * config file there, in which case we would want to read 2334 * from it after installing. 2335 * 2336 * Before reading that config, we also need to clear out any cached 2337 * values (since we've just potentially changed what's available on 2338 * disk). 2339 */ 2340 copy_templates(template_path); 2341 repo_config_clear(the_repository); 2342 repo_settings_reset_shared_repository(the_repository); 2343 repo_config(the_repository, git_default_config, NULL); 2344 2345 reinit = is_reinit(); 2346 2347 /* 2348 * We must make sure command-line options continue to override any 2349 * values we might have just re-read from the config. 2350 */ 2351 if (init_shared_repository != -1) 2352 repo_settings_set_shared_repository(the_repository, 2353 init_shared_repository); 2354 2355 is_bare_repository_cfg = !work_tree; 2356 2357 /* 2358 * We would have created the above under user's umask -- under 2359 * shared-repository settings, we would need to fix them up. 2360 */ 2361 if (repo_settings_get_shared_repository(the_repository)) { 2362 adjust_shared_perm(the_repository, repo_get_git_dir(the_repository)); 2363 } 2364 2365 initialize_repository_version(fmt->hash_algo, fmt->ref_storage_format, reinit); 2366 2367 /* Check filemode trustability */ 2368 repo_git_path_replace(the_repository, &path, "config"); 2369 filemode = TEST_FILEMODE; 2370 if (TEST_FILEMODE && !lstat(path.buf, &st1)) { 2371 struct stat st2; 2372 filemode = (!chmod(path.buf, st1.st_mode ^ S_IXUSR) && 2373 !lstat(path.buf, &st2) && 2374 st1.st_mode != st2.st_mode && 2375 !chmod(path.buf, st1.st_mode)); 2376 if (filemode && !reinit && (st1.st_mode & S_IXUSR)) 2377 filemode = 0; 2378 } 2379 repo_config_set(the_repository, "core.filemode", filemode ? "true" : "false"); 2380 2381 if (is_bare_repository()) 2382 repo_config_set(the_repository, "core.bare", "true"); 2383 else { 2384 repo_config_set(the_repository, "core.bare", "false"); 2385 /* allow template config file to override the default */ 2386 if (repo_settings_get_log_all_ref_updates(the_repository) == LOG_REFS_UNSET) 2387 repo_config_set(the_repository, "core.logallrefupdates", "true"); 2388 if (needs_work_tree_config(original_git_dir, work_tree)) 2389 repo_config_set(the_repository, "core.worktree", work_tree); 2390 } 2391 2392 if (!reinit) { 2393 /* Check if symlink is supported in the work tree */ 2394 repo_git_path_replace(the_repository, &path, "tXXXXXX"); 2395 if (!close(xmkstemp(path.buf)) && 2396 !unlink(path.buf) && 2397 !symlink("testing", path.buf) && 2398 !lstat(path.buf, &st1) && 2399 S_ISLNK(st1.st_mode)) 2400 unlink(path.buf); /* good */ 2401 else 2402 repo_config_set(the_repository, "core.symlinks", "false"); 2403 2404 /* Check if the filesystem is case-insensitive */ 2405 repo_git_path_replace(the_repository, &path, "CoNfIg"); 2406 if (!access(path.buf, F_OK)) 2407 repo_config_set(the_repository, "core.ignorecase", "true"); 2408 probe_utf8_pathname_composition(); 2409 } 2410 2411 strbuf_release(&path); 2412 return reinit; 2413} 2414 2415static void create_object_directory(void) 2416{ 2417 struct strbuf path = STRBUF_INIT; 2418 size_t baselen; 2419 2420 strbuf_addstr(&path, repo_get_object_directory(the_repository)); 2421 baselen = path.len; 2422 2423 safe_create_dir(the_repository, path.buf, 1); 2424 2425 strbuf_setlen(&path, baselen); 2426 strbuf_addstr(&path, "/pack"); 2427 safe_create_dir(the_repository, path.buf, 1); 2428 2429 strbuf_setlen(&path, baselen); 2430 strbuf_addstr(&path, "/info"); 2431 safe_create_dir(the_repository, path.buf, 1); 2432 2433 strbuf_release(&path); 2434} 2435 2436static void separate_git_dir(const char *git_dir, const char *git_link) 2437{ 2438 struct stat st; 2439 2440 if (!stat(git_link, &st)) { 2441 const char *src; 2442 2443 if (S_ISREG(st.st_mode)) 2444 src = read_gitfile(git_link); 2445 else if (S_ISDIR(st.st_mode)) 2446 src = git_link; 2447 else 2448 die(_("unable to handle file type %d"), (int)st.st_mode); 2449 2450 if (rename(src, git_dir)) 2451 die_errno(_("unable to move %s to %s"), src, git_dir); 2452 repair_worktrees_after_gitdir_move(src); 2453 } 2454 2455 write_file(git_link, "gitdir: %s", git_dir); 2456} 2457 2458struct default_format_config { 2459 int hash; 2460 enum ref_storage_format ref_format; 2461}; 2462 2463static int read_default_format_config(const char *key, const char *value, 2464 const struct config_context *ctx UNUSED, 2465 void *payload) 2466{ 2467 struct default_format_config *cfg = payload; 2468 char *str = NULL; 2469 int ret; 2470 2471 if (!strcmp(key, "init.defaultobjectformat")) { 2472 ret = git_config_string(&str, key, value); 2473 if (ret) 2474 goto out; 2475 cfg->hash = hash_algo_by_name(str); 2476 if (cfg->hash == GIT_HASH_UNKNOWN) 2477 warning(_("unknown hash algorithm '%s'"), str); 2478 goto out; 2479 } 2480 2481 if (!strcmp(key, "init.defaultrefformat")) { 2482 ret = git_config_string(&str, key, value); 2483 if (ret) 2484 goto out; 2485 cfg->ref_format = ref_storage_format_by_name(str); 2486 if (cfg->ref_format == REF_STORAGE_FORMAT_UNKNOWN) 2487 warning(_("unknown ref storage format '%s'"), str); 2488 goto out; 2489 } 2490 2491 /* 2492 * Enable the reftable format when "features.experimental" is enabled. 2493 * "init.defaultRefFormat" takes precedence over this setting. 2494 */ 2495 if (!strcmp(key, "feature.experimental") && 2496 cfg->ref_format == REF_STORAGE_FORMAT_UNKNOWN && 2497 git_config_bool(key, value)) { 2498 cfg->ref_format = REF_STORAGE_FORMAT_REFTABLE; 2499 ret = 0; 2500 goto out; 2501 } 2502 2503 ret = 0; 2504out: 2505 free(str); 2506 return ret; 2507} 2508 2509static void repository_format_configure(struct repository_format *repo_fmt, 2510 int hash, enum ref_storage_format ref_format) 2511{ 2512 struct default_format_config cfg = { 2513 .hash = GIT_HASH_UNKNOWN, 2514 .ref_format = REF_STORAGE_FORMAT_UNKNOWN, 2515 }; 2516 struct config_options opts = { 2517 .respect_includes = 1, 2518 .ignore_repo = 1, 2519 .ignore_worktree = 1, 2520 }; 2521 const char *env; 2522 2523 config_with_options(read_default_format_config, &cfg, NULL, NULL, &opts); 2524 2525 /* 2526 * If we already have an initialized repo, don't allow the user to 2527 * specify a different algorithm, as that could cause corruption. 2528 * Otherwise, if the user has specified one on the command line, use it. 2529 */ 2530 env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT); 2531 if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo) 2532 die(_("attempt to reinitialize repository with different hash")); 2533 else if (hash != GIT_HASH_UNKNOWN) 2534 repo_fmt->hash_algo = hash; 2535 else if (env) { 2536 int env_algo = hash_algo_by_name(env); 2537 if (env_algo == GIT_HASH_UNKNOWN) 2538 die(_("unknown hash algorithm '%s'"), env); 2539 if (repo_fmt->version < 0 || 2540 repo_fmt->hash_algo == GIT_HASH_UNKNOWN) 2541 repo_fmt->hash_algo = env_algo; 2542 } else if (cfg.hash != GIT_HASH_UNKNOWN) { 2543 repo_fmt->hash_algo = cfg.hash; 2544 } 2545 repo_set_hash_algo(the_repository, repo_fmt->hash_algo); 2546 2547 env = getenv("GIT_DEFAULT_REF_FORMAT"); 2548 if (repo_fmt->version >= 0 && 2549 ref_format != REF_STORAGE_FORMAT_UNKNOWN && 2550 ref_format != repo_fmt->ref_storage_format) { 2551 die(_("attempt to reinitialize repository with different reference storage format")); 2552 } else if (ref_format != REF_STORAGE_FORMAT_UNKNOWN) { 2553 repo_fmt->ref_storage_format = ref_format; 2554 } else if (env) { 2555 ref_format = ref_storage_format_by_name(env); 2556 if (ref_format == REF_STORAGE_FORMAT_UNKNOWN) 2557 die(_("unknown ref storage format '%s'"), env); 2558 if (repo_fmt->version < 0 || 2559 repo_fmt->ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN) 2560 repo_fmt->ref_storage_format = ref_format; 2561 } else if (cfg.ref_format != REF_STORAGE_FORMAT_UNKNOWN) { 2562 repo_fmt->ref_storage_format = cfg.ref_format; 2563 } else { 2564 repo_fmt->ref_storage_format = REF_STORAGE_FORMAT_DEFAULT; 2565 } 2566 repo_set_ref_storage_format(the_repository, repo_fmt->ref_storage_format); 2567} 2568 2569int init_db(const char *git_dir, const char *real_git_dir, 2570 const char *template_dir, int hash, 2571 enum ref_storage_format ref_storage_format, 2572 const char *initial_branch, 2573 int init_shared_repository, unsigned int flags) 2574{ 2575 int reinit; 2576 int exist_ok = flags & INIT_DB_EXIST_OK; 2577 char *original_git_dir = real_pathdup(git_dir, 1); 2578 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT; 2579 2580 if (real_git_dir) { 2581 struct stat st; 2582 2583 if (!exist_ok && !stat(git_dir, &st)) 2584 die(_("%s already exists"), git_dir); 2585 2586 if (!exist_ok && !stat(real_git_dir, &st)) 2587 die(_("%s already exists"), real_git_dir); 2588 2589 set_git_dir(real_git_dir, 1); 2590 git_dir = repo_get_git_dir(the_repository); 2591 separate_git_dir(git_dir, original_git_dir); 2592 } 2593 else { 2594 set_git_dir(git_dir, 1); 2595 git_dir = repo_get_git_dir(the_repository); 2596 } 2597 startup_info->have_repository = 1; 2598 2599 /* 2600 * Check to see if the repository version is right. 2601 * Note that a newly created repository does not have 2602 * config file, so this will not fail. What we are catching 2603 * is an attempt to reinitialize new repository with an old tool. 2604 */ 2605 check_repository_format(&repo_fmt); 2606 2607 repository_format_configure(&repo_fmt, hash, ref_storage_format); 2608 2609 /* 2610 * Ensure `core.hidedotfiles` is processed. This must happen after we 2611 * have set up the repository format such that we can evaluate 2612 * includeIf conditions correctly in the case of re-initialization. 2613 */ 2614 repo_config(the_repository, platform_core_config, NULL); 2615 2616 safe_create_dir(the_repository, git_dir, 0); 2617 2618 reinit = create_default_files(template_dir, original_git_dir, 2619 &repo_fmt, init_shared_repository); 2620 2621 if (!(flags & INIT_DB_SKIP_REFDB)) 2622 create_reference_database(repo_fmt.ref_storage_format, 2623 initial_branch, flags & INIT_DB_QUIET); 2624 create_object_directory(); 2625 2626 if (repo_settings_get_shared_repository(the_repository)) { 2627 char buf[10]; 2628 /* We do not spell "group" and such, so that 2629 * the configuration can be read by older version 2630 * of git. Note, we use octal numbers for new share modes, 2631 * and compatibility values for PERM_GROUP and 2632 * PERM_EVERYBODY. 2633 */ 2634 if (repo_settings_get_shared_repository(the_repository) < 0) 2635 /* force to the mode value */ 2636 xsnprintf(buf, sizeof(buf), "0%o", -repo_settings_get_shared_repository(the_repository)); 2637 else if (repo_settings_get_shared_repository(the_repository) == PERM_GROUP) 2638 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP); 2639 else if (repo_settings_get_shared_repository(the_repository) == PERM_EVERYBODY) 2640 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY); 2641 else 2642 BUG("invalid value for shared_repository"); 2643 repo_config_set(the_repository, "core.sharedrepository", buf); 2644 repo_config_set(the_repository, "receive.denyNonFastforwards", "true"); 2645 } 2646 2647 if (!(flags & INIT_DB_QUIET)) { 2648 int len = strlen(git_dir); 2649 2650 if (reinit) 2651 printf(repo_settings_get_shared_repository(the_repository) 2652 ? _("Reinitialized existing shared Git repository in %s%s\n") 2653 : _("Reinitialized existing Git repository in %s%s\n"), 2654 git_dir, len && git_dir[len-1] != '/' ? "/" : ""); 2655 else 2656 printf(repo_settings_get_shared_repository(the_repository) 2657 ? _("Initialized empty shared Git repository in %s%s\n") 2658 : _("Initialized empty Git repository in %s%s\n"), 2659 git_dir, len && git_dir[len-1] != '/' ? "/" : ""); 2660 } 2661 2662 clear_repository_format(&repo_fmt); 2663 free(original_git_dir); 2664 return 0; 2665}