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