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