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