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