5fc89fd7da6a7035e7c187e17074073b8d51e6a7
   1#include "cache.h"
   2#include "dir.h"
   3
   4static int inside_git_dir = -1;
   5static int inside_work_tree = -1;
   6
   7static int sanitary_path_copy(char *dst, const char *src)
   8{
   9        char *dst0 = dst;
  10
  11        if (*src == '/') {
  12                *dst++ = '/';
  13                while (*src == '/')
  14                        src++;
  15        }
  16
  17        for (;;) {
  18                char c = *src;
  19
  20                /*
  21                 * A path component that begins with . could be
  22                 * special:
  23                 * (1) "." and ends   -- ignore and terminate.
  24                 * (2) "./"           -- ignore them, eat slash and continue.
  25                 * (3) ".." and ends  -- strip one and terminate.
  26                 * (4) "../"          -- strip one, eat slash and continue.
  27                 */
  28                if (c == '.') {
  29                        if (!src[1]) {
  30                                /* (1) */
  31                                src++;
  32                        } else if (src[1] == '/') {
  33                                /* (2) */
  34                                src += 2;
  35                                while (*src == '/')
  36                                        src++;
  37                                continue;
  38                        } else if (src[1] == '.') {
  39                                if (!src[2]) {
  40                                        /* (3) */
  41                                        src += 2;
  42                                        goto up_one;
  43                                } else if (src[2] == '/') {
  44                                        /* (4) */
  45                                        src += 3;
  46                                        while (*src == '/')
  47                                                src++;
  48                                        goto up_one;
  49                                }
  50                        }
  51                }
  52
  53                /* copy up to the next '/', and eat all '/' */
  54                while ((c = *src++) != '\0' && c != '/')
  55                        *dst++ = c;
  56                if (c == '/') {
  57                        *dst++ = c;
  58                        while (c == '/')
  59                                c = *src++;
  60                        src--;
  61                } else if (!c)
  62                        break;
  63                continue;
  64
  65        up_one:
  66                /*
  67                 * dst0..dst is prefix portion, and dst[-1] is '/';
  68                 * go up one level.
  69                 */
  70                dst -= 2; /* go past trailing '/' if any */
  71                if (dst < dst0)
  72                        return -1;
  73                while (1) {
  74                        if (dst <= dst0)
  75                                break;
  76                        c = *dst--;
  77                        if (c == '/') {
  78                                dst += 2;
  79                                break;
  80                        }
  81                }
  82        }
  83        *dst = '\0';
  84        return 0;
  85}
  86
  87const char *prefix_path(const char *prefix, int len, const char *path)
  88{
  89        const char *orig = path;
  90        char *sanitized = xmalloc(len + strlen(path) + 1);
  91        if (is_absolute_path(orig))
  92                strcpy(sanitized, path);
  93        else {
  94                if (len)
  95                        memcpy(sanitized, prefix, len);
  96                strcpy(sanitized + len, path);
  97        }
  98        if (sanitary_path_copy(sanitized, sanitized))
  99                goto error_out;
 100        if (is_absolute_path(orig)) {
 101                const char *work_tree = get_git_work_tree();
 102                size_t len = strlen(work_tree);
 103                size_t total = strlen(sanitized) + 1;
 104                if (strncmp(sanitized, work_tree, len) ||
 105                    (sanitized[len] != '\0' && sanitized[len] != '/')) {
 106                error_out:
 107                        error("'%s' is outside repository", orig);
 108                        free(sanitized);
 109                        return NULL;
 110                }
 111                if (sanitized[len] == '/')
 112                        len++;
 113                memmove(sanitized, sanitized + len, total - len);
 114        }
 115        return sanitized;
 116}
 117
 118/*
 119 * Unlike prefix_path, this should be used if the named file does
 120 * not have to interact with index entry; i.e. name of a random file
 121 * on the filesystem.
 122 */
 123const char *prefix_filename(const char *pfx, int pfx_len, const char *arg)
 124{
 125        static char path[PATH_MAX];
 126        if (!pfx || !*pfx || is_absolute_path(arg))
 127                return arg;
 128        memcpy(path, pfx, pfx_len);
 129        strcpy(path + pfx_len, arg);
 130        return path;
 131}
 132
 133/*
 134 * Verify a filename that we got as an argument for a pathspec
 135 * entry. Note that a filename that begins with "-" never verifies
 136 * as true, because even if such a filename were to exist, we want
 137 * it to be preceded by the "--" marker (or we want the user to
 138 * use a format like "./-filename")
 139 */
 140void verify_filename(const char *prefix, const char *arg)
 141{
 142        const char *name;
 143        struct stat st;
 144
 145        if (*arg == '-')
 146                die("bad flag '%s' used after filename", arg);
 147        name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
 148        if (!lstat(name, &st))
 149                return;
 150        if (errno == ENOENT)
 151                die("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
 152                    "Use '--' to separate paths from revisions", arg);
 153        die("'%s': %s", arg, strerror(errno));
 154}
 155
 156/*
 157 * Opposite of the above: the command line did not have -- marker
 158 * and we parsed the arg as a refname.  It should not be interpretable
 159 * as a filename.
 160 */
 161void verify_non_filename(const char *prefix, const char *arg)
 162{
 163        const char *name;
 164        struct stat st;
 165
 166        if (!is_inside_work_tree() || is_inside_git_dir())
 167                return;
 168        if (*arg == '-')
 169                return; /* flag */
 170        name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
 171        if (!lstat(name, &st))
 172                die("ambiguous argument '%s': both revision and filename\n"
 173                    "Use '--' to separate filenames from revisions", arg);
 174        if (errno != ENOENT && errno != ENOTDIR)
 175                die("'%s': %s", arg, strerror(errno));
 176}
 177
 178const char **get_pathspec(const char *prefix, const char **pathspec)
 179{
 180        const char *entry = *pathspec;
 181        const char **src, **dst;
 182        int prefixlen;
 183
 184        if (!prefix && !entry)
 185                return NULL;
 186
 187        if (!entry) {
 188                static const char *spec[2];
 189                spec[0] = prefix;
 190                spec[1] = NULL;
 191                return spec;
 192        }
 193
 194        /* Otherwise we have to re-write the entries.. */
 195        src = pathspec;
 196        dst = pathspec;
 197        prefixlen = prefix ? strlen(prefix) : 0;
 198        while (*src) {
 199                const char *p = prefix_path(prefix, prefixlen, *src);
 200                if (p)
 201                        *(dst++) = p;
 202                else
 203                        exit(128); /* error message already given */
 204                src++;
 205        }
 206        *dst = NULL;
 207        if (!*pathspec)
 208                return NULL;
 209        return pathspec;
 210}
 211
 212/*
 213 * Test if it looks like we're at a git directory.
 214 * We want to see:
 215 *
 216 *  - either an objects/ directory _or_ the proper
 217 *    GIT_OBJECT_DIRECTORY environment variable
 218 *  - a refs/ directory
 219 *  - either a HEAD symlink or a HEAD file that is formatted as
 220 *    a proper "ref:", or a regular file HEAD that has a properly
 221 *    formatted sha1 object name.
 222 */
 223static int is_git_directory(const char *suspect)
 224{
 225        char path[PATH_MAX];
 226        size_t len = strlen(suspect);
 227
 228        strcpy(path, suspect);
 229        if (getenv(DB_ENVIRONMENT)) {
 230                if (access(getenv(DB_ENVIRONMENT), X_OK))
 231                        return 0;
 232        }
 233        else {
 234                strcpy(path + len, "/objects");
 235                if (access(path, X_OK))
 236                        return 0;
 237        }
 238
 239        strcpy(path + len, "/refs");
 240        if (access(path, X_OK))
 241                return 0;
 242
 243        strcpy(path + len, "/HEAD");
 244        if (validate_headref(path))
 245                return 0;
 246
 247        return 1;
 248}
 249
 250int is_inside_git_dir(void)
 251{
 252        if (inside_git_dir < 0)
 253                inside_git_dir = is_inside_dir(get_git_dir());
 254        return inside_git_dir;
 255}
 256
 257int is_inside_work_tree(void)
 258{
 259        if (inside_work_tree < 0)
 260                inside_work_tree = is_inside_dir(get_git_work_tree());
 261        return inside_work_tree;
 262}
 263
 264/*
 265 * set_work_tree() is only ever called if you set GIT_DIR explicitely.
 266 * The old behaviour (which we retain here) is to set the work tree root
 267 * to the cwd, unless overridden by the config, the command line, or
 268 * GIT_WORK_TREE.
 269 */
 270static const char *set_work_tree(const char *dir)
 271{
 272        char buffer[PATH_MAX + 1];
 273
 274        if (!getcwd(buffer, sizeof(buffer)))
 275                die ("Could not get the current working directory");
 276        git_work_tree_cfg = xstrdup(buffer);
 277        inside_work_tree = 1;
 278
 279        return NULL;
 280}
 281
 282void setup_work_tree(void)
 283{
 284        const char *work_tree, *git_dir;
 285        static int initialized = 0;
 286
 287        if (initialized)
 288                return;
 289        work_tree = get_git_work_tree();
 290        git_dir = get_git_dir();
 291        if (!is_absolute_path(git_dir))
 292                set_git_dir(make_absolute_path(git_dir));
 293        if (!work_tree || chdir(work_tree))
 294                die("This operation must be run in a work tree");
 295        initialized = 1;
 296}
 297
 298static int check_repository_format_gently(int *nongit_ok)
 299{
 300        git_config(check_repository_format_version, NULL);
 301        if (GIT_REPO_VERSION < repository_format_version) {
 302                if (!nongit_ok)
 303                        die ("Expected git repo version <= %d, found %d",
 304                             GIT_REPO_VERSION, repository_format_version);
 305                warning("Expected git repo version <= %d, found %d",
 306                        GIT_REPO_VERSION, repository_format_version);
 307                warning("Please upgrade Git");
 308                *nongit_ok = -1;
 309                return -1;
 310        }
 311        return 0;
 312}
 313
 314/*
 315 * Try to read the location of the git directory from the .git file,
 316 * return path to git directory if found.
 317 */
 318const char *read_gitfile_gently(const char *path)
 319{
 320        char *buf;
 321        struct stat st;
 322        int fd;
 323        size_t len;
 324
 325        if (stat(path, &st))
 326                return NULL;
 327        if (!S_ISREG(st.st_mode))
 328                return NULL;
 329        fd = open(path, O_RDONLY);
 330        if (fd < 0)
 331                die("Error opening %s: %s", path, strerror(errno));
 332        buf = xmalloc(st.st_size + 1);
 333        len = read_in_full(fd, buf, st.st_size);
 334        close(fd);
 335        if (len != st.st_size)
 336                die("Error reading %s", path);
 337        buf[len] = '\0';
 338        if (prefixcmp(buf, "gitdir: "))
 339                die("Invalid gitfile format: %s", path);
 340        while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
 341                len--;
 342        if (len < 9)
 343                die("No path in gitfile: %s", path);
 344        buf[len] = '\0';
 345        if (!is_git_directory(buf + 8))
 346                die("Not a git repository: %s", buf + 8);
 347        path = make_absolute_path(buf + 8);
 348        free(buf);
 349        return path;
 350}
 351
 352/*
 353 * We cannot decide in this function whether we are in the work tree or
 354 * not, since the config can only be read _after_ this function was called.
 355 */
 356const char *setup_git_directory_gently(int *nongit_ok)
 357{
 358        const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
 359        static char cwd[PATH_MAX+1];
 360        const char *gitdirenv;
 361        const char *gitfile_dir;
 362        int len, offset;
 363
 364        /*
 365         * Let's assume that we are in a git repository.
 366         * If it turns out later that we are somewhere else, the value will be
 367         * updated accordingly.
 368         */
 369        if (nongit_ok)
 370                *nongit_ok = 0;
 371
 372        /*
 373         * If GIT_DIR is set explicitly, we're not going
 374         * to do any discovery, but we still do repository
 375         * validation.
 376         */
 377        gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
 378        if (gitdirenv) {
 379                if (PATH_MAX - 40 < strlen(gitdirenv))
 380                        die("'$%s' too big", GIT_DIR_ENVIRONMENT);
 381                if (is_git_directory(gitdirenv)) {
 382                        static char buffer[1024 + 1];
 383                        const char *retval;
 384
 385                        if (!work_tree_env) {
 386                                retval = set_work_tree(gitdirenv);
 387                                /* config may override worktree */
 388                                if (check_repository_format_gently(nongit_ok))
 389                                        return NULL;
 390                                return retval;
 391                        }
 392                        if (check_repository_format_gently(nongit_ok))
 393                                return NULL;
 394                        retval = get_relative_cwd(buffer, sizeof(buffer) - 1,
 395                                        get_git_work_tree());
 396                        if (!retval || !*retval)
 397                                return NULL;
 398                        set_git_dir(make_absolute_path(gitdirenv));
 399                        if (chdir(work_tree_env) < 0)
 400                                die ("Could not chdir to %s", work_tree_env);
 401                        strcat(buffer, "/");
 402                        return retval;
 403                }
 404                if (nongit_ok) {
 405                        *nongit_ok = 1;
 406                        return NULL;
 407                }
 408                die("Not a git repository: '%s'", gitdirenv);
 409        }
 410
 411        if (!getcwd(cwd, sizeof(cwd)-1))
 412                die("Unable to read current working directory");
 413
 414        /*
 415         * Test in the following order (relative to the cwd):
 416         * - .git (file containing "gitdir: <path>")
 417         * - .git/
 418         * - ./ (bare)
 419         * - ../.git
 420         * - ../.git/
 421         * - ../ (bare)
 422         * - ../../.git/
 423         *   etc.
 424         */
 425        offset = len = strlen(cwd);
 426        for (;;) {
 427                gitfile_dir = read_gitfile_gently(DEFAULT_GIT_DIR_ENVIRONMENT);
 428                if (gitfile_dir) {
 429                        if (set_git_dir(gitfile_dir))
 430                                die("Repository setup failed");
 431                        break;
 432                }
 433                if (is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT))
 434                        break;
 435                if (is_git_directory(".")) {
 436                        inside_git_dir = 1;
 437                        if (!work_tree_env)
 438                                inside_work_tree = 0;
 439                        setenv(GIT_DIR_ENVIRONMENT, ".", 1);
 440                        check_repository_format_gently(nongit_ok);
 441                        return NULL;
 442                }
 443                chdir("..");
 444                do {
 445                        if (!offset) {
 446                                if (nongit_ok) {
 447                                        if (chdir(cwd))
 448                                                die("Cannot come back to cwd");
 449                                        *nongit_ok = 1;
 450                                        return NULL;
 451                                }
 452                                die("Not a git repository");
 453                        }
 454                } while (cwd[--offset] != '/');
 455        }
 456
 457        inside_git_dir = 0;
 458        if (!work_tree_env)
 459                inside_work_tree = 1;
 460        git_work_tree_cfg = xstrndup(cwd, offset);
 461        if (check_repository_format_gently(nongit_ok))
 462                return NULL;
 463        if (offset == len)
 464                return NULL;
 465
 466        /* Make "offset" point to past the '/', and add a '/' at the end */
 467        offset++;
 468        cwd[len++] = '/';
 469        cwd[len] = 0;
 470        return cwd + offset;
 471}
 472
 473int git_config_perm(const char *var, const char *value)
 474{
 475        int i;
 476        char *endptr;
 477
 478        if (value == NULL)
 479                return PERM_GROUP;
 480
 481        if (!strcmp(value, "umask"))
 482                return PERM_UMASK;
 483        if (!strcmp(value, "group"))
 484                return PERM_GROUP;
 485        if (!strcmp(value, "all") ||
 486            !strcmp(value, "world") ||
 487            !strcmp(value, "everybody"))
 488                return PERM_EVERYBODY;
 489
 490        /* Parse octal numbers */
 491        i = strtol(value, &endptr, 8);
 492
 493        /* If not an octal number, maybe true/false? */
 494        if (*endptr != 0)
 495                return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
 496
 497        /*
 498         * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
 499         * a chmod value.
 500         */
 501        switch (i) {
 502        case PERM_UMASK:               /* 0 */
 503                return PERM_UMASK;
 504        case OLD_PERM_GROUP:           /* 1 */
 505                return PERM_GROUP;
 506        case OLD_PERM_EVERYBODY:       /* 2 */
 507                return PERM_EVERYBODY;
 508        }
 509
 510        /* A filemode value was given: 0xxx */
 511
 512        if ((i & 0600) != 0600)
 513                die("Problem with core.sharedRepository filemode value "
 514                    "(0%.3o).\nThe owner of files must always have "
 515                    "read and write permissions.", i);
 516
 517        /*
 518         * Mask filemode value. Others can not get write permission.
 519         * x flags for directories are handled separately.
 520         */
 521        return i & 0666;
 522}
 523
 524int check_repository_format_version(const char *var, const char *value, void *cb)
 525{
 526        if (strcmp(var, "core.repositoryformatversion") == 0)
 527                repository_format_version = git_config_int(var, value);
 528        else if (strcmp(var, "core.sharedrepository") == 0)
 529                shared_repository = git_config_perm(var, value);
 530        else if (strcmp(var, "core.bare") == 0) {
 531                is_bare_repository_cfg = git_config_bool(var, value);
 532                if (is_bare_repository_cfg == 1)
 533                        inside_work_tree = -1;
 534        } else if (strcmp(var, "core.worktree") == 0) {
 535                if (!value)
 536                        return config_error_nonbool(var);
 537                free(git_work_tree_cfg);
 538                git_work_tree_cfg = xstrdup(value);
 539                inside_work_tree = -1;
 540        }
 541        return 0;
 542}
 543
 544int check_repository_format(void)
 545{
 546        return check_repository_format_gently(NULL);
 547}
 548
 549const char *setup_git_directory(void)
 550{
 551        const char *retval = setup_git_directory_gently(NULL);
 552
 553        /* If the work tree is not the default one, recompute prefix */
 554        if (inside_work_tree < 0) {
 555                static char buffer[PATH_MAX + 1];
 556                char *rel;
 557                if (retval && chdir(retval))
 558                        die ("Could not jump back into original cwd");
 559                rel = get_relative_cwd(buffer, PATH_MAX, get_git_work_tree());
 560                return rel && *rel ? strcat(rel, "/") : NULL;
 561        }
 562
 563        return retval;
 564}