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