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