de4aed63df292d8814fcf4279db0062147c6cbc1
   1/*
   2 * GIT - The information manager from hell
   3 *
   4 * Copyright (C) Linus Torvalds, 2005
   5 *
   6 * This handles basic git sha1 object files - packing, unpacking,
   7 * creation etc.
   8 */
   9#include "cache.h"
  10#include "config.h"
  11#include "string-list.h"
  12#include "lockfile.h"
  13#include "delta.h"
  14#include "pack.h"
  15#include "blob.h"
  16#include "commit.h"
  17#include "run-command.h"
  18#include "tag.h"
  19#include "tree.h"
  20#include "tree-walk.h"
  21#include "refs.h"
  22#include "pack-revindex.h"
  23#include "sha1-lookup.h"
  24#include "bulk-checkin.h"
  25#include "streaming.h"
  26#include "dir.h"
  27#include "mru.h"
  28#include "list.h"
  29#include "mergesort.h"
  30#include "quote.h"
  31#include "packfile.h"
  32
  33const unsigned char null_sha1[20];
  34const struct object_id null_oid;
  35const struct object_id empty_tree_oid = {
  36        EMPTY_TREE_SHA1_BIN_LITERAL
  37};
  38const struct object_id empty_blob_oid = {
  39        EMPTY_BLOB_SHA1_BIN_LITERAL
  40};
  41
  42/*
  43 * This is meant to hold a *small* number of objects that you would
  44 * want read_sha1_file() to be able to return, but yet you do not want
  45 * to write them into the object store (e.g. a browse-only
  46 * application).
  47 */
  48static struct cached_object {
  49        unsigned char sha1[20];
  50        enum object_type type;
  51        void *buf;
  52        unsigned long size;
  53} *cached_objects;
  54static int cached_object_nr, cached_object_alloc;
  55
  56static struct cached_object empty_tree = {
  57        EMPTY_TREE_SHA1_BIN_LITERAL,
  58        OBJ_TREE,
  59        "",
  60        0
  61};
  62
  63static struct cached_object *find_cached_object(const unsigned char *sha1)
  64{
  65        int i;
  66        struct cached_object *co = cached_objects;
  67
  68        for (i = 0; i < cached_object_nr; i++, co++) {
  69                if (!hashcmp(co->sha1, sha1))
  70                        return co;
  71        }
  72        if (!hashcmp(sha1, empty_tree.sha1))
  73                return &empty_tree;
  74        return NULL;
  75}
  76
  77int mkdir_in_gitdir(const char *path)
  78{
  79        if (mkdir(path, 0777)) {
  80                int saved_errno = errno;
  81                struct stat st;
  82                struct strbuf sb = STRBUF_INIT;
  83
  84                if (errno != EEXIST)
  85                        return -1;
  86                /*
  87                 * Are we looking at a path in a symlinked worktree
  88                 * whose original repository does not yet have it?
  89                 * e.g. .git/rr-cache pointing at its original
  90                 * repository in which the user hasn't performed any
  91                 * conflict resolution yet?
  92                 */
  93                if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
  94                    strbuf_readlink(&sb, path, st.st_size) ||
  95                    !is_absolute_path(sb.buf) ||
  96                    mkdir(sb.buf, 0777)) {
  97                        strbuf_release(&sb);
  98                        errno = saved_errno;
  99                        return -1;
 100                }
 101                strbuf_release(&sb);
 102        }
 103        return adjust_shared_perm(path);
 104}
 105
 106enum scld_error safe_create_leading_directories(char *path)
 107{
 108        char *next_component = path + offset_1st_component(path);
 109        enum scld_error ret = SCLD_OK;
 110
 111        while (ret == SCLD_OK && next_component) {
 112                struct stat st;
 113                char *slash = next_component, slash_character;
 114
 115                while (*slash && !is_dir_sep(*slash))
 116                        slash++;
 117
 118                if (!*slash)
 119                        break;
 120
 121                next_component = slash + 1;
 122                while (is_dir_sep(*next_component))
 123                        next_component++;
 124                if (!*next_component)
 125                        break;
 126
 127                slash_character = *slash;
 128                *slash = '\0';
 129                if (!stat(path, &st)) {
 130                        /* path exists */
 131                        if (!S_ISDIR(st.st_mode)) {
 132                                errno = ENOTDIR;
 133                                ret = SCLD_EXISTS;
 134                        }
 135                } else if (mkdir(path, 0777)) {
 136                        if (errno == EEXIST &&
 137                            !stat(path, &st) && S_ISDIR(st.st_mode))
 138                                ; /* somebody created it since we checked */
 139                        else if (errno == ENOENT)
 140                                /*
 141                                 * Either mkdir() failed because
 142                                 * somebody just pruned the containing
 143                                 * directory, or stat() failed because
 144                                 * the file that was in our way was
 145                                 * just removed.  Either way, inform
 146                                 * the caller that it might be worth
 147                                 * trying again:
 148                                 */
 149                                ret = SCLD_VANISHED;
 150                        else
 151                                ret = SCLD_FAILED;
 152                } else if (adjust_shared_perm(path)) {
 153                        ret = SCLD_PERMS;
 154                }
 155                *slash = slash_character;
 156        }
 157        return ret;
 158}
 159
 160enum scld_error safe_create_leading_directories_const(const char *path)
 161{
 162        int save_errno;
 163        /* path points to cache entries, so xstrdup before messing with it */
 164        char *buf = xstrdup(path);
 165        enum scld_error result = safe_create_leading_directories(buf);
 166
 167        save_errno = errno;
 168        free(buf);
 169        errno = save_errno;
 170        return result;
 171}
 172
 173int raceproof_create_file(const char *path, create_file_fn fn, void *cb)
 174{
 175        /*
 176         * The number of times we will try to remove empty directories
 177         * in the way of path. This is only 1 because if another
 178         * process is racily creating directories that conflict with
 179         * us, we don't want to fight against them.
 180         */
 181        int remove_directories_remaining = 1;
 182
 183        /*
 184         * The number of times that we will try to create the
 185         * directories containing path. We are willing to attempt this
 186         * more than once, because another process could be trying to
 187         * clean up empty directories at the same time as we are
 188         * trying to create them.
 189         */
 190        int create_directories_remaining = 3;
 191
 192        /* A scratch copy of path, filled lazily if we need it: */
 193        struct strbuf path_copy = STRBUF_INIT;
 194
 195        int ret, save_errno;
 196
 197        /* Sanity check: */
 198        assert(*path);
 199
 200retry_fn:
 201        ret = fn(path, cb);
 202        save_errno = errno;
 203        if (!ret)
 204                goto out;
 205
 206        if (errno == EISDIR && remove_directories_remaining-- > 0) {
 207                /*
 208                 * A directory is in the way. Maybe it is empty; try
 209                 * to remove it:
 210                 */
 211                if (!path_copy.len)
 212                        strbuf_addstr(&path_copy, path);
 213
 214                if (!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY))
 215                        goto retry_fn;
 216        } else if (errno == ENOENT && create_directories_remaining-- > 0) {
 217                /*
 218                 * Maybe the containing directory didn't exist, or
 219                 * maybe it was just deleted by a process that is
 220                 * racing with us to clean up empty directories. Try
 221                 * to create it:
 222                 */
 223                enum scld_error scld_result;
 224
 225                if (!path_copy.len)
 226                        strbuf_addstr(&path_copy, path);
 227
 228                do {
 229                        scld_result = safe_create_leading_directories(path_copy.buf);
 230                        if (scld_result == SCLD_OK)
 231                                goto retry_fn;
 232                } while (scld_result == SCLD_VANISHED && create_directories_remaining-- > 0);
 233        }
 234
 235out:
 236        strbuf_release(&path_copy);
 237        errno = save_errno;
 238        return ret;
 239}
 240
 241static void fill_sha1_path(struct strbuf *buf, const unsigned char *sha1)
 242{
 243        int i;
 244        for (i = 0; i < 20; i++) {
 245                static char hex[] = "0123456789abcdef";
 246                unsigned int val = sha1[i];
 247                strbuf_addch(buf, hex[val >> 4]);
 248                strbuf_addch(buf, hex[val & 0xf]);
 249                if (!i)
 250                        strbuf_addch(buf, '/');
 251        }
 252}
 253
 254const char *sha1_file_name(const unsigned char *sha1)
 255{
 256        static struct strbuf buf = STRBUF_INIT;
 257
 258        strbuf_reset(&buf);
 259        strbuf_addf(&buf, "%s/", get_object_directory());
 260
 261        fill_sha1_path(&buf, sha1);
 262        return buf.buf;
 263}
 264
 265struct strbuf *alt_scratch_buf(struct alternate_object_database *alt)
 266{
 267        strbuf_setlen(&alt->scratch, alt->base_len);
 268        return &alt->scratch;
 269}
 270
 271static const char *alt_sha1_path(struct alternate_object_database *alt,
 272                                 const unsigned char *sha1)
 273{
 274        struct strbuf *buf = alt_scratch_buf(alt);
 275        fill_sha1_path(buf, sha1);
 276        return buf->buf;
 277}
 278
 279struct alternate_object_database *alt_odb_list;
 280static struct alternate_object_database **alt_odb_tail;
 281
 282/*
 283 * Return non-zero iff the path is usable as an alternate object database.
 284 */
 285static int alt_odb_usable(struct strbuf *path, const char *normalized_objdir)
 286{
 287        struct alternate_object_database *alt;
 288
 289        /* Detect cases where alternate disappeared */
 290        if (!is_directory(path->buf)) {
 291                error("object directory %s does not exist; "
 292                      "check .git/objects/info/alternates.",
 293                      path->buf);
 294                return 0;
 295        }
 296
 297        /*
 298         * Prevent the common mistake of listing the same
 299         * thing twice, or object directory itself.
 300         */
 301        for (alt = alt_odb_list; alt; alt = alt->next) {
 302                if (!fspathcmp(path->buf, alt->path))
 303                        return 0;
 304        }
 305        if (!fspathcmp(path->buf, normalized_objdir))
 306                return 0;
 307
 308        return 1;
 309}
 310
 311/*
 312 * Prepare alternate object database registry.
 313 *
 314 * The variable alt_odb_list points at the list of struct
 315 * alternate_object_database.  The elements on this list come from
 316 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
 317 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
 318 * whose contents is similar to that environment variable but can be
 319 * LF separated.  Its base points at a statically allocated buffer that
 320 * contains "/the/directory/corresponding/to/.git/objects/...", while
 321 * its name points just after the slash at the end of ".git/objects/"
 322 * in the example above, and has enough space to hold 40-byte hex
 323 * SHA1, an extra slash for the first level indirection, and the
 324 * terminating NUL.
 325 */
 326static void read_info_alternates(const char * relative_base, int depth);
 327static int link_alt_odb_entry(const char *entry, const char *relative_base,
 328        int depth, const char *normalized_objdir)
 329{
 330        struct alternate_object_database *ent;
 331        struct strbuf pathbuf = STRBUF_INIT;
 332
 333        if (!is_absolute_path(entry) && relative_base) {
 334                strbuf_realpath(&pathbuf, relative_base, 1);
 335                strbuf_addch(&pathbuf, '/');
 336        }
 337        strbuf_addstr(&pathbuf, entry);
 338
 339        if (strbuf_normalize_path(&pathbuf) < 0 && relative_base) {
 340                error("unable to normalize alternate object path: %s",
 341                      pathbuf.buf);
 342                strbuf_release(&pathbuf);
 343                return -1;
 344        }
 345
 346        /*
 347         * The trailing slash after the directory name is given by
 348         * this function at the end. Remove duplicates.
 349         */
 350        while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
 351                strbuf_setlen(&pathbuf, pathbuf.len - 1);
 352
 353        if (!alt_odb_usable(&pathbuf, normalized_objdir)) {
 354                strbuf_release(&pathbuf);
 355                return -1;
 356        }
 357
 358        ent = alloc_alt_odb(pathbuf.buf);
 359
 360        /* add the alternate entry */
 361        *alt_odb_tail = ent;
 362        alt_odb_tail = &(ent->next);
 363        ent->next = NULL;
 364
 365        /* recursively add alternates */
 366        read_info_alternates(pathbuf.buf, depth + 1);
 367
 368        strbuf_release(&pathbuf);
 369        return 0;
 370}
 371
 372static const char *parse_alt_odb_entry(const char *string,
 373                                       int sep,
 374                                       struct strbuf *out)
 375{
 376        const char *end;
 377
 378        strbuf_reset(out);
 379
 380        if (*string == '#') {
 381                /* comment; consume up to next separator */
 382                end = strchrnul(string, sep);
 383        } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
 384                /*
 385                 * quoted path; unquote_c_style has copied the
 386                 * data for us and set "end". Broken quoting (e.g.,
 387                 * an entry that doesn't end with a quote) falls
 388                 * back to the unquoted case below.
 389                 */
 390        } else {
 391                /* normal, unquoted path */
 392                end = strchrnul(string, sep);
 393                strbuf_add(out, string, end - string);
 394        }
 395
 396        if (*end)
 397                end++;
 398        return end;
 399}
 400
 401static void link_alt_odb_entries(const char *alt, int len, int sep,
 402                                 const char *relative_base, int depth)
 403{
 404        struct strbuf objdirbuf = STRBUF_INIT;
 405        struct strbuf entry = STRBUF_INIT;
 406
 407        if (depth > 5) {
 408                error("%s: ignoring alternate object stores, nesting too deep.",
 409                                relative_base);
 410                return;
 411        }
 412
 413        strbuf_add_absolute_path(&objdirbuf, get_object_directory());
 414        if (strbuf_normalize_path(&objdirbuf) < 0)
 415                die("unable to normalize object directory: %s",
 416                    objdirbuf.buf);
 417
 418        while (*alt) {
 419                alt = parse_alt_odb_entry(alt, sep, &entry);
 420                if (!entry.len)
 421                        continue;
 422                link_alt_odb_entry(entry.buf, relative_base, depth, objdirbuf.buf);
 423        }
 424        strbuf_release(&entry);
 425        strbuf_release(&objdirbuf);
 426}
 427
 428static void read_info_alternates(const char * relative_base, int depth)
 429{
 430        char *map;
 431        size_t mapsz;
 432        struct stat st;
 433        char *path;
 434        int fd;
 435
 436        path = xstrfmt("%s/info/alternates", relative_base);
 437        fd = git_open(path);
 438        free(path);
 439        if (fd < 0)
 440                return;
 441        if (fstat(fd, &st) || (st.st_size == 0)) {
 442                close(fd);
 443                return;
 444        }
 445        mapsz = xsize_t(st.st_size);
 446        map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
 447        close(fd);
 448
 449        link_alt_odb_entries(map, mapsz, '\n', relative_base, depth);
 450
 451        munmap(map, mapsz);
 452}
 453
 454struct alternate_object_database *alloc_alt_odb(const char *dir)
 455{
 456        struct alternate_object_database *ent;
 457
 458        FLEX_ALLOC_STR(ent, path, dir);
 459        strbuf_init(&ent->scratch, 0);
 460        strbuf_addf(&ent->scratch, "%s/", dir);
 461        ent->base_len = ent->scratch.len;
 462
 463        return ent;
 464}
 465
 466void add_to_alternates_file(const char *reference)
 467{
 468        struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
 469        char *alts = git_pathdup("objects/info/alternates");
 470        FILE *in, *out;
 471
 472        hold_lock_file_for_update(lock, alts, LOCK_DIE_ON_ERROR);
 473        out = fdopen_lock_file(lock, "w");
 474        if (!out)
 475                die_errno("unable to fdopen alternates lockfile");
 476
 477        in = fopen(alts, "r");
 478        if (in) {
 479                struct strbuf line = STRBUF_INIT;
 480                int found = 0;
 481
 482                while (strbuf_getline(&line, in) != EOF) {
 483                        if (!strcmp(reference, line.buf)) {
 484                                found = 1;
 485                                break;
 486                        }
 487                        fprintf_or_die(out, "%s\n", line.buf);
 488                }
 489
 490                strbuf_release(&line);
 491                fclose(in);
 492
 493                if (found) {
 494                        rollback_lock_file(lock);
 495                        lock = NULL;
 496                }
 497        }
 498        else if (errno != ENOENT)
 499                die_errno("unable to read alternates file");
 500
 501        if (lock) {
 502                fprintf_or_die(out, "%s\n", reference);
 503                if (commit_lock_file(lock))
 504                        die_errno("unable to move new alternates file into place");
 505                if (alt_odb_tail)
 506                        link_alt_odb_entries(reference, strlen(reference), '\n', NULL, 0);
 507        }
 508        free(alts);
 509}
 510
 511void add_to_alternates_memory(const char *reference)
 512{
 513        /*
 514         * Make sure alternates are initialized, or else our entry may be
 515         * overwritten when they are.
 516         */
 517        prepare_alt_odb();
 518
 519        link_alt_odb_entries(reference, strlen(reference), '\n', NULL, 0);
 520}
 521
 522/*
 523 * Compute the exact path an alternate is at and returns it. In case of
 524 * error NULL is returned and the human readable error is added to `err`
 525 * `path` may be relative and should point to $GITDIR.
 526 * `err` must not be null.
 527 */
 528char *compute_alternate_path(const char *path, struct strbuf *err)
 529{
 530        char *ref_git = NULL;
 531        const char *repo, *ref_git_s;
 532        int seen_error = 0;
 533
 534        ref_git_s = real_path_if_valid(path);
 535        if (!ref_git_s) {
 536                seen_error = 1;
 537                strbuf_addf(err, _("path '%s' does not exist"), path);
 538                goto out;
 539        } else
 540                /*
 541                 * Beware: read_gitfile(), real_path() and mkpath()
 542                 * return static buffer
 543                 */
 544                ref_git = xstrdup(ref_git_s);
 545
 546        repo = read_gitfile(ref_git);
 547        if (!repo)
 548                repo = read_gitfile(mkpath("%s/.git", ref_git));
 549        if (repo) {
 550                free(ref_git);
 551                ref_git = xstrdup(repo);
 552        }
 553
 554        if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
 555                char *ref_git_git = mkpathdup("%s/.git", ref_git);
 556                free(ref_git);
 557                ref_git = ref_git_git;
 558        } else if (!is_directory(mkpath("%s/objects", ref_git))) {
 559                struct strbuf sb = STRBUF_INIT;
 560                seen_error = 1;
 561                if (get_common_dir(&sb, ref_git)) {
 562                        strbuf_addf(err,
 563                                    _("reference repository '%s' as a linked "
 564                                      "checkout is not supported yet."),
 565                                    path);
 566                        goto out;
 567                }
 568
 569                strbuf_addf(err, _("reference repository '%s' is not a "
 570                                        "local repository."), path);
 571                goto out;
 572        }
 573
 574        if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
 575                strbuf_addf(err, _("reference repository '%s' is shallow"),
 576                            path);
 577                seen_error = 1;
 578                goto out;
 579        }
 580
 581        if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
 582                strbuf_addf(err,
 583                            _("reference repository '%s' is grafted"),
 584                            path);
 585                seen_error = 1;
 586                goto out;
 587        }
 588
 589out:
 590        if (seen_error) {
 591                FREE_AND_NULL(ref_git);
 592        }
 593
 594        return ref_git;
 595}
 596
 597int foreach_alt_odb(alt_odb_fn fn, void *cb)
 598{
 599        struct alternate_object_database *ent;
 600        int r = 0;
 601
 602        prepare_alt_odb();
 603        for (ent = alt_odb_list; ent; ent = ent->next) {
 604                r = fn(ent, cb);
 605                if (r)
 606                        break;
 607        }
 608        return r;
 609}
 610
 611void prepare_alt_odb(void)
 612{
 613        const char *alt;
 614
 615        if (alt_odb_tail)
 616                return;
 617
 618        alt = getenv(ALTERNATE_DB_ENVIRONMENT);
 619        if (!alt) alt = "";
 620
 621        alt_odb_tail = &alt_odb_list;
 622        link_alt_odb_entries(alt, strlen(alt), PATH_SEP, NULL, 0);
 623
 624        read_info_alternates(get_object_directory(), 0);
 625}
 626
 627/* Returns 1 if we have successfully freshened the file, 0 otherwise. */
 628static int freshen_file(const char *fn)
 629{
 630        struct utimbuf t;
 631        t.actime = t.modtime = time(NULL);
 632        return !utime(fn, &t);
 633}
 634
 635/*
 636 * All of the check_and_freshen functions return 1 if the file exists and was
 637 * freshened (if freshening was requested), 0 otherwise. If they return
 638 * 0, you should not assume that it is safe to skip a write of the object (it
 639 * either does not exist on disk, or has a stale mtime and may be subject to
 640 * pruning).
 641 */
 642int check_and_freshen_file(const char *fn, int freshen)
 643{
 644        if (access(fn, F_OK))
 645                return 0;
 646        if (freshen && !freshen_file(fn))
 647                return 0;
 648        return 1;
 649}
 650
 651static int check_and_freshen_local(const unsigned char *sha1, int freshen)
 652{
 653        return check_and_freshen_file(sha1_file_name(sha1), freshen);
 654}
 655
 656static int check_and_freshen_nonlocal(const unsigned char *sha1, int freshen)
 657{
 658        struct alternate_object_database *alt;
 659        prepare_alt_odb();
 660        for (alt = alt_odb_list; alt; alt = alt->next) {
 661                const char *path = alt_sha1_path(alt, sha1);
 662                if (check_and_freshen_file(path, freshen))
 663                        return 1;
 664        }
 665        return 0;
 666}
 667
 668static int check_and_freshen(const unsigned char *sha1, int freshen)
 669{
 670        return check_and_freshen_local(sha1, freshen) ||
 671               check_and_freshen_nonlocal(sha1, freshen);
 672}
 673
 674int has_loose_object_nonlocal(const unsigned char *sha1)
 675{
 676        return check_and_freshen_nonlocal(sha1, 0);
 677}
 678
 679static int has_loose_object(const unsigned char *sha1)
 680{
 681        return check_and_freshen(sha1, 0);
 682}
 683
 684static void mmap_limit_check(size_t length)
 685{
 686        static size_t limit = 0;
 687        if (!limit) {
 688                limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
 689                if (!limit)
 690                        limit = SIZE_MAX;
 691        }
 692        if (length > limit)
 693                die("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX,
 694                    (uintmax_t)length, (uintmax_t)limit);
 695}
 696
 697void *xmmap_gently(void *start, size_t length,
 698                  int prot, int flags, int fd, off_t offset)
 699{
 700        void *ret;
 701
 702        mmap_limit_check(length);
 703        ret = mmap(start, length, prot, flags, fd, offset);
 704        if (ret == MAP_FAILED) {
 705                if (!length)
 706                        return NULL;
 707                release_pack_memory(length);
 708                ret = mmap(start, length, prot, flags, fd, offset);
 709        }
 710        return ret;
 711}
 712
 713void *xmmap(void *start, size_t length,
 714        int prot, int flags, int fd, off_t offset)
 715{
 716        void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
 717        if (ret == MAP_FAILED)
 718                die_errno("mmap failed");
 719        return ret;
 720}
 721
 722/*
 723 * The LRU pack is the one with the oldest MRU window, preferring packs
 724 * with no used windows, or the oldest mtime if it has no windows allocated.
 725 */
 726static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
 727{
 728        struct pack_window *w, *this_mru_w;
 729        int has_windows_inuse = 0;
 730
 731        /*
 732         * Reject this pack if it has windows and the previously selected
 733         * one does not.  If this pack does not have windows, reject
 734         * it if the pack file is newer than the previously selected one.
 735         */
 736        if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
 737                return;
 738
 739        for (w = this_mru_w = p->windows; w; w = w->next) {
 740                /*
 741                 * Reject this pack if any of its windows are in use,
 742                 * but the previously selected pack did not have any
 743                 * inuse windows.  Otherwise, record that this pack
 744                 * has windows in use.
 745                 */
 746                if (w->inuse_cnt) {
 747                        if (*accept_windows_inuse)
 748                                has_windows_inuse = 1;
 749                        else
 750                                return;
 751                }
 752
 753                if (w->last_used > this_mru_w->last_used)
 754                        this_mru_w = w;
 755
 756                /*
 757                 * Reject this pack if it has windows that have been
 758                 * used more recently than the previously selected pack.
 759                 * If the previously selected pack had windows inuse and
 760                 * we have not encountered a window in this pack that is
 761                 * inuse, skip this check since we prefer a pack with no
 762                 * inuse windows to one that has inuse windows.
 763                 */
 764                if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
 765                    this_mru_w->last_used > (*mru_w)->last_used)
 766                        return;
 767        }
 768
 769        /*
 770         * Select this pack.
 771         */
 772        *mru_w = this_mru_w;
 773        *lru_p = p;
 774        *accept_windows_inuse = has_windows_inuse;
 775}
 776
 777static int close_one_pack(void)
 778{
 779        struct packed_git *p, *lru_p = NULL;
 780        struct pack_window *mru_w = NULL;
 781        int accept_windows_inuse = 1;
 782
 783        for (p = packed_git; p; p = p->next) {
 784                if (p->pack_fd == -1)
 785                        continue;
 786                find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
 787        }
 788
 789        if (lru_p)
 790                return close_pack_fd(lru_p);
 791
 792        return 0;
 793}
 794
 795void unuse_pack(struct pack_window **w_cursor)
 796{
 797        struct pack_window *w = *w_cursor;
 798        if (w) {
 799                w->inuse_cnt--;
 800                *w_cursor = NULL;
 801        }
 802}
 803
 804static unsigned int get_max_fd_limit(void)
 805{
 806#ifdef RLIMIT_NOFILE
 807        {
 808                struct rlimit lim;
 809
 810                if (!getrlimit(RLIMIT_NOFILE, &lim))
 811                        return lim.rlim_cur;
 812        }
 813#endif
 814
 815#ifdef _SC_OPEN_MAX
 816        {
 817                long open_max = sysconf(_SC_OPEN_MAX);
 818                if (0 < open_max)
 819                        return open_max;
 820                /*
 821                 * Otherwise, we got -1 for one of the two
 822                 * reasons:
 823                 *
 824                 * (1) sysconf() did not understand _SC_OPEN_MAX
 825                 *     and signaled an error with -1; or
 826                 * (2) sysconf() said there is no limit.
 827                 *
 828                 * We _could_ clear errno before calling sysconf() to
 829                 * tell these two cases apart and return a huge number
 830                 * in the latter case to let the caller cap it to a
 831                 * value that is not so selfish, but letting the
 832                 * fallback OPEN_MAX codepath take care of these cases
 833                 * is a lot simpler.
 834                 */
 835        }
 836#endif
 837
 838#ifdef OPEN_MAX
 839        return OPEN_MAX;
 840#else
 841        return 1; /* see the caller ;-) */
 842#endif
 843}
 844
 845/*
 846 * Do not call this directly as this leaks p->pack_fd on error return;
 847 * call open_packed_git() instead.
 848 */
 849static int open_packed_git_1(struct packed_git *p)
 850{
 851        struct stat st;
 852        struct pack_header hdr;
 853        unsigned char sha1[20];
 854        unsigned char *idx_sha1;
 855        long fd_flag;
 856
 857        if (!p->index_data && open_pack_index(p))
 858                return error("packfile %s index unavailable", p->pack_name);
 859
 860        if (!pack_max_fds) {
 861                unsigned int max_fds = get_max_fd_limit();
 862
 863                /* Save 3 for stdin/stdout/stderr, 22 for work */
 864                if (25 < max_fds)
 865                        pack_max_fds = max_fds - 25;
 866                else
 867                        pack_max_fds = 1;
 868        }
 869
 870        while (pack_max_fds <= pack_open_fds && close_one_pack())
 871                ; /* nothing */
 872
 873        p->pack_fd = git_open(p->pack_name);
 874        if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
 875                return -1;
 876        pack_open_fds++;
 877
 878        /* If we created the struct before we had the pack we lack size. */
 879        if (!p->pack_size) {
 880                if (!S_ISREG(st.st_mode))
 881                        return error("packfile %s not a regular file", p->pack_name);
 882                p->pack_size = st.st_size;
 883        } else if (p->pack_size != st.st_size)
 884                return error("packfile %s size changed", p->pack_name);
 885
 886        /* We leave these file descriptors open with sliding mmap;
 887         * there is no point keeping them open across exec(), though.
 888         */
 889        fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
 890        if (fd_flag < 0)
 891                return error("cannot determine file descriptor flags");
 892        fd_flag |= FD_CLOEXEC;
 893        if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
 894                return error("cannot set FD_CLOEXEC");
 895
 896        /* Verify we recognize this pack file format. */
 897        if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
 898                return error("file %s is far too short to be a packfile", p->pack_name);
 899        if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
 900                return error("file %s is not a GIT packfile", p->pack_name);
 901        if (!pack_version_ok(hdr.hdr_version))
 902                return error("packfile %s is version %"PRIu32" and not"
 903                        " supported (try upgrading GIT to a newer version)",
 904                        p->pack_name, ntohl(hdr.hdr_version));
 905
 906        /* Verify the pack matches its index. */
 907        if (p->num_objects != ntohl(hdr.hdr_entries))
 908                return error("packfile %s claims to have %"PRIu32" objects"
 909                             " while index indicates %"PRIu32" objects",
 910                             p->pack_name, ntohl(hdr.hdr_entries),
 911                             p->num_objects);
 912        if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
 913                return error("end of packfile %s is unavailable", p->pack_name);
 914        if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
 915                return error("packfile %s signature is unavailable", p->pack_name);
 916        idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
 917        if (hashcmp(sha1, idx_sha1))
 918                return error("packfile %s does not match index", p->pack_name);
 919        return 0;
 920}
 921
 922static int open_packed_git(struct packed_git *p)
 923{
 924        if (!open_packed_git_1(p))
 925                return 0;
 926        close_pack_fd(p);
 927        return -1;
 928}
 929
 930static int in_window(struct pack_window *win, off_t offset)
 931{
 932        /* We must promise at least 20 bytes (one hash) after the
 933         * offset is available from this window, otherwise the offset
 934         * is not actually in this window and a different window (which
 935         * has that one hash excess) must be used.  This is to support
 936         * the object header and delta base parsing routines below.
 937         */
 938        off_t win_off = win->offset;
 939        return win_off <= offset
 940                && (offset + 20) <= (win_off + win->len);
 941}
 942
 943unsigned char *use_pack(struct packed_git *p,
 944                struct pack_window **w_cursor,
 945                off_t offset,
 946                unsigned long *left)
 947{
 948        struct pack_window *win = *w_cursor;
 949
 950        /* Since packfiles end in a hash of their content and it's
 951         * pointless to ask for an offset into the middle of that
 952         * hash, and the in_window function above wouldn't match
 953         * don't allow an offset too close to the end of the file.
 954         */
 955        if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
 956                die("packfile %s cannot be accessed", p->pack_name);
 957        if (offset > (p->pack_size - 20))
 958                die("offset beyond end of packfile (truncated pack?)");
 959        if (offset < 0)
 960                die(_("offset before end of packfile (broken .idx?)"));
 961
 962        if (!win || !in_window(win, offset)) {
 963                if (win)
 964                        win->inuse_cnt--;
 965                for (win = p->windows; win; win = win->next) {
 966                        if (in_window(win, offset))
 967                                break;
 968                }
 969                if (!win) {
 970                        size_t window_align = packed_git_window_size / 2;
 971                        off_t len;
 972
 973                        if (p->pack_fd == -1 && open_packed_git(p))
 974                                die("packfile %s cannot be accessed", p->pack_name);
 975
 976                        win = xcalloc(1, sizeof(*win));
 977                        win->offset = (offset / window_align) * window_align;
 978                        len = p->pack_size - win->offset;
 979                        if (len > packed_git_window_size)
 980                                len = packed_git_window_size;
 981                        win->len = (size_t)len;
 982                        pack_mapped += win->len;
 983                        while (packed_git_limit < pack_mapped
 984                                && unuse_one_window(p))
 985                                ; /* nothing */
 986                        win->base = xmmap(NULL, win->len,
 987                                PROT_READ, MAP_PRIVATE,
 988                                p->pack_fd, win->offset);
 989                        if (win->base == MAP_FAILED)
 990                                die_errno("packfile %s cannot be mapped",
 991                                          p->pack_name);
 992                        if (!win->offset && win->len == p->pack_size
 993                                && !p->do_not_close)
 994                                close_pack_fd(p);
 995                        pack_mmap_calls++;
 996                        pack_open_windows++;
 997                        if (pack_mapped > peak_pack_mapped)
 998                                peak_pack_mapped = pack_mapped;
 999                        if (pack_open_windows > peak_pack_open_windows)
1000                                peak_pack_open_windows = pack_open_windows;
1001                        win->next = p->windows;
1002                        p->windows = win;
1003                }
1004        }
1005        if (win != *w_cursor) {
1006                win->last_used = pack_used_ctr++;
1007                win->inuse_cnt++;
1008                *w_cursor = win;
1009        }
1010        offset -= win->offset;
1011        if (left)
1012                *left = win->len - xsize_t(offset);
1013        return win->base + offset;
1014}
1015
1016static struct packed_git *alloc_packed_git(int extra)
1017{
1018        struct packed_git *p = xmalloc(st_add(sizeof(*p), extra));
1019        memset(p, 0, sizeof(*p));
1020        p->pack_fd = -1;
1021        return p;
1022}
1023
1024static void try_to_free_pack_memory(size_t size)
1025{
1026        release_pack_memory(size);
1027}
1028
1029struct packed_git *add_packed_git(const char *path, size_t path_len, int local)
1030{
1031        static int have_set_try_to_free_routine;
1032        struct stat st;
1033        size_t alloc;
1034        struct packed_git *p;
1035
1036        if (!have_set_try_to_free_routine) {
1037                have_set_try_to_free_routine = 1;
1038                set_try_to_free_routine(try_to_free_pack_memory);
1039        }
1040
1041        /*
1042         * Make sure a corresponding .pack file exists and that
1043         * the index looks sane.
1044         */
1045        if (!strip_suffix_mem(path, &path_len, ".idx"))
1046                return NULL;
1047
1048        /*
1049         * ".pack" is long enough to hold any suffix we're adding (and
1050         * the use xsnprintf double-checks that)
1051         */
1052        alloc = st_add3(path_len, strlen(".pack"), 1);
1053        p = alloc_packed_git(alloc);
1054        memcpy(p->pack_name, path, path_len);
1055
1056        xsnprintf(p->pack_name + path_len, alloc - path_len, ".keep");
1057        if (!access(p->pack_name, F_OK))
1058                p->pack_keep = 1;
1059
1060        xsnprintf(p->pack_name + path_len, alloc - path_len, ".pack");
1061        if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
1062                free(p);
1063                return NULL;
1064        }
1065
1066        /* ok, it looks sane as far as we can check without
1067         * actually mapping the pack file.
1068         */
1069        p->pack_size = st.st_size;
1070        p->pack_local = local;
1071        p->mtime = st.st_mtime;
1072        if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
1073                hashclr(p->sha1);
1074        return p;
1075}
1076
1077void install_packed_git(struct packed_git *pack)
1078{
1079        if (pack->pack_fd != -1)
1080                pack_open_fds++;
1081
1082        pack->next = packed_git;
1083        packed_git = pack;
1084}
1085
1086void (*report_garbage)(unsigned seen_bits, const char *path);
1087
1088static void report_helper(const struct string_list *list,
1089                          int seen_bits, int first, int last)
1090{
1091        if (seen_bits == (PACKDIR_FILE_PACK|PACKDIR_FILE_IDX))
1092                return;
1093
1094        for (; first < last; first++)
1095                report_garbage(seen_bits, list->items[first].string);
1096}
1097
1098static void report_pack_garbage(struct string_list *list)
1099{
1100        int i, baselen = -1, first = 0, seen_bits = 0;
1101
1102        if (!report_garbage)
1103                return;
1104
1105        string_list_sort(list);
1106
1107        for (i = 0; i < list->nr; i++) {
1108                const char *path = list->items[i].string;
1109                if (baselen != -1 &&
1110                    strncmp(path, list->items[first].string, baselen)) {
1111                        report_helper(list, seen_bits, first, i);
1112                        baselen = -1;
1113                        seen_bits = 0;
1114                }
1115                if (baselen == -1) {
1116                        const char *dot = strrchr(path, '.');
1117                        if (!dot) {
1118                                report_garbage(PACKDIR_FILE_GARBAGE, path);
1119                                continue;
1120                        }
1121                        baselen = dot - path + 1;
1122                        first = i;
1123                }
1124                if (!strcmp(path + baselen, "pack"))
1125                        seen_bits |= 1;
1126                else if (!strcmp(path + baselen, "idx"))
1127                        seen_bits |= 2;
1128        }
1129        report_helper(list, seen_bits, first, list->nr);
1130}
1131
1132static void prepare_packed_git_one(char *objdir, int local)
1133{
1134        struct strbuf path = STRBUF_INIT;
1135        size_t dirnamelen;
1136        DIR *dir;
1137        struct dirent *de;
1138        struct string_list garbage = STRING_LIST_INIT_DUP;
1139
1140        strbuf_addstr(&path, objdir);
1141        strbuf_addstr(&path, "/pack");
1142        dir = opendir(path.buf);
1143        if (!dir) {
1144                if (errno != ENOENT)
1145                        error_errno("unable to open object pack directory: %s",
1146                                    path.buf);
1147                strbuf_release(&path);
1148                return;
1149        }
1150        strbuf_addch(&path, '/');
1151        dirnamelen = path.len;
1152        while ((de = readdir(dir)) != NULL) {
1153                struct packed_git *p;
1154                size_t base_len;
1155
1156                if (is_dot_or_dotdot(de->d_name))
1157                        continue;
1158
1159                strbuf_setlen(&path, dirnamelen);
1160                strbuf_addstr(&path, de->d_name);
1161
1162                base_len = path.len;
1163                if (strip_suffix_mem(path.buf, &base_len, ".idx")) {
1164                        /* Don't reopen a pack we already have. */
1165                        for (p = packed_git; p; p = p->next) {
1166                                size_t len;
1167                                if (strip_suffix(p->pack_name, ".pack", &len) &&
1168                                    len == base_len &&
1169                                    !memcmp(p->pack_name, path.buf, len))
1170                                        break;
1171                        }
1172                        if (p == NULL &&
1173                            /*
1174                             * See if it really is a valid .idx file with
1175                             * corresponding .pack file that we can map.
1176                             */
1177                            (p = add_packed_git(path.buf, path.len, local)) != NULL)
1178                                install_packed_git(p);
1179                }
1180
1181                if (!report_garbage)
1182                        continue;
1183
1184                if (ends_with(de->d_name, ".idx") ||
1185                    ends_with(de->d_name, ".pack") ||
1186                    ends_with(de->d_name, ".bitmap") ||
1187                    ends_with(de->d_name, ".keep"))
1188                        string_list_append(&garbage, path.buf);
1189                else
1190                        report_garbage(PACKDIR_FILE_GARBAGE, path.buf);
1191        }
1192        closedir(dir);
1193        report_pack_garbage(&garbage);
1194        string_list_clear(&garbage, 0);
1195        strbuf_release(&path);
1196}
1197
1198static int approximate_object_count_valid;
1199
1200/*
1201 * Give a fast, rough count of the number of objects in the repository. This
1202 * ignores loose objects completely. If you have a lot of them, then either
1203 * you should repack because your performance will be awful, or they are
1204 * all unreachable objects about to be pruned, in which case they're not really
1205 * interesting as a measure of repo size in the first place.
1206 */
1207unsigned long approximate_object_count(void)
1208{
1209        static unsigned long count;
1210        if (!approximate_object_count_valid) {
1211                struct packed_git *p;
1212
1213                prepare_packed_git();
1214                count = 0;
1215                for (p = packed_git; p; p = p->next) {
1216                        if (open_pack_index(p))
1217                                continue;
1218                        count += p->num_objects;
1219                }
1220        }
1221        return count;
1222}
1223
1224static void *get_next_packed_git(const void *p)
1225{
1226        return ((const struct packed_git *)p)->next;
1227}
1228
1229static void set_next_packed_git(void *p, void *next)
1230{
1231        ((struct packed_git *)p)->next = next;
1232}
1233
1234static int sort_pack(const void *a_, const void *b_)
1235{
1236        const struct packed_git *a = a_;
1237        const struct packed_git *b = b_;
1238        int st;
1239
1240        /*
1241         * Local packs tend to contain objects specific to our
1242         * variant of the project than remote ones.  In addition,
1243         * remote ones could be on a network mounted filesystem.
1244         * Favor local ones for these reasons.
1245         */
1246        st = a->pack_local - b->pack_local;
1247        if (st)
1248                return -st;
1249
1250        /*
1251         * Younger packs tend to contain more recent objects,
1252         * and more recent objects tend to get accessed more
1253         * often.
1254         */
1255        if (a->mtime < b->mtime)
1256                return 1;
1257        else if (a->mtime == b->mtime)
1258                return 0;
1259        return -1;
1260}
1261
1262static void rearrange_packed_git(void)
1263{
1264        packed_git = llist_mergesort(packed_git, get_next_packed_git,
1265                                     set_next_packed_git, sort_pack);
1266}
1267
1268static void prepare_packed_git_mru(void)
1269{
1270        struct packed_git *p;
1271
1272        mru_clear(packed_git_mru);
1273        for (p = packed_git; p; p = p->next)
1274                mru_append(packed_git_mru, p);
1275}
1276
1277static int prepare_packed_git_run_once = 0;
1278void prepare_packed_git(void)
1279{
1280        struct alternate_object_database *alt;
1281
1282        if (prepare_packed_git_run_once)
1283                return;
1284        prepare_packed_git_one(get_object_directory(), 1);
1285        prepare_alt_odb();
1286        for (alt = alt_odb_list; alt; alt = alt->next)
1287                prepare_packed_git_one(alt->path, 0);
1288        rearrange_packed_git();
1289        prepare_packed_git_mru();
1290        prepare_packed_git_run_once = 1;
1291}
1292
1293void reprepare_packed_git(void)
1294{
1295        approximate_object_count_valid = 0;
1296        prepare_packed_git_run_once = 0;
1297        prepare_packed_git();
1298}
1299
1300static void mark_bad_packed_object(struct packed_git *p,
1301                                   const unsigned char *sha1)
1302{
1303        unsigned i;
1304        for (i = 0; i < p->num_bad_objects; i++)
1305                if (!hashcmp(sha1, p->bad_object_sha1 + GIT_SHA1_RAWSZ * i))
1306                        return;
1307        p->bad_object_sha1 = xrealloc(p->bad_object_sha1,
1308                                      st_mult(GIT_MAX_RAWSZ,
1309                                              st_add(p->num_bad_objects, 1)));
1310        hashcpy(p->bad_object_sha1 + GIT_SHA1_RAWSZ * p->num_bad_objects, sha1);
1311        p->num_bad_objects++;
1312}
1313
1314static const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
1315{
1316        struct packed_git *p;
1317        unsigned i;
1318
1319        for (p = packed_git; p; p = p->next)
1320                for (i = 0; i < p->num_bad_objects; i++)
1321                        if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1322                                return p;
1323        return NULL;
1324}
1325
1326/*
1327 * With an in-core object data in "map", rehash it to make sure the
1328 * object name actually matches "sha1" to detect object corruption.
1329 * With "map" == NULL, try reading the object named with "sha1" using
1330 * the streaming interface and rehash it to do the same.
1331 */
1332int check_sha1_signature(const unsigned char *sha1, void *map,
1333                         unsigned long size, const char *type)
1334{
1335        unsigned char real_sha1[20];
1336        enum object_type obj_type;
1337        struct git_istream *st;
1338        git_SHA_CTX c;
1339        char hdr[32];
1340        int hdrlen;
1341
1342        if (map) {
1343                hash_sha1_file(map, size, type, real_sha1);
1344                return hashcmp(sha1, real_sha1) ? -1 : 0;
1345        }
1346
1347        st = open_istream(sha1, &obj_type, &size, NULL);
1348        if (!st)
1349                return -1;
1350
1351        /* Generate the header */
1352        hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(obj_type), size) + 1;
1353
1354        /* Sha1.. */
1355        git_SHA1_Init(&c);
1356        git_SHA1_Update(&c, hdr, hdrlen);
1357        for (;;) {
1358                char buf[1024 * 16];
1359                ssize_t readlen = read_istream(st, buf, sizeof(buf));
1360
1361                if (readlen < 0) {
1362                        close_istream(st);
1363                        return -1;
1364                }
1365                if (!readlen)
1366                        break;
1367                git_SHA1_Update(&c, buf, readlen);
1368        }
1369        git_SHA1_Final(real_sha1, &c);
1370        close_istream(st);
1371        return hashcmp(sha1, real_sha1) ? -1 : 0;
1372}
1373
1374int git_open_cloexec(const char *name, int flags)
1375{
1376        int fd;
1377        static int o_cloexec = O_CLOEXEC;
1378
1379        fd = open(name, flags | o_cloexec);
1380        if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
1381                /* Try again w/o O_CLOEXEC: the kernel might not support it */
1382                o_cloexec &= ~O_CLOEXEC;
1383                fd = open(name, flags | o_cloexec);
1384        }
1385
1386#if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
1387        {
1388                static int fd_cloexec = FD_CLOEXEC;
1389
1390                if (!o_cloexec && 0 <= fd && fd_cloexec) {
1391                        /* Opened w/o O_CLOEXEC?  try with fcntl(2) to add it */
1392                        int flags = fcntl(fd, F_GETFD);
1393                        if (fcntl(fd, F_SETFD, flags | fd_cloexec))
1394                                fd_cloexec = 0;
1395                }
1396        }
1397#endif
1398        return fd;
1399}
1400
1401/*
1402 * Find "sha1" as a loose object in the local repository or in an alternate.
1403 * Returns 0 on success, negative on failure.
1404 *
1405 * The "path" out-parameter will give the path of the object we found (if any).
1406 * Note that it may point to static storage and is only valid until another
1407 * call to sha1_file_name(), etc.
1408 */
1409static int stat_sha1_file(const unsigned char *sha1, struct stat *st,
1410                          const char **path)
1411{
1412        struct alternate_object_database *alt;
1413
1414        *path = sha1_file_name(sha1);
1415        if (!lstat(*path, st))
1416                return 0;
1417
1418        prepare_alt_odb();
1419        errno = ENOENT;
1420        for (alt = alt_odb_list; alt; alt = alt->next) {
1421                *path = alt_sha1_path(alt, sha1);
1422                if (!lstat(*path, st))
1423                        return 0;
1424        }
1425
1426        return -1;
1427}
1428
1429/*
1430 * Like stat_sha1_file(), but actually open the object and return the
1431 * descriptor. See the caveats on the "path" parameter above.
1432 */
1433static int open_sha1_file(const unsigned char *sha1, const char **path)
1434{
1435        int fd;
1436        struct alternate_object_database *alt;
1437        int most_interesting_errno;
1438
1439        *path = sha1_file_name(sha1);
1440        fd = git_open(*path);
1441        if (fd >= 0)
1442                return fd;
1443        most_interesting_errno = errno;
1444
1445        prepare_alt_odb();
1446        for (alt = alt_odb_list; alt; alt = alt->next) {
1447                *path = alt_sha1_path(alt, sha1);
1448                fd = git_open(*path);
1449                if (fd >= 0)
1450                        return fd;
1451                if (most_interesting_errno == ENOENT)
1452                        most_interesting_errno = errno;
1453        }
1454        errno = most_interesting_errno;
1455        return -1;
1456}
1457
1458/*
1459 * Map the loose object at "path" if it is not NULL, or the path found by
1460 * searching for a loose object named "sha1".
1461 */
1462static void *map_sha1_file_1(const char *path,
1463                             const unsigned char *sha1,
1464                             unsigned long *size)
1465{
1466        void *map;
1467        int fd;
1468
1469        if (path)
1470                fd = git_open(path);
1471        else
1472                fd = open_sha1_file(sha1, &path);
1473        map = NULL;
1474        if (fd >= 0) {
1475                struct stat st;
1476
1477                if (!fstat(fd, &st)) {
1478                        *size = xsize_t(st.st_size);
1479                        if (!*size) {
1480                                /* mmap() is forbidden on empty files */
1481                                error("object file %s is empty", path);
1482                                return NULL;
1483                        }
1484                        map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1485                }
1486                close(fd);
1487        }
1488        return map;
1489}
1490
1491void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1492{
1493        return map_sha1_file_1(NULL, sha1, size);
1494}
1495
1496unsigned long unpack_object_header_buffer(const unsigned char *buf,
1497                unsigned long len, enum object_type *type, unsigned long *sizep)
1498{
1499        unsigned shift;
1500        unsigned long size, c;
1501        unsigned long used = 0;
1502
1503        c = buf[used++];
1504        *type = (c >> 4) & 7;
1505        size = c & 15;
1506        shift = 4;
1507        while (c & 0x80) {
1508                if (len <= used || bitsizeof(long) <= shift) {
1509                        error("bad object header");
1510                        size = used = 0;
1511                        break;
1512                }
1513                c = buf[used++];
1514                size += (c & 0x7f) << shift;
1515                shift += 7;
1516        }
1517        *sizep = size;
1518        return used;
1519}
1520
1521static int unpack_sha1_short_header(git_zstream *stream,
1522                                    unsigned char *map, unsigned long mapsize,
1523                                    void *buffer, unsigned long bufsiz)
1524{
1525        /* Get the data stream */
1526        memset(stream, 0, sizeof(*stream));
1527        stream->next_in = map;
1528        stream->avail_in = mapsize;
1529        stream->next_out = buffer;
1530        stream->avail_out = bufsiz;
1531
1532        git_inflate_init(stream);
1533        return git_inflate(stream, 0);
1534}
1535
1536int unpack_sha1_header(git_zstream *stream,
1537                       unsigned char *map, unsigned long mapsize,
1538                       void *buffer, unsigned long bufsiz)
1539{
1540        int status = unpack_sha1_short_header(stream, map, mapsize,
1541                                              buffer, bufsiz);
1542
1543        if (status < Z_OK)
1544                return status;
1545
1546        /* Make sure we have the terminating NUL */
1547        if (!memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1548                return -1;
1549        return 0;
1550}
1551
1552static int unpack_sha1_header_to_strbuf(git_zstream *stream, unsigned char *map,
1553                                        unsigned long mapsize, void *buffer,
1554                                        unsigned long bufsiz, struct strbuf *header)
1555{
1556        int status;
1557
1558        status = unpack_sha1_short_header(stream, map, mapsize, buffer, bufsiz);
1559        if (status < Z_OK)
1560                return -1;
1561
1562        /*
1563         * Check if entire header is unpacked in the first iteration.
1564         */
1565        if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1566                return 0;
1567
1568        /*
1569         * buffer[0..bufsiz] was not large enough.  Copy the partial
1570         * result out to header, and then append the result of further
1571         * reading the stream.
1572         */
1573        strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1574        stream->next_out = buffer;
1575        stream->avail_out = bufsiz;
1576
1577        do {
1578                status = git_inflate(stream, 0);
1579                strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1580                if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1581                        return 0;
1582                stream->next_out = buffer;
1583                stream->avail_out = bufsiz;
1584        } while (status != Z_STREAM_END);
1585        return -1;
1586}
1587
1588static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1589{
1590        int bytes = strlen(buffer) + 1;
1591        unsigned char *buf = xmallocz(size);
1592        unsigned long n;
1593        int status = Z_OK;
1594
1595        n = stream->total_out - bytes;
1596        if (n > size)
1597                n = size;
1598        memcpy(buf, (char *) buffer + bytes, n);
1599        bytes = n;
1600        if (bytes <= size) {
1601                /*
1602                 * The above condition must be (bytes <= size), not
1603                 * (bytes < size).  In other words, even though we
1604                 * expect no more output and set avail_out to zero,
1605                 * the input zlib stream may have bytes that express
1606                 * "this concludes the stream", and we *do* want to
1607                 * eat that input.
1608                 *
1609                 * Otherwise we would not be able to test that we
1610                 * consumed all the input to reach the expected size;
1611                 * we also want to check that zlib tells us that all
1612                 * went well with status == Z_STREAM_END at the end.
1613                 */
1614                stream->next_out = buf + bytes;
1615                stream->avail_out = size - bytes;
1616                while (status == Z_OK)
1617                        status = git_inflate(stream, Z_FINISH);
1618        }
1619        if (status == Z_STREAM_END && !stream->avail_in) {
1620                git_inflate_end(stream);
1621                return buf;
1622        }
1623
1624        if (status < 0)
1625                error("corrupt loose object '%s'", sha1_to_hex(sha1));
1626        else if (stream->avail_in)
1627                error("garbage at end of loose object '%s'",
1628                      sha1_to_hex(sha1));
1629        free(buf);
1630        return NULL;
1631}
1632
1633/*
1634 * We used to just use "sscanf()", but that's actually way
1635 * too permissive for what we want to check. So do an anal
1636 * object header parse by hand.
1637 */
1638static int parse_sha1_header_extended(const char *hdr, struct object_info *oi,
1639                               unsigned int flags)
1640{
1641        const char *type_buf = hdr;
1642        unsigned long size;
1643        int type, type_len = 0;
1644
1645        /*
1646         * The type can be of any size but is followed by
1647         * a space.
1648         */
1649        for (;;) {
1650                char c = *hdr++;
1651                if (!c)
1652                        return -1;
1653                if (c == ' ')
1654                        break;
1655                type_len++;
1656        }
1657
1658        type = type_from_string_gently(type_buf, type_len, 1);
1659        if (oi->typename)
1660                strbuf_add(oi->typename, type_buf, type_len);
1661        /*
1662         * Set type to 0 if its an unknown object and
1663         * we're obtaining the type using '--allow-unknown-type'
1664         * option.
1665         */
1666        if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE) && (type < 0))
1667                type = 0;
1668        else if (type < 0)
1669                die("invalid object type");
1670        if (oi->typep)
1671                *oi->typep = type;
1672
1673        /*
1674         * The length must follow immediately, and be in canonical
1675         * decimal format (ie "010" is not valid).
1676         */
1677        size = *hdr++ - '0';
1678        if (size > 9)
1679                return -1;
1680        if (size) {
1681                for (;;) {
1682                        unsigned long c = *hdr - '0';
1683                        if (c > 9)
1684                                break;
1685                        hdr++;
1686                        size = size * 10 + c;
1687                }
1688        }
1689
1690        if (oi->sizep)
1691                *oi->sizep = size;
1692
1693        /*
1694         * The length must be followed by a zero byte
1695         */
1696        return *hdr ? -1 : type;
1697}
1698
1699int parse_sha1_header(const char *hdr, unsigned long *sizep)
1700{
1701        struct object_info oi = OBJECT_INFO_INIT;
1702
1703        oi.sizep = sizep;
1704        return parse_sha1_header_extended(hdr, &oi, 0);
1705}
1706
1707unsigned long get_size_from_delta(struct packed_git *p,
1708                                  struct pack_window **w_curs,
1709                                  off_t curpos)
1710{
1711        const unsigned char *data;
1712        unsigned char delta_head[20], *in;
1713        git_zstream stream;
1714        int st;
1715
1716        memset(&stream, 0, sizeof(stream));
1717        stream.next_out = delta_head;
1718        stream.avail_out = sizeof(delta_head);
1719
1720        git_inflate_init(&stream);
1721        do {
1722                in = use_pack(p, w_curs, curpos, &stream.avail_in);
1723                stream.next_in = in;
1724                st = git_inflate(&stream, Z_FINISH);
1725                curpos += stream.next_in - in;
1726        } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1727                 stream.total_out < sizeof(delta_head));
1728        git_inflate_end(&stream);
1729        if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1730                error("delta data unpack-initial failed");
1731                return 0;
1732        }
1733
1734        /* Examine the initial part of the delta to figure out
1735         * the result size.
1736         */
1737        data = delta_head;
1738
1739        /* ignore base size */
1740        get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1741
1742        /* Read the result size */
1743        return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1744}
1745
1746static off_t get_delta_base(struct packed_git *p,
1747                                    struct pack_window **w_curs,
1748                                    off_t *curpos,
1749                                    enum object_type type,
1750                                    off_t delta_obj_offset)
1751{
1752        unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1753        off_t base_offset;
1754
1755        /* use_pack() assured us we have [base_info, base_info + 20)
1756         * as a range that we can look at without walking off the
1757         * end of the mapped window.  Its actually the hash size
1758         * that is assured.  An OFS_DELTA longer than the hash size
1759         * is stupid, as then a REF_DELTA would be smaller to store.
1760         */
1761        if (type == OBJ_OFS_DELTA) {
1762                unsigned used = 0;
1763                unsigned char c = base_info[used++];
1764                base_offset = c & 127;
1765                while (c & 128) {
1766                        base_offset += 1;
1767                        if (!base_offset || MSB(base_offset, 7))
1768                                return 0;  /* overflow */
1769                        c = base_info[used++];
1770                        base_offset = (base_offset << 7) + (c & 127);
1771                }
1772                base_offset = delta_obj_offset - base_offset;
1773                if (base_offset <= 0 || base_offset >= delta_obj_offset)
1774                        return 0;  /* out of bound */
1775                *curpos += used;
1776        } else if (type == OBJ_REF_DELTA) {
1777                /* The base entry _must_ be in the same pack */
1778                base_offset = find_pack_entry_one(base_info, p);
1779                *curpos += 20;
1780        } else
1781                die("I am totally screwed");
1782        return base_offset;
1783}
1784
1785/*
1786 * Like get_delta_base above, but we return the sha1 instead of the pack
1787 * offset. This means it is cheaper for REF deltas (we do not have to do
1788 * the final object lookup), but more expensive for OFS deltas (we
1789 * have to load the revidx to convert the offset back into a sha1).
1790 */
1791static const unsigned char *get_delta_base_sha1(struct packed_git *p,
1792                                                struct pack_window **w_curs,
1793                                                off_t curpos,
1794                                                enum object_type type,
1795                                                off_t delta_obj_offset)
1796{
1797        if (type == OBJ_REF_DELTA) {
1798                unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1799                return base;
1800        } else if (type == OBJ_OFS_DELTA) {
1801                struct revindex_entry *revidx;
1802                off_t base_offset = get_delta_base(p, w_curs, &curpos,
1803                                                   type, delta_obj_offset);
1804
1805                if (!base_offset)
1806                        return NULL;
1807
1808                revidx = find_pack_revindex(p, base_offset);
1809                if (!revidx)
1810                        return NULL;
1811
1812                return nth_packed_object_sha1(p, revidx->nr);
1813        } else
1814                return NULL;
1815}
1816
1817int unpack_object_header(struct packed_git *p,
1818                         struct pack_window **w_curs,
1819                         off_t *curpos,
1820                         unsigned long *sizep)
1821{
1822        unsigned char *base;
1823        unsigned long left;
1824        unsigned long used;
1825        enum object_type type;
1826
1827        /* use_pack() assures us we have [base, base + 20) available
1828         * as a range that we can look at.  (Its actually the hash
1829         * size that is assured.)  With our object header encoding
1830         * the maximum deflated object size is 2^137, which is just
1831         * insane, so we know won't exceed what we have been given.
1832         */
1833        base = use_pack(p, w_curs, *curpos, &left);
1834        used = unpack_object_header_buffer(base, left, &type, sizep);
1835        if (!used) {
1836                type = OBJ_BAD;
1837        } else
1838                *curpos += used;
1839
1840        return type;
1841}
1842
1843static int retry_bad_packed_offset(struct packed_git *p, off_t obj_offset)
1844{
1845        int type;
1846        struct revindex_entry *revidx;
1847        const unsigned char *sha1;
1848        revidx = find_pack_revindex(p, obj_offset);
1849        if (!revidx)
1850                return OBJ_BAD;
1851        sha1 = nth_packed_object_sha1(p, revidx->nr);
1852        mark_bad_packed_object(p, sha1);
1853        type = sha1_object_info(sha1, NULL);
1854        if (type <= OBJ_NONE)
1855                return OBJ_BAD;
1856        return type;
1857}
1858
1859#define POI_STACK_PREALLOC 64
1860
1861static enum object_type packed_to_object_type(struct packed_git *p,
1862                                              off_t obj_offset,
1863                                              enum object_type type,
1864                                              struct pack_window **w_curs,
1865                                              off_t curpos)
1866{
1867        off_t small_poi_stack[POI_STACK_PREALLOC];
1868        off_t *poi_stack = small_poi_stack;
1869        int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1870
1871        while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1872                off_t base_offset;
1873                unsigned long size;
1874                /* Push the object we're going to leave behind */
1875                if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1876                        poi_stack_alloc = alloc_nr(poi_stack_nr);
1877                        ALLOC_ARRAY(poi_stack, poi_stack_alloc);
1878                        memcpy(poi_stack, small_poi_stack, sizeof(off_t)*poi_stack_nr);
1879                } else {
1880                        ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1881                }
1882                poi_stack[poi_stack_nr++] = obj_offset;
1883                /* If parsing the base offset fails, just unwind */
1884                base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1885                if (!base_offset)
1886                        goto unwind;
1887                curpos = obj_offset = base_offset;
1888                type = unpack_object_header(p, w_curs, &curpos, &size);
1889                if (type <= OBJ_NONE) {
1890                        /* If getting the base itself fails, we first
1891                         * retry the base, otherwise unwind */
1892                        type = retry_bad_packed_offset(p, base_offset);
1893                        if (type > OBJ_NONE)
1894                                goto out;
1895                        goto unwind;
1896                }
1897        }
1898
1899        switch (type) {
1900        case OBJ_BAD:
1901        case OBJ_COMMIT:
1902        case OBJ_TREE:
1903        case OBJ_BLOB:
1904        case OBJ_TAG:
1905                break;
1906        default:
1907                error("unknown object type %i at offset %"PRIuMAX" in %s",
1908                      type, (uintmax_t)obj_offset, p->pack_name);
1909                type = OBJ_BAD;
1910        }
1911
1912out:
1913        if (poi_stack != small_poi_stack)
1914                free(poi_stack);
1915        return type;
1916
1917unwind:
1918        while (poi_stack_nr) {
1919                obj_offset = poi_stack[--poi_stack_nr];
1920                type = retry_bad_packed_offset(p, obj_offset);
1921                if (type > OBJ_NONE)
1922                        goto out;
1923        }
1924        type = OBJ_BAD;
1925        goto out;
1926}
1927
1928static struct hashmap delta_base_cache;
1929static size_t delta_base_cached;
1930
1931static LIST_HEAD(delta_base_cache_lru);
1932
1933struct delta_base_cache_key {
1934        struct packed_git *p;
1935        off_t base_offset;
1936};
1937
1938struct delta_base_cache_entry {
1939        struct hashmap hash;
1940        struct delta_base_cache_key key;
1941        struct list_head lru;
1942        void *data;
1943        unsigned long size;
1944        enum object_type type;
1945};
1946
1947static unsigned int pack_entry_hash(struct packed_git *p, off_t base_offset)
1948{
1949        unsigned int hash;
1950
1951        hash = (unsigned int)(intptr_t)p + (unsigned int)base_offset;
1952        hash += (hash >> 8) + (hash >> 16);
1953        return hash;
1954}
1955
1956static struct delta_base_cache_entry *
1957get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
1958{
1959        struct hashmap_entry entry;
1960        struct delta_base_cache_key key;
1961
1962        if (!delta_base_cache.cmpfn)
1963                return NULL;
1964
1965        hashmap_entry_init(&entry, pack_entry_hash(p, base_offset));
1966        key.p = p;
1967        key.base_offset = base_offset;
1968        return hashmap_get(&delta_base_cache, &entry, &key);
1969}
1970
1971static int delta_base_cache_key_eq(const struct delta_base_cache_key *a,
1972                                   const struct delta_base_cache_key *b)
1973{
1974        return a->p == b->p && a->base_offset == b->base_offset;
1975}
1976
1977static int delta_base_cache_hash_cmp(const void *unused_cmp_data,
1978                                     const void *va, const void *vb,
1979                                     const void *vkey)
1980{
1981        const struct delta_base_cache_entry *a = va, *b = vb;
1982        const struct delta_base_cache_key *key = vkey;
1983        if (key)
1984                return !delta_base_cache_key_eq(&a->key, key);
1985        else
1986                return !delta_base_cache_key_eq(&a->key, &b->key);
1987}
1988
1989static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
1990{
1991        return !!get_delta_base_cache_entry(p, base_offset);
1992}
1993
1994/*
1995 * Remove the entry from the cache, but do _not_ free the associated
1996 * entry data. The caller takes ownership of the "data" buffer, and
1997 * should copy out any fields it wants before detaching.
1998 */
1999static void detach_delta_base_cache_entry(struct delta_base_cache_entry *ent)
2000{
2001        hashmap_remove(&delta_base_cache, ent, &ent->key);
2002        list_del(&ent->lru);
2003        delta_base_cached -= ent->size;
2004        free(ent);
2005}
2006
2007static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
2008        unsigned long *base_size, enum object_type *type)
2009{
2010        struct delta_base_cache_entry *ent;
2011
2012        ent = get_delta_base_cache_entry(p, base_offset);
2013        if (!ent)
2014                return unpack_entry(p, base_offset, type, base_size);
2015
2016        if (type)
2017                *type = ent->type;
2018        if (base_size)
2019                *base_size = ent->size;
2020        return xmemdupz(ent->data, ent->size);
2021}
2022
2023static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
2024{
2025        free(ent->data);
2026        detach_delta_base_cache_entry(ent);
2027}
2028
2029void clear_delta_base_cache(void)
2030{
2031        struct list_head *lru, *tmp;
2032        list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
2033                struct delta_base_cache_entry *entry =
2034                        list_entry(lru, struct delta_base_cache_entry, lru);
2035                release_delta_base_cache(entry);
2036        }
2037}
2038
2039static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
2040        void *base, unsigned long base_size, enum object_type type)
2041{
2042        struct delta_base_cache_entry *ent = xmalloc(sizeof(*ent));
2043        struct list_head *lru, *tmp;
2044
2045        delta_base_cached += base_size;
2046
2047        list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
2048                struct delta_base_cache_entry *f =
2049                        list_entry(lru, struct delta_base_cache_entry, lru);
2050                if (delta_base_cached <= delta_base_cache_limit)
2051                        break;
2052                release_delta_base_cache(f);
2053        }
2054
2055        ent->key.p = p;
2056        ent->key.base_offset = base_offset;
2057        ent->type = type;
2058        ent->data = base;
2059        ent->size = base_size;
2060        list_add_tail(&ent->lru, &delta_base_cache_lru);
2061
2062        if (!delta_base_cache.cmpfn)
2063                hashmap_init(&delta_base_cache, delta_base_cache_hash_cmp, NULL, 0);
2064        hashmap_entry_init(ent, pack_entry_hash(p, base_offset));
2065        hashmap_add(&delta_base_cache, ent);
2066}
2067
2068int packed_object_info(struct packed_git *p, off_t obj_offset,
2069                       struct object_info *oi)
2070{
2071        struct pack_window *w_curs = NULL;
2072        unsigned long size;
2073        off_t curpos = obj_offset;
2074        enum object_type type;
2075
2076        /*
2077         * We always get the representation type, but only convert it to
2078         * a "real" type later if the caller is interested.
2079         */
2080        if (oi->contentp) {
2081                *oi->contentp = cache_or_unpack_entry(p, obj_offset, oi->sizep,
2082                                                      &type);
2083                if (!*oi->contentp)
2084                        type = OBJ_BAD;
2085        } else {
2086                type = unpack_object_header(p, &w_curs, &curpos, &size);
2087        }
2088
2089        if (!oi->contentp && oi->sizep) {
2090                if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
2091                        off_t tmp_pos = curpos;
2092                        off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
2093                                                           type, obj_offset);
2094                        if (!base_offset) {
2095                                type = OBJ_BAD;
2096                                goto out;
2097                        }
2098                        *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
2099                        if (*oi->sizep == 0) {
2100                                type = OBJ_BAD;
2101                                goto out;
2102                        }
2103                } else {
2104                        *oi->sizep = size;
2105                }
2106        }
2107
2108        if (oi->disk_sizep) {
2109                struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
2110                *oi->disk_sizep = revidx[1].offset - obj_offset;
2111        }
2112
2113        if (oi->typep || oi->typename) {
2114                enum object_type ptot;
2115                ptot = packed_to_object_type(p, obj_offset, type, &w_curs,
2116                                             curpos);
2117                if (oi->typep)
2118                        *oi->typep = ptot;
2119                if (oi->typename) {
2120                        const char *tn = typename(ptot);
2121                        if (tn)
2122                                strbuf_addstr(oi->typename, tn);
2123                }
2124                if (ptot < 0) {
2125                        type = OBJ_BAD;
2126                        goto out;
2127                }
2128        }
2129
2130        if (oi->delta_base_sha1) {
2131                if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
2132                        const unsigned char *base;
2133
2134                        base = get_delta_base_sha1(p, &w_curs, curpos,
2135                                                   type, obj_offset);
2136                        if (!base) {
2137                                type = OBJ_BAD;
2138                                goto out;
2139                        }
2140
2141                        hashcpy(oi->delta_base_sha1, base);
2142                } else
2143                        hashclr(oi->delta_base_sha1);
2144        }
2145
2146        oi->whence = in_delta_base_cache(p, obj_offset) ? OI_DBCACHED :
2147                                                          OI_PACKED;
2148
2149out:
2150        unuse_pack(&w_curs);
2151        return type;
2152}
2153
2154static void *unpack_compressed_entry(struct packed_git *p,
2155                                    struct pack_window **w_curs,
2156                                    off_t curpos,
2157                                    unsigned long size)
2158{
2159        int st;
2160        git_zstream stream;
2161        unsigned char *buffer, *in;
2162
2163        buffer = xmallocz_gently(size);
2164        if (!buffer)
2165                return NULL;
2166        memset(&stream, 0, sizeof(stream));
2167        stream.next_out = buffer;
2168        stream.avail_out = size + 1;
2169
2170        git_inflate_init(&stream);
2171        do {
2172                in = use_pack(p, w_curs, curpos, &stream.avail_in);
2173                stream.next_in = in;
2174                st = git_inflate(&stream, Z_FINISH);
2175                if (!stream.avail_out)
2176                        break; /* the payload is larger than it should be */
2177                curpos += stream.next_in - in;
2178        } while (st == Z_OK || st == Z_BUF_ERROR);
2179        git_inflate_end(&stream);
2180        if ((st != Z_STREAM_END) || stream.total_out != size) {
2181                free(buffer);
2182                return NULL;
2183        }
2184
2185        return buffer;
2186}
2187
2188static void *read_object(const unsigned char *sha1, enum object_type *type,
2189                         unsigned long *size);
2190
2191static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
2192{
2193        static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
2194        trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
2195                         p->pack_name, (uintmax_t)obj_offset);
2196}
2197
2198int do_check_packed_object_crc;
2199
2200#define UNPACK_ENTRY_STACK_PREALLOC 64
2201struct unpack_entry_stack_ent {
2202        off_t obj_offset;
2203        off_t curpos;
2204        unsigned long size;
2205};
2206
2207void *unpack_entry(struct packed_git *p, off_t obj_offset,
2208                   enum object_type *final_type, unsigned long *final_size)
2209{
2210        struct pack_window *w_curs = NULL;
2211        off_t curpos = obj_offset;
2212        void *data = NULL;
2213        unsigned long size;
2214        enum object_type type;
2215        struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
2216        struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
2217        int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
2218        int base_from_cache = 0;
2219
2220        write_pack_access_log(p, obj_offset);
2221
2222        /* PHASE 1: drill down to the innermost base object */
2223        for (;;) {
2224                off_t base_offset;
2225                int i;
2226                struct delta_base_cache_entry *ent;
2227
2228                ent = get_delta_base_cache_entry(p, curpos);
2229                if (ent) {
2230                        type = ent->type;
2231                        data = ent->data;
2232                        size = ent->size;
2233                        detach_delta_base_cache_entry(ent);
2234                        base_from_cache = 1;
2235                        break;
2236                }
2237
2238                if (do_check_packed_object_crc && p->index_version > 1) {
2239                        struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
2240                        off_t len = revidx[1].offset - obj_offset;
2241                        if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
2242                                const unsigned char *sha1 =
2243                                        nth_packed_object_sha1(p, revidx->nr);
2244                                error("bad packed object CRC for %s",
2245                                      sha1_to_hex(sha1));
2246                                mark_bad_packed_object(p, sha1);
2247                                data = NULL;
2248                                goto out;
2249                        }
2250                }
2251
2252                type = unpack_object_header(p, &w_curs, &curpos, &size);
2253                if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
2254                        break;
2255
2256                base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
2257                if (!base_offset) {
2258                        error("failed to validate delta base reference "
2259                              "at offset %"PRIuMAX" from %s",
2260                              (uintmax_t)curpos, p->pack_name);
2261                        /* bail to phase 2, in hopes of recovery */
2262                        data = NULL;
2263                        break;
2264                }
2265
2266                /* push object, proceed to base */
2267                if (delta_stack_nr >= delta_stack_alloc
2268                    && delta_stack == small_delta_stack) {
2269                        delta_stack_alloc = alloc_nr(delta_stack_nr);
2270                        ALLOC_ARRAY(delta_stack, delta_stack_alloc);
2271                        memcpy(delta_stack, small_delta_stack,
2272                               sizeof(*delta_stack)*delta_stack_nr);
2273                } else {
2274                        ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
2275                }
2276                i = delta_stack_nr++;
2277                delta_stack[i].obj_offset = obj_offset;
2278                delta_stack[i].curpos = curpos;
2279                delta_stack[i].size = size;
2280
2281                curpos = obj_offset = base_offset;
2282        }
2283
2284        /* PHASE 2: handle the base */
2285        switch (type) {
2286        case OBJ_OFS_DELTA:
2287        case OBJ_REF_DELTA:
2288                if (data)
2289                        die("BUG: unpack_entry: left loop at a valid delta");
2290                break;
2291        case OBJ_COMMIT:
2292        case OBJ_TREE:
2293        case OBJ_BLOB:
2294        case OBJ_TAG:
2295                if (!base_from_cache)
2296                        data = unpack_compressed_entry(p, &w_curs, curpos, size);
2297                break;
2298        default:
2299                data = NULL;
2300                error("unknown object type %i at offset %"PRIuMAX" in %s",
2301                      type, (uintmax_t)obj_offset, p->pack_name);
2302        }
2303
2304        /* PHASE 3: apply deltas in order */
2305
2306        /* invariants:
2307         *   'data' holds the base data, or NULL if there was corruption
2308         */
2309        while (delta_stack_nr) {
2310                void *delta_data;
2311                void *base = data;
2312                void *external_base = NULL;
2313                unsigned long delta_size, base_size = size;
2314                int i;
2315
2316                data = NULL;
2317
2318                if (base)
2319                        add_delta_base_cache(p, obj_offset, base, base_size, type);
2320
2321                if (!base) {
2322                        /*
2323                         * We're probably in deep shit, but let's try to fetch
2324                         * the required base anyway from another pack or loose.
2325                         * This is costly but should happen only in the presence
2326                         * of a corrupted pack, and is better than failing outright.
2327                         */
2328                        struct revindex_entry *revidx;
2329                        const unsigned char *base_sha1;
2330                        revidx = find_pack_revindex(p, obj_offset);
2331                        if (revidx) {
2332                                base_sha1 = nth_packed_object_sha1(p, revidx->nr);
2333                                error("failed to read delta base object %s"
2334                                      " at offset %"PRIuMAX" from %s",
2335                                      sha1_to_hex(base_sha1), (uintmax_t)obj_offset,
2336                                      p->pack_name);
2337                                mark_bad_packed_object(p, base_sha1);
2338                                base = read_object(base_sha1, &type, &base_size);
2339                                external_base = base;
2340                        }
2341                }
2342
2343                i = --delta_stack_nr;
2344                obj_offset = delta_stack[i].obj_offset;
2345                curpos = delta_stack[i].curpos;
2346                delta_size = delta_stack[i].size;
2347
2348                if (!base)
2349                        continue;
2350
2351                delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
2352
2353                if (!delta_data) {
2354                        error("failed to unpack compressed delta "
2355                              "at offset %"PRIuMAX" from %s",
2356                              (uintmax_t)curpos, p->pack_name);
2357                        data = NULL;
2358                        free(external_base);
2359                        continue;
2360                }
2361
2362                data = patch_delta(base, base_size,
2363                                   delta_data, delta_size,
2364                                   &size);
2365
2366                /*
2367                 * We could not apply the delta; warn the user, but keep going.
2368                 * Our failure will be noticed either in the next iteration of
2369                 * the loop, or if this is the final delta, in the caller when
2370                 * we return NULL. Those code paths will take care of making
2371                 * a more explicit warning and retrying with another copy of
2372                 * the object.
2373                 */
2374                if (!data)
2375                        error("failed to apply delta");
2376
2377                free(delta_data);
2378                free(external_base);
2379        }
2380
2381        if (final_type)
2382                *final_type = type;
2383        if (final_size)
2384                *final_size = size;
2385
2386out:
2387        unuse_pack(&w_curs);
2388
2389        if (delta_stack != small_delta_stack)
2390                free(delta_stack);
2391
2392        return data;
2393}
2394
2395const unsigned char *nth_packed_object_sha1(struct packed_git *p,
2396                                            uint32_t n)
2397{
2398        const unsigned char *index = p->index_data;
2399        if (!index) {
2400                if (open_pack_index(p))
2401                        return NULL;
2402                index = p->index_data;
2403        }
2404        if (n >= p->num_objects)
2405                return NULL;
2406        index += 4 * 256;
2407        if (p->index_version == 1) {
2408                return index + 24 * n + 4;
2409        } else {
2410                index += 8;
2411                return index + 20 * n;
2412        }
2413}
2414
2415const struct object_id *nth_packed_object_oid(struct object_id *oid,
2416                                              struct packed_git *p,
2417                                              uint32_t n)
2418{
2419        const unsigned char *hash = nth_packed_object_sha1(p, n);
2420        if (!hash)
2421                return NULL;
2422        hashcpy(oid->hash, hash);
2423        return oid;
2424}
2425
2426void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
2427{
2428        const unsigned char *ptr = vptr;
2429        const unsigned char *start = p->index_data;
2430        const unsigned char *end = start + p->index_size;
2431        if (ptr < start)
2432                die(_("offset before start of pack index for %s (corrupt index?)"),
2433                    p->pack_name);
2434        /* No need to check for underflow; .idx files must be at least 8 bytes */
2435        if (ptr >= end - 8)
2436                die(_("offset beyond end of pack index for %s (truncated index?)"),
2437                    p->pack_name);
2438}
2439
2440off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
2441{
2442        const unsigned char *index = p->index_data;
2443        index += 4 * 256;
2444        if (p->index_version == 1) {
2445                return ntohl(*((uint32_t *)(index + 24 * n)));
2446        } else {
2447                uint32_t off;
2448                index += 8 + p->num_objects * (20 + 4);
2449                off = ntohl(*((uint32_t *)(index + 4 * n)));
2450                if (!(off & 0x80000000))
2451                        return off;
2452                index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
2453                check_pack_index_ptr(p, index);
2454                return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
2455                                   ntohl(*((uint32_t *)(index + 4)));
2456        }
2457}
2458
2459off_t find_pack_entry_one(const unsigned char *sha1,
2460                                  struct packed_git *p)
2461{
2462        const uint32_t *level1_ofs = p->index_data;
2463        const unsigned char *index = p->index_data;
2464        unsigned hi, lo, stride;
2465        static int debug_lookup = -1;
2466
2467        if (debug_lookup < 0)
2468                debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
2469
2470        if (!index) {
2471                if (open_pack_index(p))
2472                        return 0;
2473                level1_ofs = p->index_data;
2474                index = p->index_data;
2475        }
2476        if (p->index_version > 1) {
2477                level1_ofs += 2;
2478                index += 8;
2479        }
2480        index += 4 * 256;
2481        hi = ntohl(level1_ofs[*sha1]);
2482        lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
2483        if (p->index_version > 1) {
2484                stride = 20;
2485        } else {
2486                stride = 24;
2487                index += 4;
2488        }
2489
2490        if (debug_lookup)
2491                printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
2492                       sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
2493
2494        while (lo < hi) {
2495                unsigned mi = (lo + hi) / 2;
2496                int cmp = hashcmp(index + mi * stride, sha1);
2497
2498                if (debug_lookup)
2499                        printf("lo %u hi %u rg %u mi %u\n",
2500                               lo, hi, hi - lo, mi);
2501                if (!cmp)
2502                        return nth_packed_object_offset(p, mi);
2503                if (cmp > 0)
2504                        hi = mi;
2505                else
2506                        lo = mi+1;
2507        }
2508        return 0;
2509}
2510
2511int is_pack_valid(struct packed_git *p)
2512{
2513        /* An already open pack is known to be valid. */
2514        if (p->pack_fd != -1)
2515                return 1;
2516
2517        /* If the pack has one window completely covering the
2518         * file size, the pack is known to be valid even if
2519         * the descriptor is not currently open.
2520         */
2521        if (p->windows) {
2522                struct pack_window *w = p->windows;
2523
2524                if (!w->offset && w->len == p->pack_size)
2525                        return 1;
2526        }
2527
2528        /* Force the pack to open to prove its valid. */
2529        return !open_packed_git(p);
2530}
2531
2532static int fill_pack_entry(const unsigned char *sha1,
2533                           struct pack_entry *e,
2534                           struct packed_git *p)
2535{
2536        off_t offset;
2537
2538        if (p->num_bad_objects) {
2539                unsigned i;
2540                for (i = 0; i < p->num_bad_objects; i++)
2541                        if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
2542                                return 0;
2543        }
2544
2545        offset = find_pack_entry_one(sha1, p);
2546        if (!offset)
2547                return 0;
2548
2549        /*
2550         * We are about to tell the caller where they can locate the
2551         * requested object.  We better make sure the packfile is
2552         * still here and can be accessed before supplying that
2553         * answer, as it may have been deleted since the index was
2554         * loaded!
2555         */
2556        if (!is_pack_valid(p))
2557                return 0;
2558        e->offset = offset;
2559        e->p = p;
2560        hashcpy(e->sha1, sha1);
2561        return 1;
2562}
2563
2564/*
2565 * Iff a pack file contains the object named by sha1, return true and
2566 * store its location to e.
2567 */
2568static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
2569{
2570        struct mru_entry *p;
2571
2572        prepare_packed_git();
2573        if (!packed_git)
2574                return 0;
2575
2576        for (p = packed_git_mru->head; p; p = p->next) {
2577                if (fill_pack_entry(sha1, e, p->item)) {
2578                        mru_mark(packed_git_mru, p);
2579                        return 1;
2580                }
2581        }
2582        return 0;
2583}
2584
2585struct packed_git *find_sha1_pack(const unsigned char *sha1,
2586                                  struct packed_git *packs)
2587{
2588        struct packed_git *p;
2589
2590        for (p = packs; p; p = p->next) {
2591                if (find_pack_entry_one(sha1, p))
2592                        return p;
2593        }
2594        return NULL;
2595
2596}
2597
2598static int sha1_loose_object_info(const unsigned char *sha1,
2599                                  struct object_info *oi,
2600                                  int flags)
2601{
2602        int status = 0;
2603        unsigned long mapsize;
2604        void *map;
2605        git_zstream stream;
2606        char hdr[32];
2607        struct strbuf hdrbuf = STRBUF_INIT;
2608        unsigned long size_scratch;
2609
2610        if (oi->delta_base_sha1)
2611                hashclr(oi->delta_base_sha1);
2612
2613        /*
2614         * If we don't care about type or size, then we don't
2615         * need to look inside the object at all. Note that we
2616         * do not optimize out the stat call, even if the
2617         * caller doesn't care about the disk-size, since our
2618         * return value implicitly indicates whether the
2619         * object even exists.
2620         */
2621        if (!oi->typep && !oi->typename && !oi->sizep && !oi->contentp) {
2622                const char *path;
2623                struct stat st;
2624                if (stat_sha1_file(sha1, &st, &path) < 0)
2625                        return -1;
2626                if (oi->disk_sizep)
2627                        *oi->disk_sizep = st.st_size;
2628                return 0;
2629        }
2630
2631        map = map_sha1_file(sha1, &mapsize);
2632        if (!map)
2633                return -1;
2634
2635        if (!oi->sizep)
2636                oi->sizep = &size_scratch;
2637
2638        if (oi->disk_sizep)
2639                *oi->disk_sizep = mapsize;
2640        if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE)) {
2641                if (unpack_sha1_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
2642                        status = error("unable to unpack %s header with --allow-unknown-type",
2643                                       sha1_to_hex(sha1));
2644        } else if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
2645                status = error("unable to unpack %s header",
2646                               sha1_to_hex(sha1));
2647        if (status < 0)
2648                ; /* Do nothing */
2649        else if (hdrbuf.len) {
2650                if ((status = parse_sha1_header_extended(hdrbuf.buf, oi, flags)) < 0)
2651                        status = error("unable to parse %s header with --allow-unknown-type",
2652                                       sha1_to_hex(sha1));
2653        } else if ((status = parse_sha1_header_extended(hdr, oi, flags)) < 0)
2654                status = error("unable to parse %s header", sha1_to_hex(sha1));
2655
2656        if (status >= 0 && oi->contentp)
2657                *oi->contentp = unpack_sha1_rest(&stream, hdr,
2658                                                 *oi->sizep, sha1);
2659        else
2660                git_inflate_end(&stream);
2661
2662        munmap(map, mapsize);
2663        if (status && oi->typep)
2664                *oi->typep = status;
2665        if (oi->sizep == &size_scratch)
2666                oi->sizep = NULL;
2667        strbuf_release(&hdrbuf);
2668        oi->whence = OI_LOOSE;
2669        return (status < 0) ? status : 0;
2670}
2671
2672int sha1_object_info_extended(const unsigned char *sha1, struct object_info *oi, unsigned flags)
2673{
2674        static struct object_info blank_oi = OBJECT_INFO_INIT;
2675        struct pack_entry e;
2676        int rtype;
2677        const unsigned char *real = (flags & OBJECT_INFO_LOOKUP_REPLACE) ?
2678                                    lookup_replace_object(sha1) :
2679                                    sha1;
2680
2681        if (!oi)
2682                oi = &blank_oi;
2683
2684        if (!(flags & OBJECT_INFO_SKIP_CACHED)) {
2685                struct cached_object *co = find_cached_object(real);
2686                if (co) {
2687                        if (oi->typep)
2688                                *(oi->typep) = co->type;
2689                        if (oi->sizep)
2690                                *(oi->sizep) = co->size;
2691                        if (oi->disk_sizep)
2692                                *(oi->disk_sizep) = 0;
2693                        if (oi->delta_base_sha1)
2694                                hashclr(oi->delta_base_sha1);
2695                        if (oi->typename)
2696                                strbuf_addstr(oi->typename, typename(co->type));
2697                        if (oi->contentp)
2698                                *oi->contentp = xmemdupz(co->buf, co->size);
2699                        oi->whence = OI_CACHED;
2700                        return 0;
2701                }
2702        }
2703
2704        if (!find_pack_entry(real, &e)) {
2705                /* Most likely it's a loose object. */
2706                if (!sha1_loose_object_info(real, oi, flags))
2707                        return 0;
2708
2709                /* Not a loose object; someone else may have just packed it. */
2710                if (flags & OBJECT_INFO_QUICK) {
2711                        return -1;
2712                } else {
2713                        reprepare_packed_git();
2714                        if (!find_pack_entry(real, &e))
2715                                return -1;
2716                }
2717        }
2718
2719        if (oi == &blank_oi)
2720                /*
2721                 * We know that the caller doesn't actually need the
2722                 * information below, so return early.
2723                 */
2724                return 0;
2725
2726        rtype = packed_object_info(e.p, e.offset, oi);
2727        if (rtype < 0) {
2728                mark_bad_packed_object(e.p, real);
2729                return sha1_object_info_extended(real, oi, 0);
2730        } else if (oi->whence == OI_PACKED) {
2731                oi->u.packed.offset = e.offset;
2732                oi->u.packed.pack = e.p;
2733                oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
2734                                         rtype == OBJ_OFS_DELTA);
2735        }
2736
2737        return 0;
2738}
2739
2740/* returns enum object_type or negative */
2741int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
2742{
2743        enum object_type type;
2744        struct object_info oi = OBJECT_INFO_INIT;
2745
2746        oi.typep = &type;
2747        oi.sizep = sizep;
2748        if (sha1_object_info_extended(sha1, &oi,
2749                                      OBJECT_INFO_LOOKUP_REPLACE) < 0)
2750                return -1;
2751        return type;
2752}
2753
2754int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2755                      unsigned char *sha1)
2756{
2757        struct cached_object *co;
2758
2759        hash_sha1_file(buf, len, typename(type), sha1);
2760        if (has_sha1_file(sha1) || find_cached_object(sha1))
2761                return 0;
2762        ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
2763        co = &cached_objects[cached_object_nr++];
2764        co->size = len;
2765        co->type = type;
2766        co->buf = xmalloc(len);
2767        memcpy(co->buf, buf, len);
2768        hashcpy(co->sha1, sha1);
2769        return 0;
2770}
2771
2772static void *read_object(const unsigned char *sha1, enum object_type *type,
2773                         unsigned long *size)
2774{
2775        struct object_info oi = OBJECT_INFO_INIT;
2776        void *content;
2777        oi.typep = type;
2778        oi.sizep = size;
2779        oi.contentp = &content;
2780
2781        if (sha1_object_info_extended(sha1, &oi, 0) < 0)
2782                return NULL;
2783        return content;
2784}
2785
2786/*
2787 * This function dies on corrupt objects; the callers who want to
2788 * deal with them should arrange to call read_object() and give error
2789 * messages themselves.
2790 */
2791void *read_sha1_file_extended(const unsigned char *sha1,
2792                              enum object_type *type,
2793                              unsigned long *size,
2794                              int lookup_replace)
2795{
2796        void *data;
2797        const struct packed_git *p;
2798        const char *path;
2799        struct stat st;
2800        const unsigned char *repl = lookup_replace ? lookup_replace_object(sha1)
2801                                                   : sha1;
2802
2803        errno = 0;
2804        data = read_object(repl, type, size);
2805        if (data)
2806                return data;
2807
2808        if (errno && errno != ENOENT)
2809                die_errno("failed to read object %s", sha1_to_hex(sha1));
2810
2811        /* die if we replaced an object with one that does not exist */
2812        if (repl != sha1)
2813                die("replacement %s not found for %s",
2814                    sha1_to_hex(repl), sha1_to_hex(sha1));
2815
2816        if (!stat_sha1_file(repl, &st, &path))
2817                die("loose object %s (stored in %s) is corrupt",
2818                    sha1_to_hex(repl), path);
2819
2820        if ((p = has_packed_and_bad(repl)) != NULL)
2821                die("packed object %s (stored in %s) is corrupt",
2822                    sha1_to_hex(repl), p->pack_name);
2823
2824        return NULL;
2825}
2826
2827void *read_object_with_reference(const unsigned char *sha1,
2828                                 const char *required_type_name,
2829                                 unsigned long *size,
2830                                 unsigned char *actual_sha1_return)
2831{
2832        enum object_type type, required_type;
2833        void *buffer;
2834        unsigned long isize;
2835        unsigned char actual_sha1[20];
2836
2837        required_type = type_from_string(required_type_name);
2838        hashcpy(actual_sha1, sha1);
2839        while (1) {
2840                int ref_length = -1;
2841                const char *ref_type = NULL;
2842
2843                buffer = read_sha1_file(actual_sha1, &type, &isize);
2844                if (!buffer)
2845                        return NULL;
2846                if (type == required_type) {
2847                        *size = isize;
2848                        if (actual_sha1_return)
2849                                hashcpy(actual_sha1_return, actual_sha1);
2850                        return buffer;
2851                }
2852                /* Handle references */
2853                else if (type == OBJ_COMMIT)
2854                        ref_type = "tree ";
2855                else if (type == OBJ_TAG)
2856                        ref_type = "object ";
2857                else {
2858                        free(buffer);
2859                        return NULL;
2860                }
2861                ref_length = strlen(ref_type);
2862
2863                if (ref_length + 40 > isize ||
2864                    memcmp(buffer, ref_type, ref_length) ||
2865                    get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2866                        free(buffer);
2867                        return NULL;
2868                }
2869                free(buffer);
2870                /* Now we have the ID of the referred-to object in
2871                 * actual_sha1.  Check again. */
2872        }
2873}
2874
2875static void write_sha1_file_prepare(const void *buf, unsigned long len,
2876                                    const char *type, unsigned char *sha1,
2877                                    char *hdr, int *hdrlen)
2878{
2879        git_SHA_CTX c;
2880
2881        /* Generate the header */
2882        *hdrlen = xsnprintf(hdr, *hdrlen, "%s %lu", type, len)+1;
2883
2884        /* Sha1.. */
2885        git_SHA1_Init(&c);
2886        git_SHA1_Update(&c, hdr, *hdrlen);
2887        git_SHA1_Update(&c, buf, len);
2888        git_SHA1_Final(sha1, &c);
2889}
2890
2891/*
2892 * Move the just written object into its final resting place.
2893 */
2894int finalize_object_file(const char *tmpfile, const char *filename)
2895{
2896        int ret = 0;
2897
2898        if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
2899                goto try_rename;
2900        else if (link(tmpfile, filename))
2901                ret = errno;
2902
2903        /*
2904         * Coda hack - coda doesn't like cross-directory links,
2905         * so we fall back to a rename, which will mean that it
2906         * won't be able to check collisions, but that's not a
2907         * big deal.
2908         *
2909         * The same holds for FAT formatted media.
2910         *
2911         * When this succeeds, we just return.  We have nothing
2912         * left to unlink.
2913         */
2914        if (ret && ret != EEXIST) {
2915        try_rename:
2916                if (!rename(tmpfile, filename))
2917                        goto out;
2918                ret = errno;
2919        }
2920        unlink_or_warn(tmpfile);
2921        if (ret) {
2922                if (ret != EEXIST) {
2923                        return error_errno("unable to write sha1 filename %s", filename);
2924                }
2925                /* FIXME!!! Collision check here ? */
2926        }
2927
2928out:
2929        if (adjust_shared_perm(filename))
2930                return error("unable to set permission to '%s'", filename);
2931        return 0;
2932}
2933
2934static int write_buffer(int fd, const void *buf, size_t len)
2935{
2936        if (write_in_full(fd, buf, len) < 0)
2937                return error_errno("file write error");
2938        return 0;
2939}
2940
2941int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2942                   unsigned char *sha1)
2943{
2944        char hdr[32];
2945        int hdrlen = sizeof(hdr);
2946        write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2947        return 0;
2948}
2949
2950/* Finalize a file on disk, and close it. */
2951static void close_sha1_file(int fd)
2952{
2953        if (fsync_object_files)
2954                fsync_or_die(fd, "sha1 file");
2955        if (close(fd) != 0)
2956                die_errno("error when closing sha1 file");
2957}
2958
2959/* Size of directory component, including the ending '/' */
2960static inline int directory_size(const char *filename)
2961{
2962        const char *s = strrchr(filename, '/');
2963        if (!s)
2964                return 0;
2965        return s - filename + 1;
2966}
2967
2968/*
2969 * This creates a temporary file in the same directory as the final
2970 * 'filename'
2971 *
2972 * We want to avoid cross-directory filename renames, because those
2973 * can have problems on various filesystems (FAT, NFS, Coda).
2974 */
2975static int create_tmpfile(struct strbuf *tmp, const char *filename)
2976{
2977        int fd, dirlen = directory_size(filename);
2978
2979        strbuf_reset(tmp);
2980        strbuf_add(tmp, filename, dirlen);
2981        strbuf_addstr(tmp, "tmp_obj_XXXXXX");
2982        fd = git_mkstemp_mode(tmp->buf, 0444);
2983        if (fd < 0 && dirlen && errno == ENOENT) {
2984                /*
2985                 * Make sure the directory exists; note that the contents
2986                 * of the buffer are undefined after mkstemp returns an
2987                 * error, so we have to rewrite the whole buffer from
2988                 * scratch.
2989                 */
2990                strbuf_reset(tmp);
2991                strbuf_add(tmp, filename, dirlen - 1);
2992                if (mkdir(tmp->buf, 0777) && errno != EEXIST)
2993                        return -1;
2994                if (adjust_shared_perm(tmp->buf))
2995                        return -1;
2996
2997                /* Try again */
2998                strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
2999                fd = git_mkstemp_mode(tmp->buf, 0444);
3000        }
3001        return fd;
3002}
3003
3004static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
3005                              const void *buf, unsigned long len, time_t mtime)
3006{
3007        int fd, ret;
3008        unsigned char compressed[4096];
3009        git_zstream stream;
3010        git_SHA_CTX c;
3011        unsigned char parano_sha1[20];
3012        static struct strbuf tmp_file = STRBUF_INIT;
3013        const char *filename = sha1_file_name(sha1);
3014
3015        fd = create_tmpfile(&tmp_file, filename);
3016        if (fd < 0) {
3017                if (errno == EACCES)
3018                        return error("insufficient permission for adding an object to repository database %s", get_object_directory());
3019                else
3020                        return error_errno("unable to create temporary file");
3021        }
3022
3023        /* Set it up */
3024        git_deflate_init(&stream, zlib_compression_level);
3025        stream.next_out = compressed;
3026        stream.avail_out = sizeof(compressed);
3027        git_SHA1_Init(&c);
3028
3029        /* First header.. */
3030        stream.next_in = (unsigned char *)hdr;
3031        stream.avail_in = hdrlen;
3032        while (git_deflate(&stream, 0) == Z_OK)
3033                ; /* nothing */
3034        git_SHA1_Update(&c, hdr, hdrlen);
3035
3036        /* Then the data itself.. */
3037        stream.next_in = (void *)buf;
3038        stream.avail_in = len;
3039        do {
3040                unsigned char *in0 = stream.next_in;
3041                ret = git_deflate(&stream, Z_FINISH);
3042                git_SHA1_Update(&c, in0, stream.next_in - in0);
3043                if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
3044                        die("unable to write sha1 file");
3045                stream.next_out = compressed;
3046                stream.avail_out = sizeof(compressed);
3047        } while (ret == Z_OK);
3048
3049        if (ret != Z_STREAM_END)
3050                die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
3051        ret = git_deflate_end_gently(&stream);
3052        if (ret != Z_OK)
3053                die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
3054        git_SHA1_Final(parano_sha1, &c);
3055        if (hashcmp(sha1, parano_sha1) != 0)
3056                die("confused by unstable object source data for %s", sha1_to_hex(sha1));
3057
3058        close_sha1_file(fd);
3059
3060        if (mtime) {
3061                struct utimbuf utb;
3062                utb.actime = mtime;
3063                utb.modtime = mtime;
3064                if (utime(tmp_file.buf, &utb) < 0)
3065                        warning_errno("failed utime() on %s", tmp_file.buf);
3066        }
3067
3068        return finalize_object_file(tmp_file.buf, filename);
3069}
3070
3071static int freshen_loose_object(const unsigned char *sha1)
3072{
3073        return check_and_freshen(sha1, 1);
3074}
3075
3076static int freshen_packed_object(const unsigned char *sha1)
3077{
3078        struct pack_entry e;
3079        if (!find_pack_entry(sha1, &e))
3080                return 0;
3081        if (e.p->freshened)
3082                return 1;
3083        if (!freshen_file(e.p->pack_name))
3084                return 0;
3085        e.p->freshened = 1;
3086        return 1;
3087}
3088
3089int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *sha1)
3090{
3091        char hdr[32];
3092        int hdrlen = sizeof(hdr);
3093
3094        /* Normally if we have it in the pack then we do not bother writing
3095         * it out into .git/objects/??/?{38} file.
3096         */
3097        write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
3098        if (freshen_packed_object(sha1) || freshen_loose_object(sha1))
3099                return 0;
3100        return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
3101}
3102
3103int hash_sha1_file_literally(const void *buf, unsigned long len, const char *type,
3104                             unsigned char *sha1, unsigned flags)
3105{
3106        char *header;
3107        int hdrlen, status = 0;
3108
3109        /* type string, SP, %lu of the length plus NUL must fit this */
3110        hdrlen = strlen(type) + 32;
3111        header = xmalloc(hdrlen);
3112        write_sha1_file_prepare(buf, len, type, sha1, header, &hdrlen);
3113
3114        if (!(flags & HASH_WRITE_OBJECT))
3115                goto cleanup;
3116        if (freshen_packed_object(sha1) || freshen_loose_object(sha1))
3117                goto cleanup;
3118        status = write_loose_object(sha1, header, hdrlen, buf, len, 0);
3119
3120cleanup:
3121        free(header);
3122        return status;
3123}
3124
3125int force_object_loose(const unsigned char *sha1, time_t mtime)
3126{
3127        void *buf;
3128        unsigned long len;
3129        enum object_type type;
3130        char hdr[32];
3131        int hdrlen;
3132        int ret;
3133
3134        if (has_loose_object(sha1))
3135                return 0;
3136        buf = read_object(sha1, &type, &len);
3137        if (!buf)
3138                return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
3139        hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(type), len) + 1;
3140        ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
3141        free(buf);
3142
3143        return ret;
3144}
3145
3146int has_pack_index(const unsigned char *sha1)
3147{
3148        struct stat st;
3149        if (stat(sha1_pack_index_name(sha1), &st))
3150                return 0;
3151        return 1;
3152}
3153
3154int has_sha1_pack(const unsigned char *sha1)
3155{
3156        struct pack_entry e;
3157        return find_pack_entry(sha1, &e);
3158}
3159
3160int has_sha1_file_with_flags(const unsigned char *sha1, int flags)
3161{
3162        if (!startup_info->have_repository)
3163                return 0;
3164        return sha1_object_info_extended(sha1, NULL,
3165                                         flags | OBJECT_INFO_SKIP_CACHED) >= 0;
3166}
3167
3168int has_object_file(const struct object_id *oid)
3169{
3170        return has_sha1_file(oid->hash);
3171}
3172
3173int has_object_file_with_flags(const struct object_id *oid, int flags)
3174{
3175        return has_sha1_file_with_flags(oid->hash, flags);
3176}
3177
3178static void check_tree(const void *buf, size_t size)
3179{
3180        struct tree_desc desc;
3181        struct name_entry entry;
3182
3183        init_tree_desc(&desc, buf, size);
3184        while (tree_entry(&desc, &entry))
3185                /* do nothing
3186                 * tree_entry() will die() on malformed entries */
3187                ;
3188}
3189
3190static void check_commit(const void *buf, size_t size)
3191{
3192        struct commit c;
3193        memset(&c, 0, sizeof(c));
3194        if (parse_commit_buffer(&c, buf, size))
3195                die("corrupt commit");
3196}
3197
3198static void check_tag(const void *buf, size_t size)
3199{
3200        struct tag t;
3201        memset(&t, 0, sizeof(t));
3202        if (parse_tag_buffer(&t, buf, size))
3203                die("corrupt tag");
3204}
3205
3206static int index_mem(unsigned char *sha1, void *buf, size_t size,
3207                     enum object_type type,
3208                     const char *path, unsigned flags)
3209{
3210        int ret, re_allocated = 0;
3211        int write_object = flags & HASH_WRITE_OBJECT;
3212
3213        if (!type)
3214                type = OBJ_BLOB;
3215
3216        /*
3217         * Convert blobs to git internal format
3218         */
3219        if ((type == OBJ_BLOB) && path) {
3220                struct strbuf nbuf = STRBUF_INIT;
3221                if (convert_to_git(&the_index, path, buf, size, &nbuf,
3222                                   write_object ? safe_crlf : SAFE_CRLF_FALSE)) {
3223                        buf = strbuf_detach(&nbuf, &size);
3224                        re_allocated = 1;
3225                }
3226        }
3227        if (flags & HASH_FORMAT_CHECK) {
3228                if (type == OBJ_TREE)
3229                        check_tree(buf, size);
3230                if (type == OBJ_COMMIT)
3231                        check_commit(buf, size);
3232                if (type == OBJ_TAG)
3233                        check_tag(buf, size);
3234        }
3235
3236        if (write_object)
3237                ret = write_sha1_file(buf, size, typename(type), sha1);
3238        else
3239                ret = hash_sha1_file(buf, size, typename(type), sha1);
3240        if (re_allocated)
3241                free(buf);
3242        return ret;
3243}
3244
3245static int index_stream_convert_blob(unsigned char *sha1, int fd,
3246                                     const char *path, unsigned flags)
3247{
3248        int ret;
3249        const int write_object = flags & HASH_WRITE_OBJECT;
3250        struct strbuf sbuf = STRBUF_INIT;
3251
3252        assert(path);
3253        assert(would_convert_to_git_filter_fd(path));
3254
3255        convert_to_git_filter_fd(&the_index, path, fd, &sbuf,
3256                                 write_object ? safe_crlf : SAFE_CRLF_FALSE);
3257
3258        if (write_object)
3259                ret = write_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
3260                                      sha1);
3261        else
3262                ret = hash_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
3263                                     sha1);
3264        strbuf_release(&sbuf);
3265        return ret;
3266}
3267
3268static int index_pipe(unsigned char *sha1, int fd, enum object_type type,
3269                      const char *path, unsigned flags)
3270{
3271        struct strbuf sbuf = STRBUF_INIT;
3272        int ret;
3273
3274        if (strbuf_read(&sbuf, fd, 4096) >= 0)
3275                ret = index_mem(sha1, sbuf.buf, sbuf.len, type, path, flags);
3276        else
3277                ret = -1;
3278        strbuf_release(&sbuf);
3279        return ret;
3280}
3281
3282#define SMALL_FILE_SIZE (32*1024)
3283
3284static int index_core(unsigned char *sha1, int fd, size_t size,
3285                      enum object_type type, const char *path,
3286                      unsigned flags)
3287{
3288        int ret;
3289
3290        if (!size) {
3291                ret = index_mem(sha1, "", size, type, path, flags);
3292        } else if (size <= SMALL_FILE_SIZE) {
3293                char *buf = xmalloc(size);
3294                if (size == read_in_full(fd, buf, size))
3295                        ret = index_mem(sha1, buf, size, type, path, flags);
3296                else
3297                        ret = error_errno("short read");
3298                free(buf);
3299        } else {
3300                void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
3301                ret = index_mem(sha1, buf, size, type, path, flags);
3302                munmap(buf, size);
3303        }
3304        return ret;
3305}
3306
3307/*
3308 * This creates one packfile per large blob unless bulk-checkin
3309 * machinery is "plugged".
3310 *
3311 * This also bypasses the usual "convert-to-git" dance, and that is on
3312 * purpose. We could write a streaming version of the converting
3313 * functions and insert that before feeding the data to fast-import
3314 * (or equivalent in-core API described above). However, that is
3315 * somewhat complicated, as we do not know the size of the filter
3316 * result, which we need to know beforehand when writing a git object.
3317 * Since the primary motivation for trying to stream from the working
3318 * tree file and to avoid mmaping it in core is to deal with large
3319 * binary blobs, they generally do not want to get any conversion, and
3320 * callers should avoid this code path when filters are requested.
3321 */
3322static int index_stream(unsigned char *sha1, int fd, size_t size,
3323                        enum object_type type, const char *path,
3324                        unsigned flags)
3325{
3326        return index_bulk_checkin(sha1, fd, size, type, path, flags);
3327}
3328
3329int index_fd(unsigned char *sha1, int fd, struct stat *st,
3330             enum object_type type, const char *path, unsigned flags)
3331{
3332        int ret;
3333
3334        /*
3335         * Call xsize_t() only when needed to avoid potentially unnecessary
3336         * die() for large files.
3337         */
3338        if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(path))
3339                ret = index_stream_convert_blob(sha1, fd, path, flags);
3340        else if (!S_ISREG(st->st_mode))
3341                ret = index_pipe(sha1, fd, type, path, flags);
3342        else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
3343                 (path && would_convert_to_git(&the_index, path)))
3344                ret = index_core(sha1, fd, xsize_t(st->st_size), type, path,
3345                                 flags);
3346        else
3347                ret = index_stream(sha1, fd, xsize_t(st->st_size), type, path,
3348                                   flags);
3349        close(fd);
3350        return ret;
3351}
3352
3353int index_path(unsigned char *sha1, const char *path, struct stat *st, unsigned flags)
3354{
3355        int fd;
3356        struct strbuf sb = STRBUF_INIT;
3357
3358        switch (st->st_mode & S_IFMT) {
3359        case S_IFREG:
3360                fd = open(path, O_RDONLY);
3361                if (fd < 0)
3362                        return error_errno("open(\"%s\")", path);
3363                if (index_fd(sha1, fd, st, OBJ_BLOB, path, flags) < 0)
3364                        return error("%s: failed to insert into database",
3365                                     path);
3366                break;
3367        case S_IFLNK:
3368                if (strbuf_readlink(&sb, path, st->st_size))
3369                        return error_errno("readlink(\"%s\")", path);
3370                if (!(flags & HASH_WRITE_OBJECT))
3371                        hash_sha1_file(sb.buf, sb.len, blob_type, sha1);
3372                else if (write_sha1_file(sb.buf, sb.len, blob_type, sha1))
3373                        return error("%s: failed to insert into database",
3374                                     path);
3375                strbuf_release(&sb);
3376                break;
3377        case S_IFDIR:
3378                return resolve_gitlink_ref(path, "HEAD", sha1);
3379        default:
3380                return error("%s: unsupported file type", path);
3381        }
3382        return 0;
3383}
3384
3385int read_pack_header(int fd, struct pack_header *header)
3386{
3387        if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
3388                /* "eof before pack header was fully read" */
3389                return PH_ERROR_EOF;
3390
3391        if (header->hdr_signature != htonl(PACK_SIGNATURE))
3392                /* "protocol error (pack signature mismatch detected)" */
3393                return PH_ERROR_PACK_SIGNATURE;
3394        if (!pack_version_ok(header->hdr_version))
3395                /* "protocol error (pack version unsupported)" */
3396                return PH_ERROR_PROTOCOL;
3397        return 0;
3398}
3399
3400void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
3401{
3402        enum object_type type = sha1_object_info(sha1, NULL);
3403        if (type < 0)
3404                die("%s is not a valid object", sha1_to_hex(sha1));
3405        if (type != expect)
3406                die("%s is not a valid '%s' object", sha1_to_hex(sha1),
3407                    typename(expect));
3408}
3409
3410int for_each_file_in_obj_subdir(unsigned int subdir_nr,
3411                                struct strbuf *path,
3412                                each_loose_object_fn obj_cb,
3413                                each_loose_cruft_fn cruft_cb,
3414                                each_loose_subdir_fn subdir_cb,
3415                                void *data)
3416{
3417        size_t origlen, baselen;
3418        DIR *dir;
3419        struct dirent *de;
3420        int r = 0;
3421
3422        if (subdir_nr > 0xff)
3423                BUG("invalid loose object subdirectory: %x", subdir_nr);
3424
3425        origlen = path->len;
3426        strbuf_complete(path, '/');
3427        strbuf_addf(path, "%02x", subdir_nr);
3428        baselen = path->len;
3429
3430        dir = opendir(path->buf);
3431        if (!dir) {
3432                if (errno != ENOENT)
3433                        r = error_errno("unable to open %s", path->buf);
3434                strbuf_setlen(path, origlen);
3435                return r;
3436        }
3437
3438        while ((de = readdir(dir))) {
3439                if (is_dot_or_dotdot(de->d_name))
3440                        continue;
3441
3442                strbuf_setlen(path, baselen);
3443                strbuf_addf(path, "/%s", de->d_name);
3444
3445                if (strlen(de->d_name) == GIT_SHA1_HEXSZ - 2)  {
3446                        char hex[GIT_MAX_HEXSZ+1];
3447                        struct object_id oid;
3448
3449                        xsnprintf(hex, sizeof(hex), "%02x%s",
3450                                  subdir_nr, de->d_name);
3451                        if (!get_oid_hex(hex, &oid)) {
3452                                if (obj_cb) {
3453                                        r = obj_cb(&oid, path->buf, data);
3454                                        if (r)
3455                                                break;
3456                                }
3457                                continue;
3458                        }
3459                }
3460
3461                if (cruft_cb) {
3462                        r = cruft_cb(de->d_name, path->buf, data);
3463                        if (r)
3464                                break;
3465                }
3466        }
3467        closedir(dir);
3468
3469        strbuf_setlen(path, baselen);
3470        if (!r && subdir_cb)
3471                r = subdir_cb(subdir_nr, path->buf, data);
3472
3473        strbuf_setlen(path, origlen);
3474
3475        return r;
3476}
3477
3478int for_each_loose_file_in_objdir_buf(struct strbuf *path,
3479                            each_loose_object_fn obj_cb,
3480                            each_loose_cruft_fn cruft_cb,
3481                            each_loose_subdir_fn subdir_cb,
3482                            void *data)
3483{
3484        int r = 0;
3485        int i;
3486
3487        for (i = 0; i < 256; i++) {
3488                r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
3489                                                subdir_cb, data);
3490                if (r)
3491                        break;
3492        }
3493
3494        return r;
3495}
3496
3497int for_each_loose_file_in_objdir(const char *path,
3498                                  each_loose_object_fn obj_cb,
3499                                  each_loose_cruft_fn cruft_cb,
3500                                  each_loose_subdir_fn subdir_cb,
3501                                  void *data)
3502{
3503        struct strbuf buf = STRBUF_INIT;
3504        int r;
3505
3506        strbuf_addstr(&buf, path);
3507        r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
3508                                              subdir_cb, data);
3509        strbuf_release(&buf);
3510
3511        return r;
3512}
3513
3514struct loose_alt_odb_data {
3515        each_loose_object_fn *cb;
3516        void *data;
3517};
3518
3519static int loose_from_alt_odb(struct alternate_object_database *alt,
3520                              void *vdata)
3521{
3522        struct loose_alt_odb_data *data = vdata;
3523        struct strbuf buf = STRBUF_INIT;
3524        int r;
3525
3526        strbuf_addstr(&buf, alt->path);
3527        r = for_each_loose_file_in_objdir_buf(&buf,
3528                                              data->cb, NULL, NULL,
3529                                              data->data);
3530        strbuf_release(&buf);
3531        return r;
3532}
3533
3534int for_each_loose_object(each_loose_object_fn cb, void *data, unsigned flags)
3535{
3536        struct loose_alt_odb_data alt;
3537        int r;
3538
3539        r = for_each_loose_file_in_objdir(get_object_directory(),
3540                                          cb, NULL, NULL, data);
3541        if (r)
3542                return r;
3543
3544        if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
3545                return 0;
3546
3547        alt.cb = cb;
3548        alt.data = data;
3549        return foreach_alt_odb(loose_from_alt_odb, &alt);
3550}
3551
3552static int for_each_object_in_pack(struct packed_git *p, each_packed_object_fn cb, void *data)
3553{
3554        uint32_t i;
3555        int r = 0;
3556
3557        for (i = 0; i < p->num_objects; i++) {
3558                struct object_id oid;
3559
3560                if (!nth_packed_object_oid(&oid, p, i))
3561                        return error("unable to get sha1 of object %u in %s",
3562                                     i, p->pack_name);
3563
3564                r = cb(&oid, p, i, data);
3565                if (r)
3566                        break;
3567        }
3568        return r;
3569}
3570
3571int for_each_packed_object(each_packed_object_fn cb, void *data, unsigned flags)
3572{
3573        struct packed_git *p;
3574        int r = 0;
3575        int pack_errors = 0;
3576
3577        prepare_packed_git();
3578        for (p = packed_git; p; p = p->next) {
3579                if ((flags & FOR_EACH_OBJECT_LOCAL_ONLY) && !p->pack_local)
3580                        continue;
3581                if (open_pack_index(p)) {
3582                        pack_errors = 1;
3583                        continue;
3584                }
3585                r = for_each_object_in_pack(p, cb, data);
3586                if (r)
3587                        break;
3588        }
3589        return r ? r : pack_errors;
3590}
3591
3592static int check_stream_sha1(git_zstream *stream,
3593                             const char *hdr,
3594                             unsigned long size,
3595                             const char *path,
3596                             const unsigned char *expected_sha1)
3597{
3598        git_SHA_CTX c;
3599        unsigned char real_sha1[GIT_MAX_RAWSZ];
3600        unsigned char buf[4096];
3601        unsigned long total_read;
3602        int status = Z_OK;
3603
3604        git_SHA1_Init(&c);
3605        git_SHA1_Update(&c, hdr, stream->total_out);
3606
3607        /*
3608         * We already read some bytes into hdr, but the ones up to the NUL
3609         * do not count against the object's content size.
3610         */
3611        total_read = stream->total_out - strlen(hdr) - 1;
3612
3613        /*
3614         * This size comparison must be "<=" to read the final zlib packets;
3615         * see the comment in unpack_sha1_rest for details.
3616         */
3617        while (total_read <= size &&
3618               (status == Z_OK || status == Z_BUF_ERROR)) {
3619                stream->next_out = buf;
3620                stream->avail_out = sizeof(buf);
3621                if (size - total_read < stream->avail_out)
3622                        stream->avail_out = size - total_read;
3623                status = git_inflate(stream, Z_FINISH);
3624                git_SHA1_Update(&c, buf, stream->next_out - buf);
3625                total_read += stream->next_out - buf;
3626        }
3627        git_inflate_end(stream);
3628
3629        if (status != Z_STREAM_END) {
3630                error("corrupt loose object '%s'", sha1_to_hex(expected_sha1));
3631                return -1;
3632        }
3633        if (stream->avail_in) {
3634                error("garbage at end of loose object '%s'",
3635                      sha1_to_hex(expected_sha1));
3636                return -1;
3637        }
3638
3639        git_SHA1_Final(real_sha1, &c);
3640        if (hashcmp(expected_sha1, real_sha1)) {
3641                error("sha1 mismatch for %s (expected %s)", path,
3642                      sha1_to_hex(expected_sha1));
3643                return -1;
3644        }
3645
3646        return 0;
3647}
3648
3649int read_loose_object(const char *path,
3650                      const unsigned char *expected_sha1,
3651                      enum object_type *type,
3652                      unsigned long *size,
3653                      void **contents)
3654{
3655        int ret = -1;
3656        void *map = NULL;
3657        unsigned long mapsize;
3658        git_zstream stream;
3659        char hdr[32];
3660
3661        *contents = NULL;
3662
3663        map = map_sha1_file_1(path, NULL, &mapsize);
3664        if (!map) {
3665                error_errno("unable to mmap %s", path);
3666                goto out;
3667        }
3668
3669        if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0) {
3670                error("unable to unpack header of %s", path);
3671                goto out;
3672        }
3673
3674        *type = parse_sha1_header(hdr, size);
3675        if (*type < 0) {
3676                error("unable to parse header of %s", path);
3677                git_inflate_end(&stream);
3678                goto out;
3679        }
3680
3681        if (*type == OBJ_BLOB) {
3682                if (check_stream_sha1(&stream, hdr, *size, path, expected_sha1) < 0)
3683                        goto out;
3684        } else {
3685                *contents = unpack_sha1_rest(&stream, hdr, *size, expected_sha1);
3686                if (!*contents) {
3687                        error("unable to unpack contents of %s", path);
3688                        git_inflate_end(&stream);
3689                        goto out;
3690                }
3691                if (check_sha1_signature(expected_sha1, *contents,
3692                                         *size, typename(*type))) {
3693                        error("sha1 mismatch for %s (expected %s)", path,
3694                              sha1_to_hex(expected_sha1));
3695                        free(*contents);
3696                        goto out;
3697                }
3698        }
3699
3700        ret = 0; /* everything checks out */
3701
3702out:
3703        if (map)
3704                munmap(map, mapsize);
3705        return ret;
3706}