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