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