path.con commit enter_repo: allow .git files in strict mode (1f5fbe1)
   1/*
   2 * Utilities for paths and pathnames
   3 */
   4#include "cache.h"
   5#include "strbuf.h"
   6#include "string-list.h"
   7#include "dir.h"
   8
   9static int get_st_mode_bits(const char *path, int *mode)
  10{
  11        struct stat st;
  12        if (lstat(path, &st) < 0)
  13                return -1;
  14        *mode = st.st_mode;
  15        return 0;
  16}
  17
  18static char bad_path[] = "/bad-path/";
  19
  20static struct strbuf *get_pathname(void)
  21{
  22        static struct strbuf pathname_array[4] = {
  23                STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
  24        };
  25        static int index;
  26        struct strbuf *sb = &pathname_array[3 & ++index];
  27        strbuf_reset(sb);
  28        return sb;
  29}
  30
  31static char *cleanup_path(char *path)
  32{
  33        /* Clean it up */
  34        if (!memcmp(path, "./", 2)) {
  35                path += 2;
  36                while (*path == '/')
  37                        path++;
  38        }
  39        return path;
  40}
  41
  42static void strbuf_cleanup_path(struct strbuf *sb)
  43{
  44        char *path = cleanup_path(sb->buf);
  45        if (path > sb->buf)
  46                strbuf_remove(sb, 0, path - sb->buf);
  47}
  48
  49char *mksnpath(char *buf, size_t n, const char *fmt, ...)
  50{
  51        va_list args;
  52        unsigned len;
  53
  54        va_start(args, fmt);
  55        len = vsnprintf(buf, n, fmt, args);
  56        va_end(args);
  57        if (len >= n) {
  58                strlcpy(buf, bad_path, n);
  59                return buf;
  60        }
  61        return cleanup_path(buf);
  62}
  63
  64static int dir_prefix(const char *buf, const char *dir)
  65{
  66        int len = strlen(dir);
  67        return !strncmp(buf, dir, len) &&
  68                (is_dir_sep(buf[len]) || buf[len] == '\0');
  69}
  70
  71/* $buf =~ m|$dir/+$file| but without regex */
  72static int is_dir_file(const char *buf, const char *dir, const char *file)
  73{
  74        int len = strlen(dir);
  75        if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
  76                return 0;
  77        while (is_dir_sep(buf[len]))
  78                len++;
  79        return !strcmp(buf + len, file);
  80}
  81
  82static void replace_dir(struct strbuf *buf, int len, const char *newdir)
  83{
  84        int newlen = strlen(newdir);
  85        int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
  86                !is_dir_sep(newdir[newlen - 1]);
  87        if (need_sep)
  88                len--;   /* keep one char, to be replaced with '/'  */
  89        strbuf_splice(buf, 0, len, newdir, newlen);
  90        if (need_sep)
  91                buf->buf[newlen] = '/';
  92}
  93
  94static const char *common_list[] = {
  95        "/branches", "/hooks", "/info", "!/logs", "/lost-found",
  96        "/objects", "/refs", "/remotes", "/worktrees", "/rr-cache", "/svn",
  97        "config", "!gc.pid", "packed-refs", "shallow",
  98        NULL
  99};
 100
 101static void update_common_dir(struct strbuf *buf, int git_dir_len)
 102{
 103        char *base = buf->buf + git_dir_len;
 104        const char **p;
 105
 106        if (is_dir_file(base, "logs", "HEAD") ||
 107            is_dir_file(base, "info", "sparse-checkout"))
 108                return; /* keep this in $GIT_DIR */
 109        for (p = common_list; *p; p++) {
 110                const char *path = *p;
 111                int is_dir = 0;
 112                if (*path == '!')
 113                        path++;
 114                if (*path == '/') {
 115                        path++;
 116                        is_dir = 1;
 117                }
 118                if (is_dir && dir_prefix(base, path)) {
 119                        replace_dir(buf, git_dir_len, get_git_common_dir());
 120                        return;
 121                }
 122                if (!is_dir && !strcmp(base, path)) {
 123                        replace_dir(buf, git_dir_len, get_git_common_dir());
 124                        return;
 125                }
 126        }
 127}
 128
 129void report_linked_checkout_garbage(void)
 130{
 131        struct strbuf sb = STRBUF_INIT;
 132        const char **p;
 133        int len;
 134
 135        if (!git_common_dir_env)
 136                return;
 137        strbuf_addf(&sb, "%s/", get_git_dir());
 138        len = sb.len;
 139        for (p = common_list; *p; p++) {
 140                const char *path = *p;
 141                if (*path == '!')
 142                        continue;
 143                strbuf_setlen(&sb, len);
 144                strbuf_addstr(&sb, path);
 145                if (file_exists(sb.buf))
 146                        report_garbage("unused in linked checkout", sb.buf);
 147        }
 148        strbuf_release(&sb);
 149}
 150
 151static void adjust_git_path(struct strbuf *buf, int git_dir_len)
 152{
 153        const char *base = buf->buf + git_dir_len;
 154        if (git_graft_env && is_dir_file(base, "info", "grafts"))
 155                strbuf_splice(buf, 0, buf->len,
 156                              get_graft_file(), strlen(get_graft_file()));
 157        else if (git_index_env && !strcmp(base, "index"))
 158                strbuf_splice(buf, 0, buf->len,
 159                              get_index_file(), strlen(get_index_file()));
 160        else if (git_db_env && dir_prefix(base, "objects"))
 161                replace_dir(buf, git_dir_len + 7, get_object_directory());
 162        else if (git_common_dir_env)
 163                update_common_dir(buf, git_dir_len);
 164}
 165
 166static void do_git_path(struct strbuf *buf, const char *fmt, va_list args)
 167{
 168        int gitdir_len;
 169        strbuf_addstr(buf, get_git_dir());
 170        if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
 171                strbuf_addch(buf, '/');
 172        gitdir_len = buf->len;
 173        strbuf_vaddf(buf, fmt, args);
 174        adjust_git_path(buf, gitdir_len);
 175        strbuf_cleanup_path(buf);
 176}
 177
 178void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
 179{
 180        va_list args;
 181        va_start(args, fmt);
 182        do_git_path(sb, fmt, args);
 183        va_end(args);
 184}
 185
 186const char *git_path(const char *fmt, ...)
 187{
 188        struct strbuf *pathname = get_pathname();
 189        va_list args;
 190        va_start(args, fmt);
 191        do_git_path(pathname, fmt, args);
 192        va_end(args);
 193        return pathname->buf;
 194}
 195
 196char *git_pathdup(const char *fmt, ...)
 197{
 198        struct strbuf path = STRBUF_INIT;
 199        va_list args;
 200        va_start(args, fmt);
 201        do_git_path(&path, fmt, args);
 202        va_end(args);
 203        return strbuf_detach(&path, NULL);
 204}
 205
 206char *mkpathdup(const char *fmt, ...)
 207{
 208        struct strbuf sb = STRBUF_INIT;
 209        va_list args;
 210        va_start(args, fmt);
 211        strbuf_vaddf(&sb, fmt, args);
 212        va_end(args);
 213        strbuf_cleanup_path(&sb);
 214        return strbuf_detach(&sb, NULL);
 215}
 216
 217const char *mkpath(const char *fmt, ...)
 218{
 219        va_list args;
 220        struct strbuf *pathname = get_pathname();
 221        va_start(args, fmt);
 222        strbuf_vaddf(pathname, fmt, args);
 223        va_end(args);
 224        return cleanup_path(pathname->buf);
 225}
 226
 227static void do_submodule_path(struct strbuf *buf, const char *path,
 228                              const char *fmt, va_list args)
 229{
 230        const char *git_dir;
 231
 232        strbuf_addstr(buf, path);
 233        if (buf->len && buf->buf[buf->len - 1] != '/')
 234                strbuf_addch(buf, '/');
 235        strbuf_addstr(buf, ".git");
 236
 237        git_dir = read_gitfile(buf->buf);
 238        if (git_dir) {
 239                strbuf_reset(buf);
 240                strbuf_addstr(buf, git_dir);
 241        }
 242        strbuf_addch(buf, '/');
 243
 244        strbuf_vaddf(buf, fmt, args);
 245        strbuf_cleanup_path(buf);
 246}
 247
 248char *git_pathdup_submodule(const char *path, const char *fmt, ...)
 249{
 250        va_list args;
 251        struct strbuf buf = STRBUF_INIT;
 252        va_start(args, fmt);
 253        do_submodule_path(&buf, path, fmt, args);
 254        va_end(args);
 255        return strbuf_detach(&buf, NULL);
 256}
 257
 258void strbuf_git_path_submodule(struct strbuf *buf, const char *path,
 259                               const char *fmt, ...)
 260{
 261        va_list args;
 262        va_start(args, fmt);
 263        do_submodule_path(buf, path, fmt, args);
 264        va_end(args);
 265}
 266
 267int validate_headref(const char *path)
 268{
 269        struct stat st;
 270        char *buf, buffer[256];
 271        unsigned char sha1[20];
 272        int fd;
 273        ssize_t len;
 274
 275        if (lstat(path, &st) < 0)
 276                return -1;
 277
 278        /* Make sure it is a "refs/.." symlink */
 279        if (S_ISLNK(st.st_mode)) {
 280                len = readlink(path, buffer, sizeof(buffer)-1);
 281                if (len >= 5 && !memcmp("refs/", buffer, 5))
 282                        return 0;
 283                return -1;
 284        }
 285
 286        /*
 287         * Anything else, just open it and try to see if it is a symbolic ref.
 288         */
 289        fd = open(path, O_RDONLY);
 290        if (fd < 0)
 291                return -1;
 292        len = read_in_full(fd, buffer, sizeof(buffer)-1);
 293        close(fd);
 294
 295        /*
 296         * Is it a symbolic ref?
 297         */
 298        if (len < 4)
 299                return -1;
 300        if (!memcmp("ref:", buffer, 4)) {
 301                buf = buffer + 4;
 302                len -= 4;
 303                while (len && isspace(*buf))
 304                        buf++, len--;
 305                if (len >= 5 && !memcmp("refs/", buf, 5))
 306                        return 0;
 307        }
 308
 309        /*
 310         * Is this a detached HEAD?
 311         */
 312        if (!get_sha1_hex(buffer, sha1))
 313                return 0;
 314
 315        return -1;
 316}
 317
 318static struct passwd *getpw_str(const char *username, size_t len)
 319{
 320        struct passwd *pw;
 321        char *username_z = xmemdupz(username, len);
 322        pw = getpwnam(username_z);
 323        free(username_z);
 324        return pw;
 325}
 326
 327/*
 328 * Return a string with ~ and ~user expanded via getpw*.  If buf != NULL,
 329 * then it is a newly allocated string. Returns NULL on getpw failure or
 330 * if path is NULL.
 331 */
 332char *expand_user_path(const char *path)
 333{
 334        struct strbuf user_path = STRBUF_INIT;
 335        const char *to_copy = path;
 336
 337        if (path == NULL)
 338                goto return_null;
 339        if (path[0] == '~') {
 340                const char *first_slash = strchrnul(path, '/');
 341                const char *username = path + 1;
 342                size_t username_len = first_slash - username;
 343                if (username_len == 0) {
 344                        const char *home = getenv("HOME");
 345                        if (!home)
 346                                goto return_null;
 347                        strbuf_addstr(&user_path, home);
 348                } else {
 349                        struct passwd *pw = getpw_str(username, username_len);
 350                        if (!pw)
 351                                goto return_null;
 352                        strbuf_addstr(&user_path, pw->pw_dir);
 353                }
 354                to_copy = first_slash;
 355        }
 356        strbuf_addstr(&user_path, to_copy);
 357        return strbuf_detach(&user_path, NULL);
 358return_null:
 359        strbuf_release(&user_path);
 360        return NULL;
 361}
 362
 363/*
 364 * First, one directory to try is determined by the following algorithm.
 365 *
 366 * (0) If "strict" is given, the path is used as given and no DWIM is
 367 *     done. Otherwise:
 368 * (1) "~/path" to mean path under the running user's home directory;
 369 * (2) "~user/path" to mean path under named user's home directory;
 370 * (3) "relative/path" to mean cwd relative directory; or
 371 * (4) "/absolute/path" to mean absolute directory.
 372 *
 373 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
 374 * in this order. We select the first one that is a valid git repository, and
 375 * chdir() to it. If none match, or we fail to chdir, we return NULL.
 376 *
 377 * If all goes well, we return the directory we used to chdir() (but
 378 * before ~user is expanded), avoiding getcwd() resolving symbolic
 379 * links.  User relative paths are also returned as they are given,
 380 * except DWIM suffixing.
 381 */
 382const char *enter_repo(const char *path, int strict)
 383{
 384        static char used_path[PATH_MAX];
 385        static char validated_path[PATH_MAX];
 386
 387        if (!path)
 388                return NULL;
 389
 390        if (!strict) {
 391                static const char *suffix[] = {
 392                        "/.git", "", ".git/.git", ".git", NULL,
 393                };
 394                const char *gitfile;
 395                int len = strlen(path);
 396                int i;
 397                while ((1 < len) && (path[len-1] == '/'))
 398                        len--;
 399
 400                if (PATH_MAX <= len)
 401                        return NULL;
 402                strncpy(used_path, path, len); used_path[len] = 0 ;
 403                strcpy(validated_path, used_path);
 404
 405                if (used_path[0] == '~') {
 406                        char *newpath = expand_user_path(used_path);
 407                        if (!newpath || (PATH_MAX - 10 < strlen(newpath))) {
 408                                free(newpath);
 409                                return NULL;
 410                        }
 411                        /*
 412                         * Copy back into the static buffer. A pity
 413                         * since newpath was not bounded, but other
 414                         * branches of the if are limited by PATH_MAX
 415                         * anyway.
 416                         */
 417                        strcpy(used_path, newpath); free(newpath);
 418                }
 419                else if (PATH_MAX - 10 < len)
 420                        return NULL;
 421                len = strlen(used_path);
 422                for (i = 0; suffix[i]; i++) {
 423                        struct stat st;
 424                        strcpy(used_path + len, suffix[i]);
 425                        if (!stat(used_path, &st) &&
 426                            (S_ISREG(st.st_mode) ||
 427                            (S_ISDIR(st.st_mode) && is_git_directory(used_path)))) {
 428                                strcat(validated_path, suffix[i]);
 429                                break;
 430                        }
 431                }
 432                if (!suffix[i])
 433                        return NULL;
 434                gitfile = read_gitfile(used_path);
 435                if (gitfile)
 436                        strcpy(used_path, gitfile);
 437                if (chdir(used_path))
 438                        return NULL;
 439                path = validated_path;
 440        }
 441        else {
 442                const char *gitfile = read_gitfile(path);
 443                if (gitfile)
 444                        path = gitfile;
 445                if (chdir(path))
 446                        return NULL;
 447        }
 448
 449        if (is_git_directory(".")) {
 450                set_git_dir(".");
 451                check_repository_format();
 452                return path;
 453        }
 454
 455        return NULL;
 456}
 457
 458static int calc_shared_perm(int mode)
 459{
 460        int tweak;
 461
 462        if (shared_repository < 0)
 463                tweak = -shared_repository;
 464        else
 465                tweak = shared_repository;
 466
 467        if (!(mode & S_IWUSR))
 468                tweak &= ~0222;
 469        if (mode & S_IXUSR)
 470                /* Copy read bits to execute bits */
 471                tweak |= (tweak & 0444) >> 2;
 472        if (shared_repository < 0)
 473                mode = (mode & ~0777) | tweak;
 474        else
 475                mode |= tweak;
 476
 477        return mode;
 478}
 479
 480
 481int adjust_shared_perm(const char *path)
 482{
 483        int old_mode, new_mode;
 484
 485        if (!shared_repository)
 486                return 0;
 487        if (get_st_mode_bits(path, &old_mode) < 0)
 488                return -1;
 489
 490        new_mode = calc_shared_perm(old_mode);
 491        if (S_ISDIR(old_mode)) {
 492                /* Copy read bits to execute bits */
 493                new_mode |= (new_mode & 0444) >> 2;
 494                new_mode |= FORCE_DIR_SET_GID;
 495        }
 496
 497        if (((old_mode ^ new_mode) & ~S_IFMT) &&
 498                        chmod(path, (new_mode & ~S_IFMT)) < 0)
 499                return -2;
 500        return 0;
 501}
 502
 503static int have_same_root(const char *path1, const char *path2)
 504{
 505        int is_abs1, is_abs2;
 506
 507        is_abs1 = is_absolute_path(path1);
 508        is_abs2 = is_absolute_path(path2);
 509        return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
 510               (!is_abs1 && !is_abs2);
 511}
 512
 513/*
 514 * Give path as relative to prefix.
 515 *
 516 * The strbuf may or may not be used, so do not assume it contains the
 517 * returned path.
 518 */
 519const char *relative_path(const char *in, const char *prefix,
 520                          struct strbuf *sb)
 521{
 522        int in_len = in ? strlen(in) : 0;
 523        int prefix_len = prefix ? strlen(prefix) : 0;
 524        int in_off = 0;
 525        int prefix_off = 0;
 526        int i = 0, j = 0;
 527
 528        if (!in_len)
 529                return "./";
 530        else if (!prefix_len)
 531                return in;
 532
 533        if (have_same_root(in, prefix)) {
 534                /* bypass dos_drive, for "c:" is identical to "C:" */
 535                if (has_dos_drive_prefix(in)) {
 536                        i = 2;
 537                        j = 2;
 538                }
 539        } else {
 540                return in;
 541        }
 542
 543        while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
 544                if (is_dir_sep(prefix[i])) {
 545                        while (is_dir_sep(prefix[i]))
 546                                i++;
 547                        while (is_dir_sep(in[j]))
 548                                j++;
 549                        prefix_off = i;
 550                        in_off = j;
 551                } else {
 552                        i++;
 553                        j++;
 554                }
 555        }
 556
 557        if (
 558            /* "prefix" seems like prefix of "in" */
 559            i >= prefix_len &&
 560            /*
 561             * but "/foo" is not a prefix of "/foobar"
 562             * (i.e. prefix not end with '/')
 563             */
 564            prefix_off < prefix_len) {
 565                if (j >= in_len) {
 566                        /* in="/a/b", prefix="/a/b" */
 567                        in_off = in_len;
 568                } else if (is_dir_sep(in[j])) {
 569                        /* in="/a/b/c", prefix="/a/b" */
 570                        while (is_dir_sep(in[j]))
 571                                j++;
 572                        in_off = j;
 573                } else {
 574                        /* in="/a/bbb/c", prefix="/a/b" */
 575                        i = prefix_off;
 576                }
 577        } else if (
 578                   /* "in" is short than "prefix" */
 579                   j >= in_len &&
 580                   /* "in" not end with '/' */
 581                   in_off < in_len) {
 582                if (is_dir_sep(prefix[i])) {
 583                        /* in="/a/b", prefix="/a/b/c/" */
 584                        while (is_dir_sep(prefix[i]))
 585                                i++;
 586                        in_off = in_len;
 587                }
 588        }
 589        in += in_off;
 590        in_len -= in_off;
 591
 592        if (i >= prefix_len) {
 593                if (!in_len)
 594                        return "./";
 595                else
 596                        return in;
 597        }
 598
 599        strbuf_reset(sb);
 600        strbuf_grow(sb, in_len);
 601
 602        while (i < prefix_len) {
 603                if (is_dir_sep(prefix[i])) {
 604                        strbuf_addstr(sb, "../");
 605                        while (is_dir_sep(prefix[i]))
 606                                i++;
 607                        continue;
 608                }
 609                i++;
 610        }
 611        if (!is_dir_sep(prefix[prefix_len - 1]))
 612                strbuf_addstr(sb, "../");
 613
 614        strbuf_addstr(sb, in);
 615
 616        return sb->buf;
 617}
 618
 619/*
 620 * A simpler implementation of relative_path
 621 *
 622 * Get relative path by removing "prefix" from "in". This function
 623 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
 624 * to increase performance when traversing the path to work_tree.
 625 */
 626const char *remove_leading_path(const char *in, const char *prefix)
 627{
 628        static char buf[PATH_MAX + 1];
 629        int i = 0, j = 0;
 630
 631        if (!prefix || !prefix[0])
 632                return in;
 633        while (prefix[i]) {
 634                if (is_dir_sep(prefix[i])) {
 635                        if (!is_dir_sep(in[j]))
 636                                return in;
 637                        while (is_dir_sep(prefix[i]))
 638                                i++;
 639                        while (is_dir_sep(in[j]))
 640                                j++;
 641                        continue;
 642                } else if (in[j] != prefix[i]) {
 643                        return in;
 644                }
 645                i++;
 646                j++;
 647        }
 648        if (
 649            /* "/foo" is a prefix of "/foo" */
 650            in[j] &&
 651            /* "/foo" is not a prefix of "/foobar" */
 652            !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
 653           )
 654                return in;
 655        while (is_dir_sep(in[j]))
 656                j++;
 657        if (!in[j])
 658                strcpy(buf, ".");
 659        else
 660                strcpy(buf, in + j);
 661        return buf;
 662}
 663
 664/*
 665 * It is okay if dst == src, but they should not overlap otherwise.
 666 *
 667 * Performs the following normalizations on src, storing the result in dst:
 668 * - Ensures that components are separated by '/' (Windows only)
 669 * - Squashes sequences of '/'.
 670 * - Removes "." components.
 671 * - Removes ".." components, and the components the precede them.
 672 * Returns failure (non-zero) if a ".." component appears as first path
 673 * component anytime during the normalization. Otherwise, returns success (0).
 674 *
 675 * Note that this function is purely textual.  It does not follow symlinks,
 676 * verify the existence of the path, or make any system calls.
 677 *
 678 * prefix_len != NULL is for a specific case of prefix_pathspec():
 679 * assume that src == dst and src[0..prefix_len-1] is already
 680 * normalized, any time "../" eats up to the prefix_len part,
 681 * prefix_len is reduced. In the end prefix_len is the remaining
 682 * prefix that has not been overridden by user pathspec.
 683 */
 684int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
 685{
 686        char *dst0;
 687
 688        if (has_dos_drive_prefix(src)) {
 689                *dst++ = *src++;
 690                *dst++ = *src++;
 691        }
 692        dst0 = dst;
 693
 694        if (is_dir_sep(*src)) {
 695                *dst++ = '/';
 696                while (is_dir_sep(*src))
 697                        src++;
 698        }
 699
 700        for (;;) {
 701                char c = *src;
 702
 703                /*
 704                 * A path component that begins with . could be
 705                 * special:
 706                 * (1) "." and ends   -- ignore and terminate.
 707                 * (2) "./"           -- ignore them, eat slash and continue.
 708                 * (3) ".." and ends  -- strip one and terminate.
 709                 * (4) "../"          -- strip one, eat slash and continue.
 710                 */
 711                if (c == '.') {
 712                        if (!src[1]) {
 713                                /* (1) */
 714                                src++;
 715                        } else if (is_dir_sep(src[1])) {
 716                                /* (2) */
 717                                src += 2;
 718                                while (is_dir_sep(*src))
 719                                        src++;
 720                                continue;
 721                        } else if (src[1] == '.') {
 722                                if (!src[2]) {
 723                                        /* (3) */
 724                                        src += 2;
 725                                        goto up_one;
 726                                } else if (is_dir_sep(src[2])) {
 727                                        /* (4) */
 728                                        src += 3;
 729                                        while (is_dir_sep(*src))
 730                                                src++;
 731                                        goto up_one;
 732                                }
 733                        }
 734                }
 735
 736                /* copy up to the next '/', and eat all '/' */
 737                while ((c = *src++) != '\0' && !is_dir_sep(c))
 738                        *dst++ = c;
 739                if (is_dir_sep(c)) {
 740                        *dst++ = '/';
 741                        while (is_dir_sep(c))
 742                                c = *src++;
 743                        src--;
 744                } else if (!c)
 745                        break;
 746                continue;
 747
 748        up_one:
 749                /*
 750                 * dst0..dst is prefix portion, and dst[-1] is '/';
 751                 * go up one level.
 752                 */
 753                dst--;  /* go to trailing '/' */
 754                if (dst <= dst0)
 755                        return -1;
 756                /* Windows: dst[-1] cannot be backslash anymore */
 757                while (dst0 < dst && dst[-1] != '/')
 758                        dst--;
 759                if (prefix_len && *prefix_len > dst - dst0)
 760                        *prefix_len = dst - dst0;
 761        }
 762        *dst = '\0';
 763        return 0;
 764}
 765
 766int normalize_path_copy(char *dst, const char *src)
 767{
 768        return normalize_path_copy_len(dst, src, NULL);
 769}
 770
 771/*
 772 * path = Canonical absolute path
 773 * prefixes = string_list containing normalized, absolute paths without
 774 * trailing slashes (except for the root directory, which is denoted by "/").
 775 *
 776 * Determines, for each path in prefixes, whether the "prefix"
 777 * is an ancestor directory of path.  Returns the length of the longest
 778 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
 779 * is an ancestor.  (Note that this means 0 is returned if prefixes is
 780 * ["/"].) "/foo" is not considered an ancestor of "/foobar".  Directories
 781 * are not considered to be their own ancestors.  path must be in a
 782 * canonical form: empty components, or "." or ".." components are not
 783 * allowed.
 784 */
 785int longest_ancestor_length(const char *path, struct string_list *prefixes)
 786{
 787        int i, max_len = -1;
 788
 789        if (!strcmp(path, "/"))
 790                return -1;
 791
 792        for (i = 0; i < prefixes->nr; i++) {
 793                const char *ceil = prefixes->items[i].string;
 794                int len = strlen(ceil);
 795
 796                if (len == 1 && ceil[0] == '/')
 797                        len = 0; /* root matches anything, with length 0 */
 798                else if (!strncmp(path, ceil, len) && path[len] == '/')
 799                        ; /* match of length len */
 800                else
 801                        continue; /* no match */
 802
 803                if (len > max_len)
 804                        max_len = len;
 805        }
 806
 807        return max_len;
 808}
 809
 810/* strip arbitrary amount of directory separators at end of path */
 811static inline int chomp_trailing_dir_sep(const char *path, int len)
 812{
 813        while (len && is_dir_sep(path[len - 1]))
 814                len--;
 815        return len;
 816}
 817
 818/*
 819 * If path ends with suffix (complete path components), returns the
 820 * part before suffix (sans trailing directory separators).
 821 * Otherwise returns NULL.
 822 */
 823char *strip_path_suffix(const char *path, const char *suffix)
 824{
 825        int path_len = strlen(path), suffix_len = strlen(suffix);
 826
 827        while (suffix_len) {
 828                if (!path_len)
 829                        return NULL;
 830
 831                if (is_dir_sep(path[path_len - 1])) {
 832                        if (!is_dir_sep(suffix[suffix_len - 1]))
 833                                return NULL;
 834                        path_len = chomp_trailing_dir_sep(path, path_len);
 835                        suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
 836                }
 837                else if (path[--path_len] != suffix[--suffix_len])
 838                        return NULL;
 839        }
 840
 841        if (path_len && !is_dir_sep(path[path_len - 1]))
 842                return NULL;
 843        return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
 844}
 845
 846int daemon_avoid_alias(const char *p)
 847{
 848        int sl, ndot;
 849
 850        /*
 851         * This resurrects the belts and suspenders paranoia check by HPA
 852         * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
 853         * does not do getcwd() based path canonicalization.
 854         *
 855         * sl becomes true immediately after seeing '/' and continues to
 856         * be true as long as dots continue after that without intervening
 857         * non-dot character.
 858         */
 859        if (!p || (*p != '/' && *p != '~'))
 860                return -1;
 861        sl = 1; ndot = 0;
 862        p++;
 863
 864        while (1) {
 865                char ch = *p++;
 866                if (sl) {
 867                        if (ch == '.')
 868                                ndot++;
 869                        else if (ch == '/') {
 870                                if (ndot < 3)
 871                                        /* reject //, /./ and /../ */
 872                                        return -1;
 873                                ndot = 0;
 874                        }
 875                        else if (ch == 0) {
 876                                if (0 < ndot && ndot < 3)
 877                                        /* reject /.$ and /..$ */
 878                                        return -1;
 879                                return 0;
 880                        }
 881                        else
 882                                sl = ndot = 0;
 883                }
 884                else if (ch == 0)
 885                        return 0;
 886                else if (ch == '/') {
 887                        sl = 1;
 888                        ndot = 0;
 889                }
 890        }
 891}
 892
 893static int only_spaces_and_periods(const char *path, size_t len, size_t skip)
 894{
 895        if (len < skip)
 896                return 0;
 897        len -= skip;
 898        path += skip;
 899        while (len-- > 0) {
 900                char c = *(path++);
 901                if (c != ' ' && c != '.')
 902                        return 0;
 903        }
 904        return 1;
 905}
 906
 907int is_ntfs_dotgit(const char *name)
 908{
 909        int len;
 910
 911        for (len = 0; ; len++)
 912                if (!name[len] || name[len] == '\\' || is_dir_sep(name[len])) {
 913                        if (only_spaces_and_periods(name, len, 4) &&
 914                                        !strncasecmp(name, ".git", 4))
 915                                return 1;
 916                        if (only_spaces_and_periods(name, len, 5) &&
 917                                        !strncasecmp(name, "git~1", 5))
 918                                return 1;
 919                        if (name[len] != '\\')
 920                                return 0;
 921                        name += len + 1;
 922                        len = -1;
 923                }
 924}
 925
 926char *xdg_config_home(const char *filename)
 927{
 928        const char *home, *config_home;
 929
 930        assert(filename);
 931        config_home = getenv("XDG_CONFIG_HOME");
 932        if (config_home && *config_home)
 933                return mkpathdup("%s/git/%s", config_home, filename);
 934
 935        home = getenv("HOME");
 936        if (home)
 937                return mkpathdup("%s/.config/git/%s", home, filename);
 938        return NULL;
 939}
 940
 941GIT_PATH_FUNC(git_path_cherry_pick_head, "CHERRY_PICK_HEAD")
 942GIT_PATH_FUNC(git_path_revert_head, "REVERT_HEAD")
 943GIT_PATH_FUNC(git_path_squash_msg, "SQUASH_MSG")
 944GIT_PATH_FUNC(git_path_merge_msg, "MERGE_MSG")
 945GIT_PATH_FUNC(git_path_merge_rr, "MERGE_RR")
 946GIT_PATH_FUNC(git_path_merge_mode, "MERGE_MODE")
 947GIT_PATH_FUNC(git_path_merge_head, "MERGE_HEAD")
 948GIT_PATH_FUNC(git_path_fetch_head, "FETCH_HEAD")
 949GIT_PATH_FUNC(git_path_shallow, "shallow")