38c1084560950d6d54798fbe0938cca524f955fb
   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
 722static void mark_bad_packed_object(struct packed_git *p,
 723                                   const unsigned char *sha1)
 724{
 725        unsigned i;
 726        for (i = 0; i < p->num_bad_objects; i++)
 727                if (!hashcmp(sha1, p->bad_object_sha1 + GIT_SHA1_RAWSZ * i))
 728                        return;
 729        p->bad_object_sha1 = xrealloc(p->bad_object_sha1,
 730                                      st_mult(GIT_MAX_RAWSZ,
 731                                              st_add(p->num_bad_objects, 1)));
 732        hashcpy(p->bad_object_sha1 + GIT_SHA1_RAWSZ * p->num_bad_objects, sha1);
 733        p->num_bad_objects++;
 734}
 735
 736static const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
 737{
 738        struct packed_git *p;
 739        unsigned i;
 740
 741        for (p = packed_git; p; p = p->next)
 742                for (i = 0; i < p->num_bad_objects; i++)
 743                        if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
 744                                return p;
 745        return NULL;
 746}
 747
 748/*
 749 * With an in-core object data in "map", rehash it to make sure the
 750 * object name actually matches "sha1" to detect object corruption.
 751 * With "map" == NULL, try reading the object named with "sha1" using
 752 * the streaming interface and rehash it to do the same.
 753 */
 754int check_sha1_signature(const unsigned char *sha1, void *map,
 755                         unsigned long size, const char *type)
 756{
 757        unsigned char real_sha1[20];
 758        enum object_type obj_type;
 759        struct git_istream *st;
 760        git_SHA_CTX c;
 761        char hdr[32];
 762        int hdrlen;
 763
 764        if (map) {
 765                hash_sha1_file(map, size, type, real_sha1);
 766                return hashcmp(sha1, real_sha1) ? -1 : 0;
 767        }
 768
 769        st = open_istream(sha1, &obj_type, &size, NULL);
 770        if (!st)
 771                return -1;
 772
 773        /* Generate the header */
 774        hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(obj_type), size) + 1;
 775
 776        /* Sha1.. */
 777        git_SHA1_Init(&c);
 778        git_SHA1_Update(&c, hdr, hdrlen);
 779        for (;;) {
 780                char buf[1024 * 16];
 781                ssize_t readlen = read_istream(st, buf, sizeof(buf));
 782
 783                if (readlen < 0) {
 784                        close_istream(st);
 785                        return -1;
 786                }
 787                if (!readlen)
 788                        break;
 789                git_SHA1_Update(&c, buf, readlen);
 790        }
 791        git_SHA1_Final(real_sha1, &c);
 792        close_istream(st);
 793        return hashcmp(sha1, real_sha1) ? -1 : 0;
 794}
 795
 796int git_open_cloexec(const char *name, int flags)
 797{
 798        int fd;
 799        static int o_cloexec = O_CLOEXEC;
 800
 801        fd = open(name, flags | o_cloexec);
 802        if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
 803                /* Try again w/o O_CLOEXEC: the kernel might not support it */
 804                o_cloexec &= ~O_CLOEXEC;
 805                fd = open(name, flags | o_cloexec);
 806        }
 807
 808#if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
 809        {
 810                static int fd_cloexec = FD_CLOEXEC;
 811
 812                if (!o_cloexec && 0 <= fd && fd_cloexec) {
 813                        /* Opened w/o O_CLOEXEC?  try with fcntl(2) to add it */
 814                        int flags = fcntl(fd, F_GETFD);
 815                        if (fcntl(fd, F_SETFD, flags | fd_cloexec))
 816                                fd_cloexec = 0;
 817                }
 818        }
 819#endif
 820        return fd;
 821}
 822
 823/*
 824 * Find "sha1" as a loose object in the local repository or in an alternate.
 825 * Returns 0 on success, negative on failure.
 826 *
 827 * The "path" out-parameter will give the path of the object we found (if any).
 828 * Note that it may point to static storage and is only valid until another
 829 * call to sha1_file_name(), etc.
 830 */
 831static int stat_sha1_file(const unsigned char *sha1, struct stat *st,
 832                          const char **path)
 833{
 834        struct alternate_object_database *alt;
 835
 836        *path = sha1_file_name(sha1);
 837        if (!lstat(*path, st))
 838                return 0;
 839
 840        prepare_alt_odb();
 841        errno = ENOENT;
 842        for (alt = alt_odb_list; alt; alt = alt->next) {
 843                *path = alt_sha1_path(alt, sha1);
 844                if (!lstat(*path, st))
 845                        return 0;
 846        }
 847
 848        return -1;
 849}
 850
 851/*
 852 * Like stat_sha1_file(), but actually open the object and return the
 853 * descriptor. See the caveats on the "path" parameter above.
 854 */
 855static int open_sha1_file(const unsigned char *sha1, const char **path)
 856{
 857        int fd;
 858        struct alternate_object_database *alt;
 859        int most_interesting_errno;
 860
 861        *path = sha1_file_name(sha1);
 862        fd = git_open(*path);
 863        if (fd >= 0)
 864                return fd;
 865        most_interesting_errno = errno;
 866
 867        prepare_alt_odb();
 868        for (alt = alt_odb_list; alt; alt = alt->next) {
 869                *path = alt_sha1_path(alt, sha1);
 870                fd = git_open(*path);
 871                if (fd >= 0)
 872                        return fd;
 873                if (most_interesting_errno == ENOENT)
 874                        most_interesting_errno = errno;
 875        }
 876        errno = most_interesting_errno;
 877        return -1;
 878}
 879
 880/*
 881 * Map the loose object at "path" if it is not NULL, or the path found by
 882 * searching for a loose object named "sha1".
 883 */
 884static void *map_sha1_file_1(const char *path,
 885                             const unsigned char *sha1,
 886                             unsigned long *size)
 887{
 888        void *map;
 889        int fd;
 890
 891        if (path)
 892                fd = git_open(path);
 893        else
 894                fd = open_sha1_file(sha1, &path);
 895        map = NULL;
 896        if (fd >= 0) {
 897                struct stat st;
 898
 899                if (!fstat(fd, &st)) {
 900                        *size = xsize_t(st.st_size);
 901                        if (!*size) {
 902                                /* mmap() is forbidden on empty files */
 903                                error("object file %s is empty", path);
 904                                return NULL;
 905                        }
 906                        map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
 907                }
 908                close(fd);
 909        }
 910        return map;
 911}
 912
 913void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
 914{
 915        return map_sha1_file_1(NULL, sha1, size);
 916}
 917
 918static int unpack_sha1_short_header(git_zstream *stream,
 919                                    unsigned char *map, unsigned long mapsize,
 920                                    void *buffer, unsigned long bufsiz)
 921{
 922        /* Get the data stream */
 923        memset(stream, 0, sizeof(*stream));
 924        stream->next_in = map;
 925        stream->avail_in = mapsize;
 926        stream->next_out = buffer;
 927        stream->avail_out = bufsiz;
 928
 929        git_inflate_init(stream);
 930        return git_inflate(stream, 0);
 931}
 932
 933int unpack_sha1_header(git_zstream *stream,
 934                       unsigned char *map, unsigned long mapsize,
 935                       void *buffer, unsigned long bufsiz)
 936{
 937        int status = unpack_sha1_short_header(stream, map, mapsize,
 938                                              buffer, bufsiz);
 939
 940        if (status < Z_OK)
 941                return status;
 942
 943        /* Make sure we have the terminating NUL */
 944        if (!memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
 945                return -1;
 946        return 0;
 947}
 948
 949static int unpack_sha1_header_to_strbuf(git_zstream *stream, unsigned char *map,
 950                                        unsigned long mapsize, void *buffer,
 951                                        unsigned long bufsiz, struct strbuf *header)
 952{
 953        int status;
 954
 955        status = unpack_sha1_short_header(stream, map, mapsize, buffer, bufsiz);
 956        if (status < Z_OK)
 957                return -1;
 958
 959        /*
 960         * Check if entire header is unpacked in the first iteration.
 961         */
 962        if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
 963                return 0;
 964
 965        /*
 966         * buffer[0..bufsiz] was not large enough.  Copy the partial
 967         * result out to header, and then append the result of further
 968         * reading the stream.
 969         */
 970        strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
 971        stream->next_out = buffer;
 972        stream->avail_out = bufsiz;
 973
 974        do {
 975                status = git_inflate(stream, 0);
 976                strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
 977                if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
 978                        return 0;
 979                stream->next_out = buffer;
 980                stream->avail_out = bufsiz;
 981        } while (status != Z_STREAM_END);
 982        return -1;
 983}
 984
 985static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
 986{
 987        int bytes = strlen(buffer) + 1;
 988        unsigned char *buf = xmallocz(size);
 989        unsigned long n;
 990        int status = Z_OK;
 991
 992        n = stream->total_out - bytes;
 993        if (n > size)
 994                n = size;
 995        memcpy(buf, (char *) buffer + bytes, n);
 996        bytes = n;
 997        if (bytes <= size) {
 998                /*
 999                 * The above condition must be (bytes <= size), not
1000                 * (bytes < size).  In other words, even though we
1001                 * expect no more output and set avail_out to zero,
1002                 * the input zlib stream may have bytes that express
1003                 * "this concludes the stream", and we *do* want to
1004                 * eat that input.
1005                 *
1006                 * Otherwise we would not be able to test that we
1007                 * consumed all the input to reach the expected size;
1008                 * we also want to check that zlib tells us that all
1009                 * went well with status == Z_STREAM_END at the end.
1010                 */
1011                stream->next_out = buf + bytes;
1012                stream->avail_out = size - bytes;
1013                while (status == Z_OK)
1014                        status = git_inflate(stream, Z_FINISH);
1015        }
1016        if (status == Z_STREAM_END && !stream->avail_in) {
1017                git_inflate_end(stream);
1018                return buf;
1019        }
1020
1021        if (status < 0)
1022                error("corrupt loose object '%s'", sha1_to_hex(sha1));
1023        else if (stream->avail_in)
1024                error("garbage at end of loose object '%s'",
1025                      sha1_to_hex(sha1));
1026        free(buf);
1027        return NULL;
1028}
1029
1030/*
1031 * We used to just use "sscanf()", but that's actually way
1032 * too permissive for what we want to check. So do an anal
1033 * object header parse by hand.
1034 */
1035static int parse_sha1_header_extended(const char *hdr, struct object_info *oi,
1036                               unsigned int flags)
1037{
1038        const char *type_buf = hdr;
1039        unsigned long size;
1040        int type, type_len = 0;
1041
1042        /*
1043         * The type can be of any size but is followed by
1044         * a space.
1045         */
1046        for (;;) {
1047                char c = *hdr++;
1048                if (!c)
1049                        return -1;
1050                if (c == ' ')
1051                        break;
1052                type_len++;
1053        }
1054
1055        type = type_from_string_gently(type_buf, type_len, 1);
1056        if (oi->typename)
1057                strbuf_add(oi->typename, type_buf, type_len);
1058        /*
1059         * Set type to 0 if its an unknown object and
1060         * we're obtaining the type using '--allow-unknown-type'
1061         * option.
1062         */
1063        if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE) && (type < 0))
1064                type = 0;
1065        else if (type < 0)
1066                die("invalid object type");
1067        if (oi->typep)
1068                *oi->typep = type;
1069
1070        /*
1071         * The length must follow immediately, and be in canonical
1072         * decimal format (ie "010" is not valid).
1073         */
1074        size = *hdr++ - '0';
1075        if (size > 9)
1076                return -1;
1077        if (size) {
1078                for (;;) {
1079                        unsigned long c = *hdr - '0';
1080                        if (c > 9)
1081                                break;
1082                        hdr++;
1083                        size = size * 10 + c;
1084                }
1085        }
1086
1087        if (oi->sizep)
1088                *oi->sizep = size;
1089
1090        /*
1091         * The length must be followed by a zero byte
1092         */
1093        return *hdr ? -1 : type;
1094}
1095
1096int parse_sha1_header(const char *hdr, unsigned long *sizep)
1097{
1098        struct object_info oi = OBJECT_INFO_INIT;
1099
1100        oi.sizep = sizep;
1101        return parse_sha1_header_extended(hdr, &oi, 0);
1102}
1103
1104static off_t get_delta_base(struct packed_git *p,
1105                                    struct pack_window **w_curs,
1106                                    off_t *curpos,
1107                                    enum object_type type,
1108                                    off_t delta_obj_offset)
1109{
1110        unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1111        off_t base_offset;
1112
1113        /* use_pack() assured us we have [base_info, base_info + 20)
1114         * as a range that we can look at without walking off the
1115         * end of the mapped window.  Its actually the hash size
1116         * that is assured.  An OFS_DELTA longer than the hash size
1117         * is stupid, as then a REF_DELTA would be smaller to store.
1118         */
1119        if (type == OBJ_OFS_DELTA) {
1120                unsigned used = 0;
1121                unsigned char c = base_info[used++];
1122                base_offset = c & 127;
1123                while (c & 128) {
1124                        base_offset += 1;
1125                        if (!base_offset || MSB(base_offset, 7))
1126                                return 0;  /* overflow */
1127                        c = base_info[used++];
1128                        base_offset = (base_offset << 7) + (c & 127);
1129                }
1130                base_offset = delta_obj_offset - base_offset;
1131                if (base_offset <= 0 || base_offset >= delta_obj_offset)
1132                        return 0;  /* out of bound */
1133                *curpos += used;
1134        } else if (type == OBJ_REF_DELTA) {
1135                /* The base entry _must_ be in the same pack */
1136                base_offset = find_pack_entry_one(base_info, p);
1137                *curpos += 20;
1138        } else
1139                die("I am totally screwed");
1140        return base_offset;
1141}
1142
1143/*
1144 * Like get_delta_base above, but we return the sha1 instead of the pack
1145 * offset. This means it is cheaper for REF deltas (we do not have to do
1146 * the final object lookup), but more expensive for OFS deltas (we
1147 * have to load the revidx to convert the offset back into a sha1).
1148 */
1149static const unsigned char *get_delta_base_sha1(struct packed_git *p,
1150                                                struct pack_window **w_curs,
1151                                                off_t curpos,
1152                                                enum object_type type,
1153                                                off_t delta_obj_offset)
1154{
1155        if (type == OBJ_REF_DELTA) {
1156                unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1157                return base;
1158        } else if (type == OBJ_OFS_DELTA) {
1159                struct revindex_entry *revidx;
1160                off_t base_offset = get_delta_base(p, w_curs, &curpos,
1161                                                   type, delta_obj_offset);
1162
1163                if (!base_offset)
1164                        return NULL;
1165
1166                revidx = find_pack_revindex(p, base_offset);
1167                if (!revidx)
1168                        return NULL;
1169
1170                return nth_packed_object_sha1(p, revidx->nr);
1171        } else
1172                return NULL;
1173}
1174
1175int unpack_object_header(struct packed_git *p,
1176                         struct pack_window **w_curs,
1177                         off_t *curpos,
1178                         unsigned long *sizep)
1179{
1180        unsigned char *base;
1181        unsigned long left;
1182        unsigned long used;
1183        enum object_type type;
1184
1185        /* use_pack() assures us we have [base, base + 20) available
1186         * as a range that we can look at.  (Its actually the hash
1187         * size that is assured.)  With our object header encoding
1188         * the maximum deflated object size is 2^137, which is just
1189         * insane, so we know won't exceed what we have been given.
1190         */
1191        base = use_pack(p, w_curs, *curpos, &left);
1192        used = unpack_object_header_buffer(base, left, &type, sizep);
1193        if (!used) {
1194                type = OBJ_BAD;
1195        } else
1196                *curpos += used;
1197
1198        return type;
1199}
1200
1201static int retry_bad_packed_offset(struct packed_git *p, off_t obj_offset)
1202{
1203        int type;
1204        struct revindex_entry *revidx;
1205        const unsigned char *sha1;
1206        revidx = find_pack_revindex(p, obj_offset);
1207        if (!revidx)
1208                return OBJ_BAD;
1209        sha1 = nth_packed_object_sha1(p, revidx->nr);
1210        mark_bad_packed_object(p, sha1);
1211        type = sha1_object_info(sha1, NULL);
1212        if (type <= OBJ_NONE)
1213                return OBJ_BAD;
1214        return type;
1215}
1216
1217#define POI_STACK_PREALLOC 64
1218
1219static enum object_type packed_to_object_type(struct packed_git *p,
1220                                              off_t obj_offset,
1221                                              enum object_type type,
1222                                              struct pack_window **w_curs,
1223                                              off_t curpos)
1224{
1225        off_t small_poi_stack[POI_STACK_PREALLOC];
1226        off_t *poi_stack = small_poi_stack;
1227        int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1228
1229        while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1230                off_t base_offset;
1231                unsigned long size;
1232                /* Push the object we're going to leave behind */
1233                if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1234                        poi_stack_alloc = alloc_nr(poi_stack_nr);
1235                        ALLOC_ARRAY(poi_stack, poi_stack_alloc);
1236                        memcpy(poi_stack, small_poi_stack, sizeof(off_t)*poi_stack_nr);
1237                } else {
1238                        ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1239                }
1240                poi_stack[poi_stack_nr++] = obj_offset;
1241                /* If parsing the base offset fails, just unwind */
1242                base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1243                if (!base_offset)
1244                        goto unwind;
1245                curpos = obj_offset = base_offset;
1246                type = unpack_object_header(p, w_curs, &curpos, &size);
1247                if (type <= OBJ_NONE) {
1248                        /* If getting the base itself fails, we first
1249                         * retry the base, otherwise unwind */
1250                        type = retry_bad_packed_offset(p, base_offset);
1251                        if (type > OBJ_NONE)
1252                                goto out;
1253                        goto unwind;
1254                }
1255        }
1256
1257        switch (type) {
1258        case OBJ_BAD:
1259        case OBJ_COMMIT:
1260        case OBJ_TREE:
1261        case OBJ_BLOB:
1262        case OBJ_TAG:
1263                break;
1264        default:
1265                error("unknown object type %i at offset %"PRIuMAX" in %s",
1266                      type, (uintmax_t)obj_offset, p->pack_name);
1267                type = OBJ_BAD;
1268        }
1269
1270out:
1271        if (poi_stack != small_poi_stack)
1272                free(poi_stack);
1273        return type;
1274
1275unwind:
1276        while (poi_stack_nr) {
1277                obj_offset = poi_stack[--poi_stack_nr];
1278                type = retry_bad_packed_offset(p, obj_offset);
1279                if (type > OBJ_NONE)
1280                        goto out;
1281        }
1282        type = OBJ_BAD;
1283        goto out;
1284}
1285
1286static struct hashmap delta_base_cache;
1287static size_t delta_base_cached;
1288
1289static LIST_HEAD(delta_base_cache_lru);
1290
1291struct delta_base_cache_key {
1292        struct packed_git *p;
1293        off_t base_offset;
1294};
1295
1296struct delta_base_cache_entry {
1297        struct hashmap hash;
1298        struct delta_base_cache_key key;
1299        struct list_head lru;
1300        void *data;
1301        unsigned long size;
1302        enum object_type type;
1303};
1304
1305static unsigned int pack_entry_hash(struct packed_git *p, off_t base_offset)
1306{
1307        unsigned int hash;
1308
1309        hash = (unsigned int)(intptr_t)p + (unsigned int)base_offset;
1310        hash += (hash >> 8) + (hash >> 16);
1311        return hash;
1312}
1313
1314static struct delta_base_cache_entry *
1315get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
1316{
1317        struct hashmap_entry entry;
1318        struct delta_base_cache_key key;
1319
1320        if (!delta_base_cache.cmpfn)
1321                return NULL;
1322
1323        hashmap_entry_init(&entry, pack_entry_hash(p, base_offset));
1324        key.p = p;
1325        key.base_offset = base_offset;
1326        return hashmap_get(&delta_base_cache, &entry, &key);
1327}
1328
1329static int delta_base_cache_key_eq(const struct delta_base_cache_key *a,
1330                                   const struct delta_base_cache_key *b)
1331{
1332        return a->p == b->p && a->base_offset == b->base_offset;
1333}
1334
1335static int delta_base_cache_hash_cmp(const void *unused_cmp_data,
1336                                     const void *va, const void *vb,
1337                                     const void *vkey)
1338{
1339        const struct delta_base_cache_entry *a = va, *b = vb;
1340        const struct delta_base_cache_key *key = vkey;
1341        if (key)
1342                return !delta_base_cache_key_eq(&a->key, key);
1343        else
1344                return !delta_base_cache_key_eq(&a->key, &b->key);
1345}
1346
1347static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
1348{
1349        return !!get_delta_base_cache_entry(p, base_offset);
1350}
1351
1352/*
1353 * Remove the entry from the cache, but do _not_ free the associated
1354 * entry data. The caller takes ownership of the "data" buffer, and
1355 * should copy out any fields it wants before detaching.
1356 */
1357static void detach_delta_base_cache_entry(struct delta_base_cache_entry *ent)
1358{
1359        hashmap_remove(&delta_base_cache, ent, &ent->key);
1360        list_del(&ent->lru);
1361        delta_base_cached -= ent->size;
1362        free(ent);
1363}
1364
1365static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
1366        unsigned long *base_size, enum object_type *type)
1367{
1368        struct delta_base_cache_entry *ent;
1369
1370        ent = get_delta_base_cache_entry(p, base_offset);
1371        if (!ent)
1372                return unpack_entry(p, base_offset, type, base_size);
1373
1374        if (type)
1375                *type = ent->type;
1376        if (base_size)
1377                *base_size = ent->size;
1378        return xmemdupz(ent->data, ent->size);
1379}
1380
1381static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1382{
1383        free(ent->data);
1384        detach_delta_base_cache_entry(ent);
1385}
1386
1387void clear_delta_base_cache(void)
1388{
1389        struct list_head *lru, *tmp;
1390        list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1391                struct delta_base_cache_entry *entry =
1392                        list_entry(lru, struct delta_base_cache_entry, lru);
1393                release_delta_base_cache(entry);
1394        }
1395}
1396
1397static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1398        void *base, unsigned long base_size, enum object_type type)
1399{
1400        struct delta_base_cache_entry *ent = xmalloc(sizeof(*ent));
1401        struct list_head *lru, *tmp;
1402
1403        delta_base_cached += base_size;
1404
1405        list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1406                struct delta_base_cache_entry *f =
1407                        list_entry(lru, struct delta_base_cache_entry, lru);
1408                if (delta_base_cached <= delta_base_cache_limit)
1409                        break;
1410                release_delta_base_cache(f);
1411        }
1412
1413        ent->key.p = p;
1414        ent->key.base_offset = base_offset;
1415        ent->type = type;
1416        ent->data = base;
1417        ent->size = base_size;
1418        list_add_tail(&ent->lru, &delta_base_cache_lru);
1419
1420        if (!delta_base_cache.cmpfn)
1421                hashmap_init(&delta_base_cache, delta_base_cache_hash_cmp, NULL, 0);
1422        hashmap_entry_init(ent, pack_entry_hash(p, base_offset));
1423        hashmap_add(&delta_base_cache, ent);
1424}
1425
1426int packed_object_info(struct packed_git *p, off_t obj_offset,
1427                       struct object_info *oi)
1428{
1429        struct pack_window *w_curs = NULL;
1430        unsigned long size;
1431        off_t curpos = obj_offset;
1432        enum object_type type;
1433
1434        /*
1435         * We always get the representation type, but only convert it to
1436         * a "real" type later if the caller is interested.
1437         */
1438        if (oi->contentp) {
1439                *oi->contentp = cache_or_unpack_entry(p, obj_offset, oi->sizep,
1440                                                      &type);
1441                if (!*oi->contentp)
1442                        type = OBJ_BAD;
1443        } else {
1444                type = unpack_object_header(p, &w_curs, &curpos, &size);
1445        }
1446
1447        if (!oi->contentp && oi->sizep) {
1448                if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1449                        off_t tmp_pos = curpos;
1450                        off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1451                                                           type, obj_offset);
1452                        if (!base_offset) {
1453                                type = OBJ_BAD;
1454                                goto out;
1455                        }
1456                        *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
1457                        if (*oi->sizep == 0) {
1458                                type = OBJ_BAD;
1459                                goto out;
1460                        }
1461                } else {
1462                        *oi->sizep = size;
1463                }
1464        }
1465
1466        if (oi->disk_sizep) {
1467                struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1468                *oi->disk_sizep = revidx[1].offset - obj_offset;
1469        }
1470
1471        if (oi->typep || oi->typename) {
1472                enum object_type ptot;
1473                ptot = packed_to_object_type(p, obj_offset, type, &w_curs,
1474                                             curpos);
1475                if (oi->typep)
1476                        *oi->typep = ptot;
1477                if (oi->typename) {
1478                        const char *tn = typename(ptot);
1479                        if (tn)
1480                                strbuf_addstr(oi->typename, tn);
1481                }
1482                if (ptot < 0) {
1483                        type = OBJ_BAD;
1484                        goto out;
1485                }
1486        }
1487
1488        if (oi->delta_base_sha1) {
1489                if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1490                        const unsigned char *base;
1491
1492                        base = get_delta_base_sha1(p, &w_curs, curpos,
1493                                                   type, obj_offset);
1494                        if (!base) {
1495                                type = OBJ_BAD;
1496                                goto out;
1497                        }
1498
1499                        hashcpy(oi->delta_base_sha1, base);
1500                } else
1501                        hashclr(oi->delta_base_sha1);
1502        }
1503
1504        oi->whence = in_delta_base_cache(p, obj_offset) ? OI_DBCACHED :
1505                                                          OI_PACKED;
1506
1507out:
1508        unuse_pack(&w_curs);
1509        return type;
1510}
1511
1512static void *unpack_compressed_entry(struct packed_git *p,
1513                                    struct pack_window **w_curs,
1514                                    off_t curpos,
1515                                    unsigned long size)
1516{
1517        int st;
1518        git_zstream stream;
1519        unsigned char *buffer, *in;
1520
1521        buffer = xmallocz_gently(size);
1522        if (!buffer)
1523                return NULL;
1524        memset(&stream, 0, sizeof(stream));
1525        stream.next_out = buffer;
1526        stream.avail_out = size + 1;
1527
1528        git_inflate_init(&stream);
1529        do {
1530                in = use_pack(p, w_curs, curpos, &stream.avail_in);
1531                stream.next_in = in;
1532                st = git_inflate(&stream, Z_FINISH);
1533                if (!stream.avail_out)
1534                        break; /* the payload is larger than it should be */
1535                curpos += stream.next_in - in;
1536        } while (st == Z_OK || st == Z_BUF_ERROR);
1537        git_inflate_end(&stream);
1538        if ((st != Z_STREAM_END) || stream.total_out != size) {
1539                free(buffer);
1540                return NULL;
1541        }
1542
1543        return buffer;
1544}
1545
1546static void *read_object(const unsigned char *sha1, enum object_type *type,
1547                         unsigned long *size);
1548
1549static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
1550{
1551        static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
1552        trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
1553                         p->pack_name, (uintmax_t)obj_offset);
1554}
1555
1556int do_check_packed_object_crc;
1557
1558#define UNPACK_ENTRY_STACK_PREALLOC 64
1559struct unpack_entry_stack_ent {
1560        off_t obj_offset;
1561        off_t curpos;
1562        unsigned long size;
1563};
1564
1565void *unpack_entry(struct packed_git *p, off_t obj_offset,
1566                   enum object_type *final_type, unsigned long *final_size)
1567{
1568        struct pack_window *w_curs = NULL;
1569        off_t curpos = obj_offset;
1570        void *data = NULL;
1571        unsigned long size;
1572        enum object_type type;
1573        struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
1574        struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
1575        int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
1576        int base_from_cache = 0;
1577
1578        write_pack_access_log(p, obj_offset);
1579
1580        /* PHASE 1: drill down to the innermost base object */
1581        for (;;) {
1582                off_t base_offset;
1583                int i;
1584                struct delta_base_cache_entry *ent;
1585
1586                ent = get_delta_base_cache_entry(p, curpos);
1587                if (ent) {
1588                        type = ent->type;
1589                        data = ent->data;
1590                        size = ent->size;
1591                        detach_delta_base_cache_entry(ent);
1592                        base_from_cache = 1;
1593                        break;
1594                }
1595
1596                if (do_check_packed_object_crc && p->index_version > 1) {
1597                        struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1598                        off_t len = revidx[1].offset - obj_offset;
1599                        if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
1600                                const unsigned char *sha1 =
1601                                        nth_packed_object_sha1(p, revidx->nr);
1602                                error("bad packed object CRC for %s",
1603                                      sha1_to_hex(sha1));
1604                                mark_bad_packed_object(p, sha1);
1605                                data = NULL;
1606                                goto out;
1607                        }
1608                }
1609
1610                type = unpack_object_header(p, &w_curs, &curpos, &size);
1611                if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
1612                        break;
1613
1614                base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1615                if (!base_offset) {
1616                        error("failed to validate delta base reference "
1617                              "at offset %"PRIuMAX" from %s",
1618                              (uintmax_t)curpos, p->pack_name);
1619                        /* bail to phase 2, in hopes of recovery */
1620                        data = NULL;
1621                        break;
1622                }
1623
1624                /* push object, proceed to base */
1625                if (delta_stack_nr >= delta_stack_alloc
1626                    && delta_stack == small_delta_stack) {
1627                        delta_stack_alloc = alloc_nr(delta_stack_nr);
1628                        ALLOC_ARRAY(delta_stack, delta_stack_alloc);
1629                        memcpy(delta_stack, small_delta_stack,
1630                               sizeof(*delta_stack)*delta_stack_nr);
1631                } else {
1632                        ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
1633                }
1634                i = delta_stack_nr++;
1635                delta_stack[i].obj_offset = obj_offset;
1636                delta_stack[i].curpos = curpos;
1637                delta_stack[i].size = size;
1638
1639                curpos = obj_offset = base_offset;
1640        }
1641
1642        /* PHASE 2: handle the base */
1643        switch (type) {
1644        case OBJ_OFS_DELTA:
1645        case OBJ_REF_DELTA:
1646                if (data)
1647                        die("BUG: unpack_entry: left loop at a valid delta");
1648                break;
1649        case OBJ_COMMIT:
1650        case OBJ_TREE:
1651        case OBJ_BLOB:
1652        case OBJ_TAG:
1653                if (!base_from_cache)
1654                        data = unpack_compressed_entry(p, &w_curs, curpos, size);
1655                break;
1656        default:
1657                data = NULL;
1658                error("unknown object type %i at offset %"PRIuMAX" in %s",
1659                      type, (uintmax_t)obj_offset, p->pack_name);
1660        }
1661
1662        /* PHASE 3: apply deltas in order */
1663
1664        /* invariants:
1665         *   'data' holds the base data, or NULL if there was corruption
1666         */
1667        while (delta_stack_nr) {
1668                void *delta_data;
1669                void *base = data;
1670                void *external_base = NULL;
1671                unsigned long delta_size, base_size = size;
1672                int i;
1673
1674                data = NULL;
1675
1676                if (base)
1677                        add_delta_base_cache(p, obj_offset, base, base_size, type);
1678
1679                if (!base) {
1680                        /*
1681                         * We're probably in deep shit, but let's try to fetch
1682                         * the required base anyway from another pack or loose.
1683                         * This is costly but should happen only in the presence
1684                         * of a corrupted pack, and is better than failing outright.
1685                         */
1686                        struct revindex_entry *revidx;
1687                        const unsigned char *base_sha1;
1688                        revidx = find_pack_revindex(p, obj_offset);
1689                        if (revidx) {
1690                                base_sha1 = nth_packed_object_sha1(p, revidx->nr);
1691                                error("failed to read delta base object %s"
1692                                      " at offset %"PRIuMAX" from %s",
1693                                      sha1_to_hex(base_sha1), (uintmax_t)obj_offset,
1694                                      p->pack_name);
1695                                mark_bad_packed_object(p, base_sha1);
1696                                base = read_object(base_sha1, &type, &base_size);
1697                                external_base = base;
1698                        }
1699                }
1700
1701                i = --delta_stack_nr;
1702                obj_offset = delta_stack[i].obj_offset;
1703                curpos = delta_stack[i].curpos;
1704                delta_size = delta_stack[i].size;
1705
1706                if (!base)
1707                        continue;
1708
1709                delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
1710
1711                if (!delta_data) {
1712                        error("failed to unpack compressed delta "
1713                              "at offset %"PRIuMAX" from %s",
1714                              (uintmax_t)curpos, p->pack_name);
1715                        data = NULL;
1716                        free(external_base);
1717                        continue;
1718                }
1719
1720                data = patch_delta(base, base_size,
1721                                   delta_data, delta_size,
1722                                   &size);
1723
1724                /*
1725                 * We could not apply the delta; warn the user, but keep going.
1726                 * Our failure will be noticed either in the next iteration of
1727                 * the loop, or if this is the final delta, in the caller when
1728                 * we return NULL. Those code paths will take care of making
1729                 * a more explicit warning and retrying with another copy of
1730                 * the object.
1731                 */
1732                if (!data)
1733                        error("failed to apply delta");
1734
1735                free(delta_data);
1736                free(external_base);
1737        }
1738
1739        if (final_type)
1740                *final_type = type;
1741        if (final_size)
1742                *final_size = size;
1743
1744out:
1745        unuse_pack(&w_curs);
1746
1747        if (delta_stack != small_delta_stack)
1748                free(delta_stack);
1749
1750        return data;
1751}
1752
1753const unsigned char *nth_packed_object_sha1(struct packed_git *p,
1754                                            uint32_t n)
1755{
1756        const unsigned char *index = p->index_data;
1757        if (!index) {
1758                if (open_pack_index(p))
1759                        return NULL;
1760                index = p->index_data;
1761        }
1762        if (n >= p->num_objects)
1763                return NULL;
1764        index += 4 * 256;
1765        if (p->index_version == 1) {
1766                return index + 24 * n + 4;
1767        } else {
1768                index += 8;
1769                return index + 20 * n;
1770        }
1771}
1772
1773const struct object_id *nth_packed_object_oid(struct object_id *oid,
1774                                              struct packed_git *p,
1775                                              uint32_t n)
1776{
1777        const unsigned char *hash = nth_packed_object_sha1(p, n);
1778        if (!hash)
1779                return NULL;
1780        hashcpy(oid->hash, hash);
1781        return oid;
1782}
1783
1784void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
1785{
1786        const unsigned char *ptr = vptr;
1787        const unsigned char *start = p->index_data;
1788        const unsigned char *end = start + p->index_size;
1789        if (ptr < start)
1790                die(_("offset before start of pack index for %s (corrupt index?)"),
1791                    p->pack_name);
1792        /* No need to check for underflow; .idx files must be at least 8 bytes */
1793        if (ptr >= end - 8)
1794                die(_("offset beyond end of pack index for %s (truncated index?)"),
1795                    p->pack_name);
1796}
1797
1798off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1799{
1800        const unsigned char *index = p->index_data;
1801        index += 4 * 256;
1802        if (p->index_version == 1) {
1803                return ntohl(*((uint32_t *)(index + 24 * n)));
1804        } else {
1805                uint32_t off;
1806                index += 8 + p->num_objects * (20 + 4);
1807                off = ntohl(*((uint32_t *)(index + 4 * n)));
1808                if (!(off & 0x80000000))
1809                        return off;
1810                index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1811                check_pack_index_ptr(p, index);
1812                return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
1813                                   ntohl(*((uint32_t *)(index + 4)));
1814        }
1815}
1816
1817off_t find_pack_entry_one(const unsigned char *sha1,
1818                                  struct packed_git *p)
1819{
1820        const uint32_t *level1_ofs = p->index_data;
1821        const unsigned char *index = p->index_data;
1822        unsigned hi, lo, stride;
1823        static int debug_lookup = -1;
1824
1825        if (debug_lookup < 0)
1826                debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
1827
1828        if (!index) {
1829                if (open_pack_index(p))
1830                        return 0;
1831                level1_ofs = p->index_data;
1832                index = p->index_data;
1833        }
1834        if (p->index_version > 1) {
1835                level1_ofs += 2;
1836                index += 8;
1837        }
1838        index += 4 * 256;
1839        hi = ntohl(level1_ofs[*sha1]);
1840        lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1841        if (p->index_version > 1) {
1842                stride = 20;
1843        } else {
1844                stride = 24;
1845                index += 4;
1846        }
1847
1848        if (debug_lookup)
1849                printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
1850                       sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
1851
1852        while (lo < hi) {
1853                unsigned mi = (lo + hi) / 2;
1854                int cmp = hashcmp(index + mi * stride, sha1);
1855
1856                if (debug_lookup)
1857                        printf("lo %u hi %u rg %u mi %u\n",
1858                               lo, hi, hi - lo, mi);
1859                if (!cmp)
1860                        return nth_packed_object_offset(p, mi);
1861                if (cmp > 0)
1862                        hi = mi;
1863                else
1864                        lo = mi+1;
1865        }
1866        return 0;
1867}
1868
1869int is_pack_valid(struct packed_git *p)
1870{
1871        /* An already open pack is known to be valid. */
1872        if (p->pack_fd != -1)
1873                return 1;
1874
1875        /* If the pack has one window completely covering the
1876         * file size, the pack is known to be valid even if
1877         * the descriptor is not currently open.
1878         */
1879        if (p->windows) {
1880                struct pack_window *w = p->windows;
1881
1882                if (!w->offset && w->len == p->pack_size)
1883                        return 1;
1884        }
1885
1886        /* Force the pack to open to prove its valid. */
1887        return !open_packed_git(p);
1888}
1889
1890static int fill_pack_entry(const unsigned char *sha1,
1891                           struct pack_entry *e,
1892                           struct packed_git *p)
1893{
1894        off_t offset;
1895
1896        if (p->num_bad_objects) {
1897                unsigned i;
1898                for (i = 0; i < p->num_bad_objects; i++)
1899                        if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1900                                return 0;
1901        }
1902
1903        offset = find_pack_entry_one(sha1, p);
1904        if (!offset)
1905                return 0;
1906
1907        /*
1908         * We are about to tell the caller where they can locate the
1909         * requested object.  We better make sure the packfile is
1910         * still here and can be accessed before supplying that
1911         * answer, as it may have been deleted since the index was
1912         * loaded!
1913         */
1914        if (!is_pack_valid(p))
1915                return 0;
1916        e->offset = offset;
1917        e->p = p;
1918        hashcpy(e->sha1, sha1);
1919        return 1;
1920}
1921
1922/*
1923 * Iff a pack file contains the object named by sha1, return true and
1924 * store its location to e.
1925 */
1926static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1927{
1928        struct mru_entry *p;
1929
1930        prepare_packed_git();
1931        if (!packed_git)
1932                return 0;
1933
1934        for (p = packed_git_mru->head; p; p = p->next) {
1935                if (fill_pack_entry(sha1, e, p->item)) {
1936                        mru_mark(packed_git_mru, p);
1937                        return 1;
1938                }
1939        }
1940        return 0;
1941}
1942
1943struct packed_git *find_sha1_pack(const unsigned char *sha1,
1944                                  struct packed_git *packs)
1945{
1946        struct packed_git *p;
1947
1948        for (p = packs; p; p = p->next) {
1949                if (find_pack_entry_one(sha1, p))
1950                        return p;
1951        }
1952        return NULL;
1953
1954}
1955
1956static int sha1_loose_object_info(const unsigned char *sha1,
1957                                  struct object_info *oi,
1958                                  int flags)
1959{
1960        int status = 0;
1961        unsigned long mapsize;
1962        void *map;
1963        git_zstream stream;
1964        char hdr[32];
1965        struct strbuf hdrbuf = STRBUF_INIT;
1966        unsigned long size_scratch;
1967
1968        if (oi->delta_base_sha1)
1969                hashclr(oi->delta_base_sha1);
1970
1971        /*
1972         * If we don't care about type or size, then we don't
1973         * need to look inside the object at all. Note that we
1974         * do not optimize out the stat call, even if the
1975         * caller doesn't care about the disk-size, since our
1976         * return value implicitly indicates whether the
1977         * object even exists.
1978         */
1979        if (!oi->typep && !oi->typename && !oi->sizep && !oi->contentp) {
1980                const char *path;
1981                struct stat st;
1982                if (stat_sha1_file(sha1, &st, &path) < 0)
1983                        return -1;
1984                if (oi->disk_sizep)
1985                        *oi->disk_sizep = st.st_size;
1986                return 0;
1987        }
1988
1989        map = map_sha1_file(sha1, &mapsize);
1990        if (!map)
1991                return -1;
1992
1993        if (!oi->sizep)
1994                oi->sizep = &size_scratch;
1995
1996        if (oi->disk_sizep)
1997                *oi->disk_sizep = mapsize;
1998        if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE)) {
1999                if (unpack_sha1_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
2000                        status = error("unable to unpack %s header with --allow-unknown-type",
2001                                       sha1_to_hex(sha1));
2002        } else if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
2003                status = error("unable to unpack %s header",
2004                               sha1_to_hex(sha1));
2005        if (status < 0)
2006                ; /* Do nothing */
2007        else if (hdrbuf.len) {
2008                if ((status = parse_sha1_header_extended(hdrbuf.buf, oi, flags)) < 0)
2009                        status = error("unable to parse %s header with --allow-unknown-type",
2010                                       sha1_to_hex(sha1));
2011        } else if ((status = parse_sha1_header_extended(hdr, oi, flags)) < 0)
2012                status = error("unable to parse %s header", sha1_to_hex(sha1));
2013
2014        if (status >= 0 && oi->contentp)
2015                *oi->contentp = unpack_sha1_rest(&stream, hdr,
2016                                                 *oi->sizep, sha1);
2017        else
2018                git_inflate_end(&stream);
2019
2020        munmap(map, mapsize);
2021        if (status && oi->typep)
2022                *oi->typep = status;
2023        if (oi->sizep == &size_scratch)
2024                oi->sizep = NULL;
2025        strbuf_release(&hdrbuf);
2026        oi->whence = OI_LOOSE;
2027        return (status < 0) ? status : 0;
2028}
2029
2030int sha1_object_info_extended(const unsigned char *sha1, struct object_info *oi, unsigned flags)
2031{
2032        static struct object_info blank_oi = OBJECT_INFO_INIT;
2033        struct pack_entry e;
2034        int rtype;
2035        const unsigned char *real = (flags & OBJECT_INFO_LOOKUP_REPLACE) ?
2036                                    lookup_replace_object(sha1) :
2037                                    sha1;
2038
2039        if (!oi)
2040                oi = &blank_oi;
2041
2042        if (!(flags & OBJECT_INFO_SKIP_CACHED)) {
2043                struct cached_object *co = find_cached_object(real);
2044                if (co) {
2045                        if (oi->typep)
2046                                *(oi->typep) = co->type;
2047                        if (oi->sizep)
2048                                *(oi->sizep) = co->size;
2049                        if (oi->disk_sizep)
2050                                *(oi->disk_sizep) = 0;
2051                        if (oi->delta_base_sha1)
2052                                hashclr(oi->delta_base_sha1);
2053                        if (oi->typename)
2054                                strbuf_addstr(oi->typename, typename(co->type));
2055                        if (oi->contentp)
2056                                *oi->contentp = xmemdupz(co->buf, co->size);
2057                        oi->whence = OI_CACHED;
2058                        return 0;
2059                }
2060        }
2061
2062        if (!find_pack_entry(real, &e)) {
2063                /* Most likely it's a loose object. */
2064                if (!sha1_loose_object_info(real, oi, flags))
2065                        return 0;
2066
2067                /* Not a loose object; someone else may have just packed it. */
2068                if (flags & OBJECT_INFO_QUICK) {
2069                        return -1;
2070                } else {
2071                        reprepare_packed_git();
2072                        if (!find_pack_entry(real, &e))
2073                                return -1;
2074                }
2075        }
2076
2077        if (oi == &blank_oi)
2078                /*
2079                 * We know that the caller doesn't actually need the
2080                 * information below, so return early.
2081                 */
2082                return 0;
2083
2084        rtype = packed_object_info(e.p, e.offset, oi);
2085        if (rtype < 0) {
2086                mark_bad_packed_object(e.p, real);
2087                return sha1_object_info_extended(real, oi, 0);
2088        } else if (oi->whence == OI_PACKED) {
2089                oi->u.packed.offset = e.offset;
2090                oi->u.packed.pack = e.p;
2091                oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
2092                                         rtype == OBJ_OFS_DELTA);
2093        }
2094
2095        return 0;
2096}
2097
2098/* returns enum object_type or negative */
2099int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
2100{
2101        enum object_type type;
2102        struct object_info oi = OBJECT_INFO_INIT;
2103
2104        oi.typep = &type;
2105        oi.sizep = sizep;
2106        if (sha1_object_info_extended(sha1, &oi,
2107                                      OBJECT_INFO_LOOKUP_REPLACE) < 0)
2108                return -1;
2109        return type;
2110}
2111
2112int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2113                      unsigned char *sha1)
2114{
2115        struct cached_object *co;
2116
2117        hash_sha1_file(buf, len, typename(type), sha1);
2118        if (has_sha1_file(sha1) || find_cached_object(sha1))
2119                return 0;
2120        ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
2121        co = &cached_objects[cached_object_nr++];
2122        co->size = len;
2123        co->type = type;
2124        co->buf = xmalloc(len);
2125        memcpy(co->buf, buf, len);
2126        hashcpy(co->sha1, sha1);
2127        return 0;
2128}
2129
2130static void *read_object(const unsigned char *sha1, enum object_type *type,
2131                         unsigned long *size)
2132{
2133        struct object_info oi = OBJECT_INFO_INIT;
2134        void *content;
2135        oi.typep = type;
2136        oi.sizep = size;
2137        oi.contentp = &content;
2138
2139        if (sha1_object_info_extended(sha1, &oi, 0) < 0)
2140                return NULL;
2141        return content;
2142}
2143
2144/*
2145 * This function dies on corrupt objects; the callers who want to
2146 * deal with them should arrange to call read_object() and give error
2147 * messages themselves.
2148 */
2149void *read_sha1_file_extended(const unsigned char *sha1,
2150                              enum object_type *type,
2151                              unsigned long *size,
2152                              int lookup_replace)
2153{
2154        void *data;
2155        const struct packed_git *p;
2156        const char *path;
2157        struct stat st;
2158        const unsigned char *repl = lookup_replace ? lookup_replace_object(sha1)
2159                                                   : sha1;
2160
2161        errno = 0;
2162        data = read_object(repl, type, size);
2163        if (data)
2164                return data;
2165
2166        if (errno && errno != ENOENT)
2167                die_errno("failed to read object %s", sha1_to_hex(sha1));
2168
2169        /* die if we replaced an object with one that does not exist */
2170        if (repl != sha1)
2171                die("replacement %s not found for %s",
2172                    sha1_to_hex(repl), sha1_to_hex(sha1));
2173
2174        if (!stat_sha1_file(repl, &st, &path))
2175                die("loose object %s (stored in %s) is corrupt",
2176                    sha1_to_hex(repl), path);
2177
2178        if ((p = has_packed_and_bad(repl)) != NULL)
2179                die("packed object %s (stored in %s) is corrupt",
2180                    sha1_to_hex(repl), p->pack_name);
2181
2182        return NULL;
2183}
2184
2185void *read_object_with_reference(const unsigned char *sha1,
2186                                 const char *required_type_name,
2187                                 unsigned long *size,
2188                                 unsigned char *actual_sha1_return)
2189{
2190        enum object_type type, required_type;
2191        void *buffer;
2192        unsigned long isize;
2193        unsigned char actual_sha1[20];
2194
2195        required_type = type_from_string(required_type_name);
2196        hashcpy(actual_sha1, sha1);
2197        while (1) {
2198                int ref_length = -1;
2199                const char *ref_type = NULL;
2200
2201                buffer = read_sha1_file(actual_sha1, &type, &isize);
2202                if (!buffer)
2203                        return NULL;
2204                if (type == required_type) {
2205                        *size = isize;
2206                        if (actual_sha1_return)
2207                                hashcpy(actual_sha1_return, actual_sha1);
2208                        return buffer;
2209                }
2210                /* Handle references */
2211                else if (type == OBJ_COMMIT)
2212                        ref_type = "tree ";
2213                else if (type == OBJ_TAG)
2214                        ref_type = "object ";
2215                else {
2216                        free(buffer);
2217                        return NULL;
2218                }
2219                ref_length = strlen(ref_type);
2220
2221                if (ref_length + 40 > isize ||
2222                    memcmp(buffer, ref_type, ref_length) ||
2223                    get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2224                        free(buffer);
2225                        return NULL;
2226                }
2227                free(buffer);
2228                /* Now we have the ID of the referred-to object in
2229                 * actual_sha1.  Check again. */
2230        }
2231}
2232
2233static void write_sha1_file_prepare(const void *buf, unsigned long len,
2234                                    const char *type, unsigned char *sha1,
2235                                    char *hdr, int *hdrlen)
2236{
2237        git_SHA_CTX c;
2238
2239        /* Generate the header */
2240        *hdrlen = xsnprintf(hdr, *hdrlen, "%s %lu", type, len)+1;
2241
2242        /* Sha1.. */
2243        git_SHA1_Init(&c);
2244        git_SHA1_Update(&c, hdr, *hdrlen);
2245        git_SHA1_Update(&c, buf, len);
2246        git_SHA1_Final(sha1, &c);
2247}
2248
2249/*
2250 * Move the just written object into its final resting place.
2251 */
2252int finalize_object_file(const char *tmpfile, const char *filename)
2253{
2254        int ret = 0;
2255
2256        if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
2257                goto try_rename;
2258        else if (link(tmpfile, filename))
2259                ret = errno;
2260
2261        /*
2262         * Coda hack - coda doesn't like cross-directory links,
2263         * so we fall back to a rename, which will mean that it
2264         * won't be able to check collisions, but that's not a
2265         * big deal.
2266         *
2267         * The same holds for FAT formatted media.
2268         *
2269         * When this succeeds, we just return.  We have nothing
2270         * left to unlink.
2271         */
2272        if (ret && ret != EEXIST) {
2273        try_rename:
2274                if (!rename(tmpfile, filename))
2275                        goto out;
2276                ret = errno;
2277        }
2278        unlink_or_warn(tmpfile);
2279        if (ret) {
2280                if (ret != EEXIST) {
2281                        return error_errno("unable to write sha1 filename %s", filename);
2282                }
2283                /* FIXME!!! Collision check here ? */
2284        }
2285
2286out:
2287        if (adjust_shared_perm(filename))
2288                return error("unable to set permission to '%s'", filename);
2289        return 0;
2290}
2291
2292static int write_buffer(int fd, const void *buf, size_t len)
2293{
2294        if (write_in_full(fd, buf, len) < 0)
2295                return error_errno("file write error");
2296        return 0;
2297}
2298
2299int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2300                   unsigned char *sha1)
2301{
2302        char hdr[32];
2303        int hdrlen = sizeof(hdr);
2304        write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2305        return 0;
2306}
2307
2308/* Finalize a file on disk, and close it. */
2309static void close_sha1_file(int fd)
2310{
2311        if (fsync_object_files)
2312                fsync_or_die(fd, "sha1 file");
2313        if (close(fd) != 0)
2314                die_errno("error when closing sha1 file");
2315}
2316
2317/* Size of directory component, including the ending '/' */
2318static inline int directory_size(const char *filename)
2319{
2320        const char *s = strrchr(filename, '/');
2321        if (!s)
2322                return 0;
2323        return s - filename + 1;
2324}
2325
2326/*
2327 * This creates a temporary file in the same directory as the final
2328 * 'filename'
2329 *
2330 * We want to avoid cross-directory filename renames, because those
2331 * can have problems on various filesystems (FAT, NFS, Coda).
2332 */
2333static int create_tmpfile(struct strbuf *tmp, const char *filename)
2334{
2335        int fd, dirlen = directory_size(filename);
2336
2337        strbuf_reset(tmp);
2338        strbuf_add(tmp, filename, dirlen);
2339        strbuf_addstr(tmp, "tmp_obj_XXXXXX");
2340        fd = git_mkstemp_mode(tmp->buf, 0444);
2341        if (fd < 0 && dirlen && errno == ENOENT) {
2342                /*
2343                 * Make sure the directory exists; note that the contents
2344                 * of the buffer are undefined after mkstemp returns an
2345                 * error, so we have to rewrite the whole buffer from
2346                 * scratch.
2347                 */
2348                strbuf_reset(tmp);
2349                strbuf_add(tmp, filename, dirlen - 1);
2350                if (mkdir(tmp->buf, 0777) && errno != EEXIST)
2351                        return -1;
2352                if (adjust_shared_perm(tmp->buf))
2353                        return -1;
2354
2355                /* Try again */
2356                strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
2357                fd = git_mkstemp_mode(tmp->buf, 0444);
2358        }
2359        return fd;
2360}
2361
2362static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
2363                              const void *buf, unsigned long len, time_t mtime)
2364{
2365        int fd, ret;
2366        unsigned char compressed[4096];
2367        git_zstream stream;
2368        git_SHA_CTX c;
2369        unsigned char parano_sha1[20];
2370        static struct strbuf tmp_file = STRBUF_INIT;
2371        const char *filename = sha1_file_name(sha1);
2372
2373        fd = create_tmpfile(&tmp_file, filename);
2374        if (fd < 0) {
2375                if (errno == EACCES)
2376                        return error("insufficient permission for adding an object to repository database %s", get_object_directory());
2377                else
2378                        return error_errno("unable to create temporary file");
2379        }
2380
2381        /* Set it up */
2382        git_deflate_init(&stream, zlib_compression_level);
2383        stream.next_out = compressed;
2384        stream.avail_out = sizeof(compressed);
2385        git_SHA1_Init(&c);
2386
2387        /* First header.. */
2388        stream.next_in = (unsigned char *)hdr;
2389        stream.avail_in = hdrlen;
2390        while (git_deflate(&stream, 0) == Z_OK)
2391                ; /* nothing */
2392        git_SHA1_Update(&c, hdr, hdrlen);
2393
2394        /* Then the data itself.. */
2395        stream.next_in = (void *)buf;
2396        stream.avail_in = len;
2397        do {
2398                unsigned char *in0 = stream.next_in;
2399                ret = git_deflate(&stream, Z_FINISH);
2400                git_SHA1_Update(&c, in0, stream.next_in - in0);
2401                if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
2402                        die("unable to write sha1 file");
2403                stream.next_out = compressed;
2404                stream.avail_out = sizeof(compressed);
2405        } while (ret == Z_OK);
2406
2407        if (ret != Z_STREAM_END)
2408                die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2409        ret = git_deflate_end_gently(&stream);
2410        if (ret != Z_OK)
2411                die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2412        git_SHA1_Final(parano_sha1, &c);
2413        if (hashcmp(sha1, parano_sha1) != 0)
2414                die("confused by unstable object source data for %s", sha1_to_hex(sha1));
2415
2416        close_sha1_file(fd);
2417
2418        if (mtime) {
2419                struct utimbuf utb;
2420                utb.actime = mtime;
2421                utb.modtime = mtime;
2422                if (utime(tmp_file.buf, &utb) < 0)
2423                        warning_errno("failed utime() on %s", tmp_file.buf);
2424        }
2425
2426        return finalize_object_file(tmp_file.buf, filename);
2427}
2428
2429static int freshen_loose_object(const unsigned char *sha1)
2430{
2431        return check_and_freshen(sha1, 1);
2432}
2433
2434static int freshen_packed_object(const unsigned char *sha1)
2435{
2436        struct pack_entry e;
2437        if (!find_pack_entry(sha1, &e))
2438                return 0;
2439        if (e.p->freshened)
2440                return 1;
2441        if (!freshen_file(e.p->pack_name))
2442                return 0;
2443        e.p->freshened = 1;
2444        return 1;
2445}
2446
2447int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *sha1)
2448{
2449        char hdr[32];
2450        int hdrlen = sizeof(hdr);
2451
2452        /* Normally if we have it in the pack then we do not bother writing
2453         * it out into .git/objects/??/?{38} file.
2454         */
2455        write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2456        if (freshen_packed_object(sha1) || freshen_loose_object(sha1))
2457                return 0;
2458        return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
2459}
2460
2461int hash_sha1_file_literally(const void *buf, unsigned long len, const char *type,
2462                             unsigned char *sha1, unsigned flags)
2463{
2464        char *header;
2465        int hdrlen, status = 0;
2466
2467        /* type string, SP, %lu of the length plus NUL must fit this */
2468        hdrlen = strlen(type) + 32;
2469        header = xmalloc(hdrlen);
2470        write_sha1_file_prepare(buf, len, type, sha1, header, &hdrlen);
2471
2472        if (!(flags & HASH_WRITE_OBJECT))
2473                goto cleanup;
2474        if (freshen_packed_object(sha1) || freshen_loose_object(sha1))
2475                goto cleanup;
2476        status = write_loose_object(sha1, header, hdrlen, buf, len, 0);
2477
2478cleanup:
2479        free(header);
2480        return status;
2481}
2482
2483int force_object_loose(const unsigned char *sha1, time_t mtime)
2484{
2485        void *buf;
2486        unsigned long len;
2487        enum object_type type;
2488        char hdr[32];
2489        int hdrlen;
2490        int ret;
2491
2492        if (has_loose_object(sha1))
2493                return 0;
2494        buf = read_object(sha1, &type, &len);
2495        if (!buf)
2496                return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2497        hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(type), len) + 1;
2498        ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
2499        free(buf);
2500
2501        return ret;
2502}
2503
2504int has_pack_index(const unsigned char *sha1)
2505{
2506        struct stat st;
2507        if (stat(sha1_pack_index_name(sha1), &st))
2508                return 0;
2509        return 1;
2510}
2511
2512int has_sha1_pack(const unsigned char *sha1)
2513{
2514        struct pack_entry e;
2515        return find_pack_entry(sha1, &e);
2516}
2517
2518int has_sha1_file_with_flags(const unsigned char *sha1, int flags)
2519{
2520        if (!startup_info->have_repository)
2521                return 0;
2522        return sha1_object_info_extended(sha1, NULL,
2523                                         flags | OBJECT_INFO_SKIP_CACHED) >= 0;
2524}
2525
2526int has_object_file(const struct object_id *oid)
2527{
2528        return has_sha1_file(oid->hash);
2529}
2530
2531int has_object_file_with_flags(const struct object_id *oid, int flags)
2532{
2533        return has_sha1_file_with_flags(oid->hash, flags);
2534}
2535
2536static void check_tree(const void *buf, size_t size)
2537{
2538        struct tree_desc desc;
2539        struct name_entry entry;
2540
2541        init_tree_desc(&desc, buf, size);
2542        while (tree_entry(&desc, &entry))
2543                /* do nothing
2544                 * tree_entry() will die() on malformed entries */
2545                ;
2546}
2547
2548static void check_commit(const void *buf, size_t size)
2549{
2550        struct commit c;
2551        memset(&c, 0, sizeof(c));
2552        if (parse_commit_buffer(&c, buf, size))
2553                die("corrupt commit");
2554}
2555
2556static void check_tag(const void *buf, size_t size)
2557{
2558        struct tag t;
2559        memset(&t, 0, sizeof(t));
2560        if (parse_tag_buffer(&t, buf, size))
2561                die("corrupt tag");
2562}
2563
2564static int index_mem(unsigned char *sha1, void *buf, size_t size,
2565                     enum object_type type,
2566                     const char *path, unsigned flags)
2567{
2568        int ret, re_allocated = 0;
2569        int write_object = flags & HASH_WRITE_OBJECT;
2570
2571        if (!type)
2572                type = OBJ_BLOB;
2573
2574        /*
2575         * Convert blobs to git internal format
2576         */
2577        if ((type == OBJ_BLOB) && path) {
2578                struct strbuf nbuf = STRBUF_INIT;
2579                if (convert_to_git(&the_index, path, buf, size, &nbuf,
2580                                   write_object ? safe_crlf : SAFE_CRLF_FALSE)) {
2581                        buf = strbuf_detach(&nbuf, &size);
2582                        re_allocated = 1;
2583                }
2584        }
2585        if (flags & HASH_FORMAT_CHECK) {
2586                if (type == OBJ_TREE)
2587                        check_tree(buf, size);
2588                if (type == OBJ_COMMIT)
2589                        check_commit(buf, size);
2590                if (type == OBJ_TAG)
2591                        check_tag(buf, size);
2592        }
2593
2594        if (write_object)
2595                ret = write_sha1_file(buf, size, typename(type), sha1);
2596        else
2597                ret = hash_sha1_file(buf, size, typename(type), sha1);
2598        if (re_allocated)
2599                free(buf);
2600        return ret;
2601}
2602
2603static int index_stream_convert_blob(unsigned char *sha1, int fd,
2604                                     const char *path, unsigned flags)
2605{
2606        int ret;
2607        const int write_object = flags & HASH_WRITE_OBJECT;
2608        struct strbuf sbuf = STRBUF_INIT;
2609
2610        assert(path);
2611        assert(would_convert_to_git_filter_fd(path));
2612
2613        convert_to_git_filter_fd(&the_index, path, fd, &sbuf,
2614                                 write_object ? safe_crlf : SAFE_CRLF_FALSE);
2615
2616        if (write_object)
2617                ret = write_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
2618                                      sha1);
2619        else
2620                ret = hash_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
2621                                     sha1);
2622        strbuf_release(&sbuf);
2623        return ret;
2624}
2625
2626static int index_pipe(unsigned char *sha1, int fd, enum object_type type,
2627                      const char *path, unsigned flags)
2628{
2629        struct strbuf sbuf = STRBUF_INIT;
2630        int ret;
2631
2632        if (strbuf_read(&sbuf, fd, 4096) >= 0)
2633                ret = index_mem(sha1, sbuf.buf, sbuf.len, type, path, flags);
2634        else
2635                ret = -1;
2636        strbuf_release(&sbuf);
2637        return ret;
2638}
2639
2640#define SMALL_FILE_SIZE (32*1024)
2641
2642static int index_core(unsigned char *sha1, int fd, size_t size,
2643                      enum object_type type, const char *path,
2644                      unsigned flags)
2645{
2646        int ret;
2647
2648        if (!size) {
2649                ret = index_mem(sha1, "", size, type, path, flags);
2650        } else if (size <= SMALL_FILE_SIZE) {
2651                char *buf = xmalloc(size);
2652                if (size == read_in_full(fd, buf, size))
2653                        ret = index_mem(sha1, buf, size, type, path, flags);
2654                else
2655                        ret = error_errno("short read");
2656                free(buf);
2657        } else {
2658                void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2659                ret = index_mem(sha1, buf, size, type, path, flags);
2660                munmap(buf, size);
2661        }
2662        return ret;
2663}
2664
2665/*
2666 * This creates one packfile per large blob unless bulk-checkin
2667 * machinery is "plugged".
2668 *
2669 * This also bypasses the usual "convert-to-git" dance, and that is on
2670 * purpose. We could write a streaming version of the converting
2671 * functions and insert that before feeding the data to fast-import
2672 * (or equivalent in-core API described above). However, that is
2673 * somewhat complicated, as we do not know the size of the filter
2674 * result, which we need to know beforehand when writing a git object.
2675 * Since the primary motivation for trying to stream from the working
2676 * tree file and to avoid mmaping it in core is to deal with large
2677 * binary blobs, they generally do not want to get any conversion, and
2678 * callers should avoid this code path when filters are requested.
2679 */
2680static int index_stream(unsigned char *sha1, int fd, size_t size,
2681                        enum object_type type, const char *path,
2682                        unsigned flags)
2683{
2684        return index_bulk_checkin(sha1, fd, size, type, path, flags);
2685}
2686
2687int index_fd(unsigned char *sha1, int fd, struct stat *st,
2688             enum object_type type, const char *path, unsigned flags)
2689{
2690        int ret;
2691
2692        /*
2693         * Call xsize_t() only when needed to avoid potentially unnecessary
2694         * die() for large files.
2695         */
2696        if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(path))
2697                ret = index_stream_convert_blob(sha1, fd, path, flags);
2698        else if (!S_ISREG(st->st_mode))
2699                ret = index_pipe(sha1, fd, type, path, flags);
2700        else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
2701                 (path && would_convert_to_git(&the_index, path)))
2702                ret = index_core(sha1, fd, xsize_t(st->st_size), type, path,
2703                                 flags);
2704        else
2705                ret = index_stream(sha1, fd, xsize_t(st->st_size), type, path,
2706                                   flags);
2707        close(fd);
2708        return ret;
2709}
2710
2711int index_path(unsigned char *sha1, const char *path, struct stat *st, unsigned flags)
2712{
2713        int fd;
2714        struct strbuf sb = STRBUF_INIT;
2715
2716        switch (st->st_mode & S_IFMT) {
2717        case S_IFREG:
2718                fd = open(path, O_RDONLY);
2719                if (fd < 0)
2720                        return error_errno("open(\"%s\")", path);
2721                if (index_fd(sha1, fd, st, OBJ_BLOB, path, flags) < 0)
2722                        return error("%s: failed to insert into database",
2723                                     path);
2724                break;
2725        case S_IFLNK:
2726                if (strbuf_readlink(&sb, path, st->st_size))
2727                        return error_errno("readlink(\"%s\")", path);
2728                if (!(flags & HASH_WRITE_OBJECT))
2729                        hash_sha1_file(sb.buf, sb.len, blob_type, sha1);
2730                else if (write_sha1_file(sb.buf, sb.len, blob_type, sha1))
2731                        return error("%s: failed to insert into database",
2732                                     path);
2733                strbuf_release(&sb);
2734                break;
2735        case S_IFDIR:
2736                return resolve_gitlink_ref(path, "HEAD", sha1);
2737        default:
2738                return error("%s: unsupported file type", path);
2739        }
2740        return 0;
2741}
2742
2743int read_pack_header(int fd, struct pack_header *header)
2744{
2745        if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
2746                /* "eof before pack header was fully read" */
2747                return PH_ERROR_EOF;
2748
2749        if (header->hdr_signature != htonl(PACK_SIGNATURE))
2750                /* "protocol error (pack signature mismatch detected)" */
2751                return PH_ERROR_PACK_SIGNATURE;
2752        if (!pack_version_ok(header->hdr_version))
2753                /* "protocol error (pack version unsupported)" */
2754                return PH_ERROR_PROTOCOL;
2755        return 0;
2756}
2757
2758void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
2759{
2760        enum object_type type = sha1_object_info(sha1, NULL);
2761        if (type < 0)
2762                die("%s is not a valid object", sha1_to_hex(sha1));
2763        if (type != expect)
2764                die("%s is not a valid '%s' object", sha1_to_hex(sha1),
2765                    typename(expect));
2766}
2767
2768int for_each_file_in_obj_subdir(unsigned int subdir_nr,
2769                                struct strbuf *path,
2770                                each_loose_object_fn obj_cb,
2771                                each_loose_cruft_fn cruft_cb,
2772                                each_loose_subdir_fn subdir_cb,
2773                                void *data)
2774{
2775        size_t origlen, baselen;
2776        DIR *dir;
2777        struct dirent *de;
2778        int r = 0;
2779
2780        if (subdir_nr > 0xff)
2781                BUG("invalid loose object subdirectory: %x", subdir_nr);
2782
2783        origlen = path->len;
2784        strbuf_complete(path, '/');
2785        strbuf_addf(path, "%02x", subdir_nr);
2786        baselen = path->len;
2787
2788        dir = opendir(path->buf);
2789        if (!dir) {
2790                if (errno != ENOENT)
2791                        r = error_errno("unable to open %s", path->buf);
2792                strbuf_setlen(path, origlen);
2793                return r;
2794        }
2795
2796        while ((de = readdir(dir))) {
2797                if (is_dot_or_dotdot(de->d_name))
2798                        continue;
2799
2800                strbuf_setlen(path, baselen);
2801                strbuf_addf(path, "/%s", de->d_name);
2802
2803                if (strlen(de->d_name) == GIT_SHA1_HEXSZ - 2)  {
2804                        char hex[GIT_MAX_HEXSZ+1];
2805                        struct object_id oid;
2806
2807                        xsnprintf(hex, sizeof(hex), "%02x%s",
2808                                  subdir_nr, de->d_name);
2809                        if (!get_oid_hex(hex, &oid)) {
2810                                if (obj_cb) {
2811                                        r = obj_cb(&oid, path->buf, data);
2812                                        if (r)
2813                                                break;
2814                                }
2815                                continue;
2816                        }
2817                }
2818
2819                if (cruft_cb) {
2820                        r = cruft_cb(de->d_name, path->buf, data);
2821                        if (r)
2822                                break;
2823                }
2824        }
2825        closedir(dir);
2826
2827        strbuf_setlen(path, baselen);
2828        if (!r && subdir_cb)
2829                r = subdir_cb(subdir_nr, path->buf, data);
2830
2831        strbuf_setlen(path, origlen);
2832
2833        return r;
2834}
2835
2836int for_each_loose_file_in_objdir_buf(struct strbuf *path,
2837                            each_loose_object_fn obj_cb,
2838                            each_loose_cruft_fn cruft_cb,
2839                            each_loose_subdir_fn subdir_cb,
2840                            void *data)
2841{
2842        int r = 0;
2843        int i;
2844
2845        for (i = 0; i < 256; i++) {
2846                r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
2847                                                subdir_cb, data);
2848                if (r)
2849                        break;
2850        }
2851
2852        return r;
2853}
2854
2855int for_each_loose_file_in_objdir(const char *path,
2856                                  each_loose_object_fn obj_cb,
2857                                  each_loose_cruft_fn cruft_cb,
2858                                  each_loose_subdir_fn subdir_cb,
2859                                  void *data)
2860{
2861        struct strbuf buf = STRBUF_INIT;
2862        int r;
2863
2864        strbuf_addstr(&buf, path);
2865        r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2866                                              subdir_cb, data);
2867        strbuf_release(&buf);
2868
2869        return r;
2870}
2871
2872struct loose_alt_odb_data {
2873        each_loose_object_fn *cb;
2874        void *data;
2875};
2876
2877static int loose_from_alt_odb(struct alternate_object_database *alt,
2878                              void *vdata)
2879{
2880        struct loose_alt_odb_data *data = vdata;
2881        struct strbuf buf = STRBUF_INIT;
2882        int r;
2883
2884        strbuf_addstr(&buf, alt->path);
2885        r = for_each_loose_file_in_objdir_buf(&buf,
2886                                              data->cb, NULL, NULL,
2887                                              data->data);
2888        strbuf_release(&buf);
2889        return r;
2890}
2891
2892int for_each_loose_object(each_loose_object_fn cb, void *data, unsigned flags)
2893{
2894        struct loose_alt_odb_data alt;
2895        int r;
2896
2897        r = for_each_loose_file_in_objdir(get_object_directory(),
2898                                          cb, NULL, NULL, data);
2899        if (r)
2900                return r;
2901
2902        if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2903                return 0;
2904
2905        alt.cb = cb;
2906        alt.data = data;
2907        return foreach_alt_odb(loose_from_alt_odb, &alt);
2908}
2909
2910static int for_each_object_in_pack(struct packed_git *p, each_packed_object_fn cb, void *data)
2911{
2912        uint32_t i;
2913        int r = 0;
2914
2915        for (i = 0; i < p->num_objects; i++) {
2916                struct object_id oid;
2917
2918                if (!nth_packed_object_oid(&oid, p, i))
2919                        return error("unable to get sha1 of object %u in %s",
2920                                     i, p->pack_name);
2921
2922                r = cb(&oid, p, i, data);
2923                if (r)
2924                        break;
2925        }
2926        return r;
2927}
2928
2929int for_each_packed_object(each_packed_object_fn cb, void *data, unsigned flags)
2930{
2931        struct packed_git *p;
2932        int r = 0;
2933        int pack_errors = 0;
2934
2935        prepare_packed_git();
2936        for (p = packed_git; p; p = p->next) {
2937                if ((flags & FOR_EACH_OBJECT_LOCAL_ONLY) && !p->pack_local)
2938                        continue;
2939                if (open_pack_index(p)) {
2940                        pack_errors = 1;
2941                        continue;
2942                }
2943                r = for_each_object_in_pack(p, cb, data);
2944                if (r)
2945                        break;
2946        }
2947        return r ? r : pack_errors;
2948}
2949
2950static int check_stream_sha1(git_zstream *stream,
2951                             const char *hdr,
2952                             unsigned long size,
2953                             const char *path,
2954                             const unsigned char *expected_sha1)
2955{
2956        git_SHA_CTX c;
2957        unsigned char real_sha1[GIT_MAX_RAWSZ];
2958        unsigned char buf[4096];
2959        unsigned long total_read;
2960        int status = Z_OK;
2961
2962        git_SHA1_Init(&c);
2963        git_SHA1_Update(&c, hdr, stream->total_out);
2964
2965        /*
2966         * We already read some bytes into hdr, but the ones up to the NUL
2967         * do not count against the object's content size.
2968         */
2969        total_read = stream->total_out - strlen(hdr) - 1;
2970
2971        /*
2972         * This size comparison must be "<=" to read the final zlib packets;
2973         * see the comment in unpack_sha1_rest for details.
2974         */
2975        while (total_read <= size &&
2976               (status == Z_OK || status == Z_BUF_ERROR)) {
2977                stream->next_out = buf;
2978                stream->avail_out = sizeof(buf);
2979                if (size - total_read < stream->avail_out)
2980                        stream->avail_out = size - total_read;
2981                status = git_inflate(stream, Z_FINISH);
2982                git_SHA1_Update(&c, buf, stream->next_out - buf);
2983                total_read += stream->next_out - buf;
2984        }
2985        git_inflate_end(stream);
2986
2987        if (status != Z_STREAM_END) {
2988                error("corrupt loose object '%s'", sha1_to_hex(expected_sha1));
2989                return -1;
2990        }
2991        if (stream->avail_in) {
2992                error("garbage at end of loose object '%s'",
2993                      sha1_to_hex(expected_sha1));
2994                return -1;
2995        }
2996
2997        git_SHA1_Final(real_sha1, &c);
2998        if (hashcmp(expected_sha1, real_sha1)) {
2999                error("sha1 mismatch for %s (expected %s)", path,
3000                      sha1_to_hex(expected_sha1));
3001                return -1;
3002        }
3003
3004        return 0;
3005}
3006
3007int read_loose_object(const char *path,
3008                      const unsigned char *expected_sha1,
3009                      enum object_type *type,
3010                      unsigned long *size,
3011                      void **contents)
3012{
3013        int ret = -1;
3014        void *map = NULL;
3015        unsigned long mapsize;
3016        git_zstream stream;
3017        char hdr[32];
3018
3019        *contents = NULL;
3020
3021        map = map_sha1_file_1(path, NULL, &mapsize);
3022        if (!map) {
3023                error_errno("unable to mmap %s", path);
3024                goto out;
3025        }
3026
3027        if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0) {
3028                error("unable to unpack header of %s", path);
3029                goto out;
3030        }
3031
3032        *type = parse_sha1_header(hdr, size);
3033        if (*type < 0) {
3034                error("unable to parse header of %s", path);
3035                git_inflate_end(&stream);
3036                goto out;
3037        }
3038
3039        if (*type == OBJ_BLOB) {
3040                if (check_stream_sha1(&stream, hdr, *size, path, expected_sha1) < 0)
3041                        goto out;
3042        } else {
3043                *contents = unpack_sha1_rest(&stream, hdr, *size, expected_sha1);
3044                if (!*contents) {
3045                        error("unable to unpack contents of %s", path);
3046                        git_inflate_end(&stream);
3047                        goto out;
3048                }
3049                if (check_sha1_signature(expected_sha1, *contents,
3050                                         *size, typename(*type))) {
3051                        error("sha1 mismatch for %s (expected %s)", path,
3052                              sha1_to_hex(expected_sha1));
3053                        free(*contents);
3054                        goto out;
3055                }
3056        }
3057
3058        ret = 0; /* everything checks out */
3059
3060out:
3061        if (map)
3062                munmap(map, mapsize);
3063        return ret;
3064}