sha1_file.con commit Update shell scripts to compute empty tree object ID (03a7f38)
   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 "repository.h"
  26#include "streaming.h"
  27#include "dir.h"
  28#include "list.h"
  29#include "mergesort.h"
  30#include "quote.h"
  31#include "packfile.h"
  32#include "fetch-object.h"
  33#include "object-store.h"
  34
  35/* The maximum size for an object header. */
  36#define MAX_HEADER_LEN 32
  37
  38
  39#define EMPTY_TREE_SHA1_BIN_LITERAL \
  40         "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60" \
  41         "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04"
  42
  43#define EMPTY_BLOB_SHA1_BIN_LITERAL \
  44        "\xe6\x9d\xe2\x9b\xb2\xd1\xd6\x43\x4b\x8b" \
  45        "\x29\xae\x77\x5a\xd8\xc2\xe4\x8c\x53\x91"
  46
  47const unsigned char null_sha1[GIT_MAX_RAWSZ];
  48const struct object_id null_oid;
  49static const struct object_id empty_tree_oid = {
  50        EMPTY_TREE_SHA1_BIN_LITERAL
  51};
  52static const struct object_id empty_blob_oid = {
  53        EMPTY_BLOB_SHA1_BIN_LITERAL
  54};
  55
  56static void git_hash_sha1_init(git_hash_ctx *ctx)
  57{
  58        git_SHA1_Init(&ctx->sha1);
  59}
  60
  61static void git_hash_sha1_update(git_hash_ctx *ctx, const void *data, size_t len)
  62{
  63        git_SHA1_Update(&ctx->sha1, data, len);
  64}
  65
  66static void git_hash_sha1_final(unsigned char *hash, git_hash_ctx *ctx)
  67{
  68        git_SHA1_Final(hash, &ctx->sha1);
  69}
  70
  71static void git_hash_unknown_init(git_hash_ctx *ctx)
  72{
  73        die("trying to init unknown hash");
  74}
  75
  76static void git_hash_unknown_update(git_hash_ctx *ctx, const void *data, size_t len)
  77{
  78        die("trying to update unknown hash");
  79}
  80
  81static void git_hash_unknown_final(unsigned char *hash, git_hash_ctx *ctx)
  82{
  83        die("trying to finalize unknown hash");
  84}
  85
  86const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
  87        {
  88                NULL,
  89                0x00000000,
  90                0,
  91                0,
  92                git_hash_unknown_init,
  93                git_hash_unknown_update,
  94                git_hash_unknown_final,
  95                NULL,
  96                NULL,
  97        },
  98        {
  99                "sha-1",
 100                /* "sha1", big-endian */
 101                0x73686131,
 102                GIT_SHA1_RAWSZ,
 103                GIT_SHA1_HEXSZ,
 104                git_hash_sha1_init,
 105                git_hash_sha1_update,
 106                git_hash_sha1_final,
 107                &empty_tree_oid,
 108                &empty_blob_oid,
 109        },
 110};
 111
 112const char *empty_tree_oid_hex(void)
 113{
 114        static char buf[GIT_MAX_HEXSZ + 1];
 115        return oid_to_hex_r(buf, the_hash_algo->empty_tree);
 116}
 117
 118const char *empty_blob_oid_hex(void)
 119{
 120        static char buf[GIT_MAX_HEXSZ + 1];
 121        return oid_to_hex_r(buf, the_hash_algo->empty_blob);
 122}
 123
 124/*
 125 * This is meant to hold a *small* number of objects that you would
 126 * want read_sha1_file() to be able to return, but yet you do not want
 127 * to write them into the object store (e.g. a browse-only
 128 * application).
 129 */
 130static struct cached_object {
 131        struct object_id oid;
 132        enum object_type type;
 133        void *buf;
 134        unsigned long size;
 135} *cached_objects;
 136static int cached_object_nr, cached_object_alloc;
 137
 138static struct cached_object empty_tree = {
 139        { EMPTY_TREE_SHA1_BIN_LITERAL },
 140        OBJ_TREE,
 141        "",
 142        0
 143};
 144
 145static struct cached_object *find_cached_object(const struct object_id *oid)
 146{
 147        int i;
 148        struct cached_object *co = cached_objects;
 149
 150        for (i = 0; i < cached_object_nr; i++, co++) {
 151                if (!oidcmp(&co->oid, oid))
 152                        return co;
 153        }
 154        if (!oidcmp(oid, the_hash_algo->empty_tree))
 155                return &empty_tree;
 156        return NULL;
 157}
 158
 159
 160static int get_conv_flags(unsigned flags)
 161{
 162        if (flags & HASH_RENORMALIZE)
 163                return CONV_EOL_RENORMALIZE;
 164        else if (flags & HASH_WRITE_OBJECT)
 165          return global_conv_flags_eol;
 166        else
 167                return 0;
 168}
 169
 170
 171int mkdir_in_gitdir(const char *path)
 172{
 173        if (mkdir(path, 0777)) {
 174                int saved_errno = errno;
 175                struct stat st;
 176                struct strbuf sb = STRBUF_INIT;
 177
 178                if (errno != EEXIST)
 179                        return -1;
 180                /*
 181                 * Are we looking at a path in a symlinked worktree
 182                 * whose original repository does not yet have it?
 183                 * e.g. .git/rr-cache pointing at its original
 184                 * repository in which the user hasn't performed any
 185                 * conflict resolution yet?
 186                 */
 187                if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
 188                    strbuf_readlink(&sb, path, st.st_size) ||
 189                    !is_absolute_path(sb.buf) ||
 190                    mkdir(sb.buf, 0777)) {
 191                        strbuf_release(&sb);
 192                        errno = saved_errno;
 193                        return -1;
 194                }
 195                strbuf_release(&sb);
 196        }
 197        return adjust_shared_perm(path);
 198}
 199
 200enum scld_error safe_create_leading_directories(char *path)
 201{
 202        char *next_component = path + offset_1st_component(path);
 203        enum scld_error ret = SCLD_OK;
 204
 205        while (ret == SCLD_OK && next_component) {
 206                struct stat st;
 207                char *slash = next_component, slash_character;
 208
 209                while (*slash && !is_dir_sep(*slash))
 210                        slash++;
 211
 212                if (!*slash)
 213                        break;
 214
 215                next_component = slash + 1;
 216                while (is_dir_sep(*next_component))
 217                        next_component++;
 218                if (!*next_component)
 219                        break;
 220
 221                slash_character = *slash;
 222                *slash = '\0';
 223                if (!stat(path, &st)) {
 224                        /* path exists */
 225                        if (!S_ISDIR(st.st_mode)) {
 226                                errno = ENOTDIR;
 227                                ret = SCLD_EXISTS;
 228                        }
 229                } else if (mkdir(path, 0777)) {
 230                        if (errno == EEXIST &&
 231                            !stat(path, &st) && S_ISDIR(st.st_mode))
 232                                ; /* somebody created it since we checked */
 233                        else if (errno == ENOENT)
 234                                /*
 235                                 * Either mkdir() failed because
 236                                 * somebody just pruned the containing
 237                                 * directory, or stat() failed because
 238                                 * the file that was in our way was
 239                                 * just removed.  Either way, inform
 240                                 * the caller that it might be worth
 241                                 * trying again:
 242                                 */
 243                                ret = SCLD_VANISHED;
 244                        else
 245                                ret = SCLD_FAILED;
 246                } else if (adjust_shared_perm(path)) {
 247                        ret = SCLD_PERMS;
 248                }
 249                *slash = slash_character;
 250        }
 251        return ret;
 252}
 253
 254enum scld_error safe_create_leading_directories_const(const char *path)
 255{
 256        int save_errno;
 257        /* path points to cache entries, so xstrdup before messing with it */
 258        char *buf = xstrdup(path);
 259        enum scld_error result = safe_create_leading_directories(buf);
 260
 261        save_errno = errno;
 262        free(buf);
 263        errno = save_errno;
 264        return result;
 265}
 266
 267int raceproof_create_file(const char *path, create_file_fn fn, void *cb)
 268{
 269        /*
 270         * The number of times we will try to remove empty directories
 271         * in the way of path. This is only 1 because if another
 272         * process is racily creating directories that conflict with
 273         * us, we don't want to fight against them.
 274         */
 275        int remove_directories_remaining = 1;
 276
 277        /*
 278         * The number of times that we will try to create the
 279         * directories containing path. We are willing to attempt this
 280         * more than once, because another process could be trying to
 281         * clean up empty directories at the same time as we are
 282         * trying to create them.
 283         */
 284        int create_directories_remaining = 3;
 285
 286        /* A scratch copy of path, filled lazily if we need it: */
 287        struct strbuf path_copy = STRBUF_INIT;
 288
 289        int ret, save_errno;
 290
 291        /* Sanity check: */
 292        assert(*path);
 293
 294retry_fn:
 295        ret = fn(path, cb);
 296        save_errno = errno;
 297        if (!ret)
 298                goto out;
 299
 300        if (errno == EISDIR && remove_directories_remaining-- > 0) {
 301                /*
 302                 * A directory is in the way. Maybe it is empty; try
 303                 * to remove it:
 304                 */
 305                if (!path_copy.len)
 306                        strbuf_addstr(&path_copy, path);
 307
 308                if (!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY))
 309                        goto retry_fn;
 310        } else if (errno == ENOENT && create_directories_remaining-- > 0) {
 311                /*
 312                 * Maybe the containing directory didn't exist, or
 313                 * maybe it was just deleted by a process that is
 314                 * racing with us to clean up empty directories. Try
 315                 * to create it:
 316                 */
 317                enum scld_error scld_result;
 318
 319                if (!path_copy.len)
 320                        strbuf_addstr(&path_copy, path);
 321
 322                do {
 323                        scld_result = safe_create_leading_directories(path_copy.buf);
 324                        if (scld_result == SCLD_OK)
 325                                goto retry_fn;
 326                } while (scld_result == SCLD_VANISHED && create_directories_remaining-- > 0);
 327        }
 328
 329out:
 330        strbuf_release(&path_copy);
 331        errno = save_errno;
 332        return ret;
 333}
 334
 335static void fill_sha1_path(struct strbuf *buf, const unsigned char *sha1)
 336{
 337        int i;
 338        for (i = 0; i < 20; i++) {
 339                static char hex[] = "0123456789abcdef";
 340                unsigned int val = sha1[i];
 341                strbuf_addch(buf, hex[val >> 4]);
 342                strbuf_addch(buf, hex[val & 0xf]);
 343                if (!i)
 344                        strbuf_addch(buf, '/');
 345        }
 346}
 347
 348void sha1_file_name(struct repository *r, struct strbuf *buf, const unsigned char *sha1)
 349{
 350        strbuf_addstr(buf, r->objects->objectdir);
 351        strbuf_addch(buf, '/');
 352        fill_sha1_path(buf, sha1);
 353}
 354
 355struct strbuf *alt_scratch_buf(struct alternate_object_database *alt)
 356{
 357        strbuf_setlen(&alt->scratch, alt->base_len);
 358        return &alt->scratch;
 359}
 360
 361static const char *alt_sha1_path(struct alternate_object_database *alt,
 362                                 const unsigned char *sha1)
 363{
 364        struct strbuf *buf = alt_scratch_buf(alt);
 365        fill_sha1_path(buf, sha1);
 366        return buf->buf;
 367}
 368
 369/*
 370 * Return non-zero iff the path is usable as an alternate object database.
 371 */
 372static int alt_odb_usable(struct raw_object_store *o,
 373                          struct strbuf *path,
 374                          const char *normalized_objdir)
 375{
 376        struct alternate_object_database *alt;
 377
 378        /* Detect cases where alternate disappeared */
 379        if (!is_directory(path->buf)) {
 380                error("object directory %s does not exist; "
 381                      "check .git/objects/info/alternates.",
 382                      path->buf);
 383                return 0;
 384        }
 385
 386        /*
 387         * Prevent the common mistake of listing the same
 388         * thing twice, or object directory itself.
 389         */
 390        for (alt = o->alt_odb_list; alt; alt = alt->next) {
 391                if (!fspathcmp(path->buf, alt->path))
 392                        return 0;
 393        }
 394        if (!fspathcmp(path->buf, normalized_objdir))
 395                return 0;
 396
 397        return 1;
 398}
 399
 400/*
 401 * Prepare alternate object database registry.
 402 *
 403 * The variable alt_odb_list points at the list of struct
 404 * alternate_object_database.  The elements on this list come from
 405 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
 406 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
 407 * whose contents is similar to that environment variable but can be
 408 * LF separated.  Its base points at a statically allocated buffer that
 409 * contains "/the/directory/corresponding/to/.git/objects/...", while
 410 * its name points just after the slash at the end of ".git/objects/"
 411 * in the example above, and has enough space to hold 40-byte hex
 412 * SHA1, an extra slash for the first level indirection, and the
 413 * terminating NUL.
 414 */
 415static void read_info_alternates(struct repository *r,
 416                                 const char *relative_base,
 417                                 int depth);
 418static int link_alt_odb_entry(struct repository *r, const char *entry,
 419        const char *relative_base, int depth, const char *normalized_objdir)
 420{
 421        struct alternate_object_database *ent;
 422        struct strbuf pathbuf = STRBUF_INIT;
 423
 424        if (!is_absolute_path(entry) && relative_base) {
 425                strbuf_realpath(&pathbuf, relative_base, 1);
 426                strbuf_addch(&pathbuf, '/');
 427        }
 428        strbuf_addstr(&pathbuf, entry);
 429
 430        if (strbuf_normalize_path(&pathbuf) < 0 && relative_base) {
 431                error("unable to normalize alternate object path: %s",
 432                      pathbuf.buf);
 433                strbuf_release(&pathbuf);
 434                return -1;
 435        }
 436
 437        /*
 438         * The trailing slash after the directory name is given by
 439         * this function at the end. Remove duplicates.
 440         */
 441        while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
 442                strbuf_setlen(&pathbuf, pathbuf.len - 1);
 443
 444        if (!alt_odb_usable(r->objects, &pathbuf, normalized_objdir)) {
 445                strbuf_release(&pathbuf);
 446                return -1;
 447        }
 448
 449        ent = alloc_alt_odb(pathbuf.buf);
 450
 451        /* add the alternate entry */
 452        *r->objects->alt_odb_tail = ent;
 453        r->objects->alt_odb_tail = &(ent->next);
 454        ent->next = NULL;
 455
 456        /* recursively add alternates */
 457        read_info_alternates(r, pathbuf.buf, depth + 1);
 458
 459        strbuf_release(&pathbuf);
 460        return 0;
 461}
 462
 463static const char *parse_alt_odb_entry(const char *string,
 464                                       int sep,
 465                                       struct strbuf *out)
 466{
 467        const char *end;
 468
 469        strbuf_reset(out);
 470
 471        if (*string == '#') {
 472                /* comment; consume up to next separator */
 473                end = strchrnul(string, sep);
 474        } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
 475                /*
 476                 * quoted path; unquote_c_style has copied the
 477                 * data for us and set "end". Broken quoting (e.g.,
 478                 * an entry that doesn't end with a quote) falls
 479                 * back to the unquoted case below.
 480                 */
 481        } else {
 482                /* normal, unquoted path */
 483                end = strchrnul(string, sep);
 484                strbuf_add(out, string, end - string);
 485        }
 486
 487        if (*end)
 488                end++;
 489        return end;
 490}
 491
 492static void link_alt_odb_entries(struct repository *r, const char *alt,
 493                                 int sep, const char *relative_base, int depth)
 494{
 495        struct strbuf objdirbuf = STRBUF_INIT;
 496        struct strbuf entry = STRBUF_INIT;
 497
 498        if (!alt || !*alt)
 499                return;
 500
 501        if (depth > 5) {
 502                error("%s: ignoring alternate object stores, nesting too deep.",
 503                                relative_base);
 504                return;
 505        }
 506
 507        strbuf_add_absolute_path(&objdirbuf, r->objects->objectdir);
 508        if (strbuf_normalize_path(&objdirbuf) < 0)
 509                die("unable to normalize object directory: %s",
 510                    objdirbuf.buf);
 511
 512        while (*alt) {
 513                alt = parse_alt_odb_entry(alt, sep, &entry);
 514                if (!entry.len)
 515                        continue;
 516                link_alt_odb_entry(r, entry.buf,
 517                                   relative_base, depth, objdirbuf.buf);
 518        }
 519        strbuf_release(&entry);
 520        strbuf_release(&objdirbuf);
 521}
 522
 523static void read_info_alternates(struct repository *r,
 524                                 const char *relative_base,
 525                                 int depth)
 526{
 527        char *path;
 528        struct strbuf buf = STRBUF_INIT;
 529
 530        path = xstrfmt("%s/info/alternates", relative_base);
 531        if (strbuf_read_file(&buf, path, 1024) < 0) {
 532                warn_on_fopen_errors(path);
 533                free(path);
 534                return;
 535        }
 536
 537        link_alt_odb_entries(r, buf.buf, '\n', relative_base, depth);
 538        strbuf_release(&buf);
 539        free(path);
 540}
 541
 542struct alternate_object_database *alloc_alt_odb(const char *dir)
 543{
 544        struct alternate_object_database *ent;
 545
 546        FLEX_ALLOC_STR(ent, path, dir);
 547        strbuf_init(&ent->scratch, 0);
 548        strbuf_addf(&ent->scratch, "%s/", dir);
 549        ent->base_len = ent->scratch.len;
 550
 551        return ent;
 552}
 553
 554void add_to_alternates_file(const char *reference)
 555{
 556        struct lock_file lock = LOCK_INIT;
 557        char *alts = git_pathdup("objects/info/alternates");
 558        FILE *in, *out;
 559        int found = 0;
 560
 561        hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
 562        out = fdopen_lock_file(&lock, "w");
 563        if (!out)
 564                die_errno("unable to fdopen alternates lockfile");
 565
 566        in = fopen(alts, "r");
 567        if (in) {
 568                struct strbuf line = STRBUF_INIT;
 569
 570                while (strbuf_getline(&line, in) != EOF) {
 571                        if (!strcmp(reference, line.buf)) {
 572                                found = 1;
 573                                break;
 574                        }
 575                        fprintf_or_die(out, "%s\n", line.buf);
 576                }
 577
 578                strbuf_release(&line);
 579                fclose(in);
 580        }
 581        else if (errno != ENOENT)
 582                die_errno("unable to read alternates file");
 583
 584        if (found) {
 585                rollback_lock_file(&lock);
 586        } else {
 587                fprintf_or_die(out, "%s\n", reference);
 588                if (commit_lock_file(&lock))
 589                        die_errno("unable to move new alternates file into place");
 590                if (the_repository->objects->alt_odb_tail)
 591                        link_alt_odb_entries(the_repository, reference,
 592                                             '\n', NULL, 0);
 593        }
 594        free(alts);
 595}
 596
 597void add_to_alternates_memory(const char *reference)
 598{
 599        /*
 600         * Make sure alternates are initialized, or else our entry may be
 601         * overwritten when they are.
 602         */
 603        prepare_alt_odb(the_repository);
 604
 605        link_alt_odb_entries(the_repository, reference,
 606                             '\n', NULL, 0);
 607}
 608
 609/*
 610 * Compute the exact path an alternate is at and returns it. In case of
 611 * error NULL is returned and the human readable error is added to `err`
 612 * `path` may be relative and should point to $GITDIR.
 613 * `err` must not be null.
 614 */
 615char *compute_alternate_path(const char *path, struct strbuf *err)
 616{
 617        char *ref_git = NULL;
 618        const char *repo, *ref_git_s;
 619        int seen_error = 0;
 620
 621        ref_git_s = real_path_if_valid(path);
 622        if (!ref_git_s) {
 623                seen_error = 1;
 624                strbuf_addf(err, _("path '%s' does not exist"), path);
 625                goto out;
 626        } else
 627                /*
 628                 * Beware: read_gitfile(), real_path() and mkpath()
 629                 * return static buffer
 630                 */
 631                ref_git = xstrdup(ref_git_s);
 632
 633        repo = read_gitfile(ref_git);
 634        if (!repo)
 635                repo = read_gitfile(mkpath("%s/.git", ref_git));
 636        if (repo) {
 637                free(ref_git);
 638                ref_git = xstrdup(repo);
 639        }
 640
 641        if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
 642                char *ref_git_git = mkpathdup("%s/.git", ref_git);
 643                free(ref_git);
 644                ref_git = ref_git_git;
 645        } else if (!is_directory(mkpath("%s/objects", ref_git))) {
 646                struct strbuf sb = STRBUF_INIT;
 647                seen_error = 1;
 648                if (get_common_dir(&sb, ref_git)) {
 649                        strbuf_addf(err,
 650                                    _("reference repository '%s' as a linked "
 651                                      "checkout is not supported yet."),
 652                                    path);
 653                        goto out;
 654                }
 655
 656                strbuf_addf(err, _("reference repository '%s' is not a "
 657                                        "local repository."), path);
 658                goto out;
 659        }
 660
 661        if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
 662                strbuf_addf(err, _("reference repository '%s' is shallow"),
 663                            path);
 664                seen_error = 1;
 665                goto out;
 666        }
 667
 668        if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
 669                strbuf_addf(err,
 670                            _("reference repository '%s' is grafted"),
 671                            path);
 672                seen_error = 1;
 673                goto out;
 674        }
 675
 676out:
 677        if (seen_error) {
 678                FREE_AND_NULL(ref_git);
 679        }
 680
 681        return ref_git;
 682}
 683
 684int foreach_alt_odb(alt_odb_fn fn, void *cb)
 685{
 686        struct alternate_object_database *ent;
 687        int r = 0;
 688
 689        prepare_alt_odb(the_repository);
 690        for (ent = the_repository->objects->alt_odb_list; ent; ent = ent->next) {
 691                r = fn(ent, cb);
 692                if (r)
 693                        break;
 694        }
 695        return r;
 696}
 697
 698void prepare_alt_odb(struct repository *r)
 699{
 700        if (r->objects->alt_odb_tail)
 701                return;
 702
 703        r->objects->alt_odb_tail = &r->objects->alt_odb_list;
 704        link_alt_odb_entries(r, r->objects->alternate_db, PATH_SEP, NULL, 0);
 705
 706        read_info_alternates(r, r->objects->objectdir, 0);
 707}
 708
 709/* Returns 1 if we have successfully freshened the file, 0 otherwise. */
 710static int freshen_file(const char *fn)
 711{
 712        struct utimbuf t;
 713        t.actime = t.modtime = time(NULL);
 714        return !utime(fn, &t);
 715}
 716
 717/*
 718 * All of the check_and_freshen functions return 1 if the file exists and was
 719 * freshened (if freshening was requested), 0 otherwise. If they return
 720 * 0, you should not assume that it is safe to skip a write of the object (it
 721 * either does not exist on disk, or has a stale mtime and may be subject to
 722 * pruning).
 723 */
 724int check_and_freshen_file(const char *fn, int freshen)
 725{
 726        if (access(fn, F_OK))
 727                return 0;
 728        if (freshen && !freshen_file(fn))
 729                return 0;
 730        return 1;
 731}
 732
 733static int check_and_freshen_local(const struct object_id *oid, int freshen)
 734{
 735        static struct strbuf buf = STRBUF_INIT;
 736
 737        strbuf_reset(&buf);
 738        sha1_file_name(the_repository, &buf, oid->hash);
 739
 740        return check_and_freshen_file(buf.buf, freshen);
 741}
 742
 743static int check_and_freshen_nonlocal(const struct object_id *oid, int freshen)
 744{
 745        struct alternate_object_database *alt;
 746        prepare_alt_odb(the_repository);
 747        for (alt = the_repository->objects->alt_odb_list; alt; alt = alt->next) {
 748                const char *path = alt_sha1_path(alt, oid->hash);
 749                if (check_and_freshen_file(path, freshen))
 750                        return 1;
 751        }
 752        return 0;
 753}
 754
 755static int check_and_freshen(const struct object_id *oid, int freshen)
 756{
 757        return check_and_freshen_local(oid, freshen) ||
 758               check_and_freshen_nonlocal(oid, freshen);
 759}
 760
 761int has_loose_object_nonlocal(const struct object_id *oid)
 762{
 763        return check_and_freshen_nonlocal(oid, 0);
 764}
 765
 766static int has_loose_object(const struct object_id *oid)
 767{
 768        return check_and_freshen(oid, 0);
 769}
 770
 771static void mmap_limit_check(size_t length)
 772{
 773        static size_t limit = 0;
 774        if (!limit) {
 775                limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
 776                if (!limit)
 777                        limit = SIZE_MAX;
 778        }
 779        if (length > limit)
 780                die("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX,
 781                    (uintmax_t)length, (uintmax_t)limit);
 782}
 783
 784void *xmmap_gently(void *start, size_t length,
 785                  int prot, int flags, int fd, off_t offset)
 786{
 787        void *ret;
 788
 789        mmap_limit_check(length);
 790        ret = mmap(start, length, prot, flags, fd, offset);
 791        if (ret == MAP_FAILED) {
 792                if (!length)
 793                        return NULL;
 794                release_pack_memory(length);
 795                ret = mmap(start, length, prot, flags, fd, offset);
 796        }
 797        return ret;
 798}
 799
 800void *xmmap(void *start, size_t length,
 801        int prot, int flags, int fd, off_t offset)
 802{
 803        void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
 804        if (ret == MAP_FAILED)
 805                die_errno("mmap failed");
 806        return ret;
 807}
 808
 809/*
 810 * With an in-core object data in "map", rehash it to make sure the
 811 * object name actually matches "sha1" to detect object corruption.
 812 * With "map" == NULL, try reading the object named with "sha1" using
 813 * the streaming interface and rehash it to do the same.
 814 */
 815int check_object_signature(const struct object_id *oid, void *map,
 816                           unsigned long size, const char *type)
 817{
 818        struct object_id real_oid;
 819        enum object_type obj_type;
 820        struct git_istream *st;
 821        git_hash_ctx c;
 822        char hdr[MAX_HEADER_LEN];
 823        int hdrlen;
 824
 825        if (map) {
 826                hash_object_file(map, size, type, &real_oid);
 827                return oidcmp(oid, &real_oid) ? -1 : 0;
 828        }
 829
 830        st = open_istream(oid, &obj_type, &size, NULL);
 831        if (!st)
 832                return -1;
 833
 834        /* Generate the header */
 835        hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", type_name(obj_type), size) + 1;
 836
 837        /* Sha1.. */
 838        the_hash_algo->init_fn(&c);
 839        the_hash_algo->update_fn(&c, hdr, hdrlen);
 840        for (;;) {
 841                char buf[1024 * 16];
 842                ssize_t readlen = read_istream(st, buf, sizeof(buf));
 843
 844                if (readlen < 0) {
 845                        close_istream(st);
 846                        return -1;
 847                }
 848                if (!readlen)
 849                        break;
 850                the_hash_algo->update_fn(&c, buf, readlen);
 851        }
 852        the_hash_algo->final_fn(real_oid.hash, &c);
 853        close_istream(st);
 854        return oidcmp(oid, &real_oid) ? -1 : 0;
 855}
 856
 857int git_open_cloexec(const char *name, int flags)
 858{
 859        int fd;
 860        static int o_cloexec = O_CLOEXEC;
 861
 862        fd = open(name, flags | o_cloexec);
 863        if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
 864                /* Try again w/o O_CLOEXEC: the kernel might not support it */
 865                o_cloexec &= ~O_CLOEXEC;
 866                fd = open(name, flags | o_cloexec);
 867        }
 868
 869#if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
 870        {
 871                static int fd_cloexec = FD_CLOEXEC;
 872
 873                if (!o_cloexec && 0 <= fd && fd_cloexec) {
 874                        /* Opened w/o O_CLOEXEC?  try with fcntl(2) to add it */
 875                        int flags = fcntl(fd, F_GETFD);
 876                        if (fcntl(fd, F_SETFD, flags | fd_cloexec))
 877                                fd_cloexec = 0;
 878                }
 879        }
 880#endif
 881        return fd;
 882}
 883
 884/*
 885 * Find "sha1" as a loose object in the local repository or in an alternate.
 886 * Returns 0 on success, negative on failure.
 887 *
 888 * The "path" out-parameter will give the path of the object we found (if any).
 889 * Note that it may point to static storage and is only valid until another
 890 * call to sha1_file_name(), etc.
 891 */
 892static int stat_sha1_file(struct repository *r, const unsigned char *sha1,
 893                          struct stat *st, const char **path)
 894{
 895        struct alternate_object_database *alt;
 896        static struct strbuf buf = STRBUF_INIT;
 897
 898        strbuf_reset(&buf);
 899        sha1_file_name(r, &buf, sha1);
 900        *path = buf.buf;
 901
 902        if (!lstat(*path, st))
 903                return 0;
 904
 905        prepare_alt_odb(r);
 906        errno = ENOENT;
 907        for (alt = r->objects->alt_odb_list; alt; alt = alt->next) {
 908                *path = alt_sha1_path(alt, sha1);
 909                if (!lstat(*path, st))
 910                        return 0;
 911        }
 912
 913        return -1;
 914}
 915
 916/*
 917 * Like stat_sha1_file(), but actually open the object and return the
 918 * descriptor. See the caveats on the "path" parameter above.
 919 */
 920static int open_sha1_file(struct repository *r,
 921                          const unsigned char *sha1, const char **path)
 922{
 923        int fd;
 924        struct alternate_object_database *alt;
 925        int most_interesting_errno;
 926        static struct strbuf buf = STRBUF_INIT;
 927
 928        strbuf_reset(&buf);
 929        sha1_file_name(r, &buf, sha1);
 930        *path = buf.buf;
 931
 932        fd = git_open(*path);
 933        if (fd >= 0)
 934                return fd;
 935        most_interesting_errno = errno;
 936
 937        prepare_alt_odb(r);
 938        for (alt = r->objects->alt_odb_list; alt; alt = alt->next) {
 939                *path = alt_sha1_path(alt, sha1);
 940                fd = git_open(*path);
 941                if (fd >= 0)
 942                        return fd;
 943                if (most_interesting_errno == ENOENT)
 944                        most_interesting_errno = errno;
 945        }
 946        errno = most_interesting_errno;
 947        return -1;
 948}
 949
 950/*
 951 * Map the loose object at "path" if it is not NULL, or the path found by
 952 * searching for a loose object named "sha1".
 953 */
 954static void *map_sha1_file_1(struct repository *r, const char *path,
 955                             const unsigned char *sha1, unsigned long *size)
 956{
 957        void *map;
 958        int fd;
 959
 960        if (path)
 961                fd = git_open(path);
 962        else
 963                fd = open_sha1_file(r, sha1, &path);
 964        map = NULL;
 965        if (fd >= 0) {
 966                struct stat st;
 967
 968                if (!fstat(fd, &st)) {
 969                        *size = xsize_t(st.st_size);
 970                        if (!*size) {
 971                                /* mmap() is forbidden on empty files */
 972                                error("object file %s is empty", path);
 973                                return NULL;
 974                        }
 975                        map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
 976                }
 977                close(fd);
 978        }
 979        return map;
 980}
 981
 982void *map_sha1_file(struct repository *r,
 983                    const unsigned char *sha1, unsigned long *size)
 984{
 985        return map_sha1_file_1(r, NULL, sha1, size);
 986}
 987
 988static int unpack_sha1_short_header(git_zstream *stream,
 989                                    unsigned char *map, unsigned long mapsize,
 990                                    void *buffer, unsigned long bufsiz)
 991{
 992        /* Get the data stream */
 993        memset(stream, 0, sizeof(*stream));
 994        stream->next_in = map;
 995        stream->avail_in = mapsize;
 996        stream->next_out = buffer;
 997        stream->avail_out = bufsiz;
 998
 999        git_inflate_init(stream);
1000        return git_inflate(stream, 0);
1001}
1002
1003int unpack_sha1_header(git_zstream *stream,
1004                       unsigned char *map, unsigned long mapsize,
1005                       void *buffer, unsigned long bufsiz)
1006{
1007        int status = unpack_sha1_short_header(stream, map, mapsize,
1008                                              buffer, bufsiz);
1009
1010        if (status < Z_OK)
1011                return status;
1012
1013        /* Make sure we have the terminating NUL */
1014        if (!memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1015                return -1;
1016        return 0;
1017}
1018
1019static int unpack_sha1_header_to_strbuf(git_zstream *stream, unsigned char *map,
1020                                        unsigned long mapsize, void *buffer,
1021                                        unsigned long bufsiz, struct strbuf *header)
1022{
1023        int status;
1024
1025        status = unpack_sha1_short_header(stream, map, mapsize, buffer, bufsiz);
1026        if (status < Z_OK)
1027                return -1;
1028
1029        /*
1030         * Check if entire header is unpacked in the first iteration.
1031         */
1032        if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1033                return 0;
1034
1035        /*
1036         * buffer[0..bufsiz] was not large enough.  Copy the partial
1037         * result out to header, and then append the result of further
1038         * reading the stream.
1039         */
1040        strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1041        stream->next_out = buffer;
1042        stream->avail_out = bufsiz;
1043
1044        do {
1045                status = git_inflate(stream, 0);
1046                strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1047                if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1048                        return 0;
1049                stream->next_out = buffer;
1050                stream->avail_out = bufsiz;
1051        } while (status != Z_STREAM_END);
1052        return -1;
1053}
1054
1055static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1056{
1057        int bytes = strlen(buffer) + 1;
1058        unsigned char *buf = xmallocz(size);
1059        unsigned long n;
1060        int status = Z_OK;
1061
1062        n = stream->total_out - bytes;
1063        if (n > size)
1064                n = size;
1065        memcpy(buf, (char *) buffer + bytes, n);
1066        bytes = n;
1067        if (bytes <= size) {
1068                /*
1069                 * The above condition must be (bytes <= size), not
1070                 * (bytes < size).  In other words, even though we
1071                 * expect no more output and set avail_out to zero,
1072                 * the input zlib stream may have bytes that express
1073                 * "this concludes the stream", and we *do* want to
1074                 * eat that input.
1075                 *
1076                 * Otherwise we would not be able to test that we
1077                 * consumed all the input to reach the expected size;
1078                 * we also want to check that zlib tells us that all
1079                 * went well with status == Z_STREAM_END at the end.
1080                 */
1081                stream->next_out = buf + bytes;
1082                stream->avail_out = size - bytes;
1083                while (status == Z_OK)
1084                        status = git_inflate(stream, Z_FINISH);
1085        }
1086        if (status == Z_STREAM_END && !stream->avail_in) {
1087                git_inflate_end(stream);
1088                return buf;
1089        }
1090
1091        if (status < 0)
1092                error("corrupt loose object '%s'", sha1_to_hex(sha1));
1093        else if (stream->avail_in)
1094                error("garbage at end of loose object '%s'",
1095                      sha1_to_hex(sha1));
1096        free(buf);
1097        return NULL;
1098}
1099
1100/*
1101 * We used to just use "sscanf()", but that's actually way
1102 * too permissive for what we want to check. So do an anal
1103 * object header parse by hand.
1104 */
1105static int parse_sha1_header_extended(const char *hdr, struct object_info *oi,
1106                               unsigned int flags)
1107{
1108        const char *type_buf = hdr;
1109        unsigned long size;
1110        int type, type_len = 0;
1111
1112        /*
1113         * The type can be of any size but is followed by
1114         * a space.
1115         */
1116        for (;;) {
1117                char c = *hdr++;
1118                if (!c)
1119                        return -1;
1120                if (c == ' ')
1121                        break;
1122                type_len++;
1123        }
1124
1125        type = type_from_string_gently(type_buf, type_len, 1);
1126        if (oi->type_name)
1127                strbuf_add(oi->type_name, type_buf, type_len);
1128        /*
1129         * Set type to 0 if its an unknown object and
1130         * we're obtaining the type using '--allow-unknown-type'
1131         * option.
1132         */
1133        if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE) && (type < 0))
1134                type = 0;
1135        else if (type < 0)
1136                die("invalid object type");
1137        if (oi->typep)
1138                *oi->typep = type;
1139
1140        /*
1141         * The length must follow immediately, and be in canonical
1142         * decimal format (ie "010" is not valid).
1143         */
1144        size = *hdr++ - '0';
1145        if (size > 9)
1146                return -1;
1147        if (size) {
1148                for (;;) {
1149                        unsigned long c = *hdr - '0';
1150                        if (c > 9)
1151                                break;
1152                        hdr++;
1153                        size = size * 10 + c;
1154                }
1155        }
1156
1157        if (oi->sizep)
1158                *oi->sizep = size;
1159
1160        /*
1161         * The length must be followed by a zero byte
1162         */
1163        return *hdr ? -1 : type;
1164}
1165
1166int parse_sha1_header(const char *hdr, unsigned long *sizep)
1167{
1168        struct object_info oi = OBJECT_INFO_INIT;
1169
1170        oi.sizep = sizep;
1171        return parse_sha1_header_extended(hdr, &oi, 0);
1172}
1173
1174static int sha1_loose_object_info(struct repository *r,
1175                                  const unsigned char *sha1,
1176                                  struct object_info *oi, int flags)
1177{
1178        int status = 0;
1179        unsigned long mapsize;
1180        void *map;
1181        git_zstream stream;
1182        char hdr[MAX_HEADER_LEN];
1183        struct strbuf hdrbuf = STRBUF_INIT;
1184        unsigned long size_scratch;
1185
1186        if (oi->delta_base_sha1)
1187                hashclr(oi->delta_base_sha1);
1188
1189        /*
1190         * If we don't care about type or size, then we don't
1191         * need to look inside the object at all. Note that we
1192         * do not optimize out the stat call, even if the
1193         * caller doesn't care about the disk-size, since our
1194         * return value implicitly indicates whether the
1195         * object even exists.
1196         */
1197        if (!oi->typep && !oi->type_name && !oi->sizep && !oi->contentp) {
1198                const char *path;
1199                struct stat st;
1200                if (stat_sha1_file(r, sha1, &st, &path) < 0)
1201                        return -1;
1202                if (oi->disk_sizep)
1203                        *oi->disk_sizep = st.st_size;
1204                return 0;
1205        }
1206
1207        map = map_sha1_file(r, sha1, &mapsize);
1208        if (!map)
1209                return -1;
1210
1211        if (!oi->sizep)
1212                oi->sizep = &size_scratch;
1213
1214        if (oi->disk_sizep)
1215                *oi->disk_sizep = mapsize;
1216        if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE)) {
1217                if (unpack_sha1_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
1218                        status = error("unable to unpack %s header with --allow-unknown-type",
1219                                       sha1_to_hex(sha1));
1220        } else if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1221                status = error("unable to unpack %s header",
1222                               sha1_to_hex(sha1));
1223        if (status < 0)
1224                ; /* Do nothing */
1225        else if (hdrbuf.len) {
1226                if ((status = parse_sha1_header_extended(hdrbuf.buf, oi, flags)) < 0)
1227                        status = error("unable to parse %s header with --allow-unknown-type",
1228                                       sha1_to_hex(sha1));
1229        } else if ((status = parse_sha1_header_extended(hdr, oi, flags)) < 0)
1230                status = error("unable to parse %s header", sha1_to_hex(sha1));
1231
1232        if (status >= 0 && oi->contentp) {
1233                *oi->contentp = unpack_sha1_rest(&stream, hdr,
1234                                                 *oi->sizep, sha1);
1235                if (!*oi->contentp) {
1236                        git_inflate_end(&stream);
1237                        status = -1;
1238                }
1239        } else
1240                git_inflate_end(&stream);
1241
1242        munmap(map, mapsize);
1243        if (status && oi->typep)
1244                *oi->typep = status;
1245        if (oi->sizep == &size_scratch)
1246                oi->sizep = NULL;
1247        strbuf_release(&hdrbuf);
1248        oi->whence = OI_LOOSE;
1249        return (status < 0) ? status : 0;
1250}
1251
1252int fetch_if_missing = 1;
1253
1254int oid_object_info_extended(const struct object_id *oid, struct object_info *oi, unsigned flags)
1255{
1256        static struct object_info blank_oi = OBJECT_INFO_INIT;
1257        struct pack_entry e;
1258        int rtype;
1259        const struct object_id *real = oid;
1260        int already_retried = 0;
1261
1262        if (flags & OBJECT_INFO_LOOKUP_REPLACE)
1263                real = lookup_replace_object(oid);
1264
1265        if (is_null_oid(real))
1266                return -1;
1267
1268        if (!oi)
1269                oi = &blank_oi;
1270
1271        if (!(flags & OBJECT_INFO_SKIP_CACHED)) {
1272                struct cached_object *co = find_cached_object(real);
1273                if (co) {
1274                        if (oi->typep)
1275                                *(oi->typep) = co->type;
1276                        if (oi->sizep)
1277                                *(oi->sizep) = co->size;
1278                        if (oi->disk_sizep)
1279                                *(oi->disk_sizep) = 0;
1280                        if (oi->delta_base_sha1)
1281                                hashclr(oi->delta_base_sha1);
1282                        if (oi->type_name)
1283                                strbuf_addstr(oi->type_name, type_name(co->type));
1284                        if (oi->contentp)
1285                                *oi->contentp = xmemdupz(co->buf, co->size);
1286                        oi->whence = OI_CACHED;
1287                        return 0;
1288                }
1289        }
1290
1291        while (1) {
1292                if (find_pack_entry(the_repository, real, &e))
1293                        break;
1294
1295                if (flags & OBJECT_INFO_IGNORE_LOOSE)
1296                        return -1;
1297
1298                /* Most likely it's a loose object. */
1299                if (!sha1_loose_object_info(the_repository, real->hash, oi, flags))
1300                        return 0;
1301
1302                /* Not a loose object; someone else may have just packed it. */
1303                if (!(flags & OBJECT_INFO_QUICK)) {
1304                        reprepare_packed_git(the_repository);
1305                        if (find_pack_entry(the_repository, real, &e))
1306                                break;
1307                }
1308
1309                /* Check if it is a missing object */
1310                if (fetch_if_missing && repository_format_partial_clone &&
1311                    !already_retried) {
1312                        /*
1313                         * TODO Investigate haveing fetch_object() return
1314                         * TODO error/success and stopping the music here.
1315                         */
1316                        fetch_object(repository_format_partial_clone, real->hash);
1317                        already_retried = 1;
1318                        continue;
1319                }
1320
1321                return -1;
1322        }
1323
1324        if (oi == &blank_oi)
1325                /*
1326                 * We know that the caller doesn't actually need the
1327                 * information below, so return early.
1328                 */
1329                return 0;
1330        rtype = packed_object_info(e.p, e.offset, oi);
1331        if (rtype < 0) {
1332                mark_bad_packed_object(e.p, real->hash);
1333                return oid_object_info_extended(real, oi, 0);
1334        } else if (oi->whence == OI_PACKED) {
1335                oi->u.packed.offset = e.offset;
1336                oi->u.packed.pack = e.p;
1337                oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1338                                         rtype == OBJ_OFS_DELTA);
1339        }
1340
1341        return 0;
1342}
1343
1344/* returns enum object_type or negative */
1345int oid_object_info(const struct object_id *oid, unsigned long *sizep)
1346{
1347        enum object_type type;
1348        struct object_info oi = OBJECT_INFO_INIT;
1349
1350        oi.typep = &type;
1351        oi.sizep = sizep;
1352        if (oid_object_info_extended(oid, &oi,
1353                                     OBJECT_INFO_LOOKUP_REPLACE) < 0)
1354                return -1;
1355        return type;
1356}
1357
1358static void *read_object(const unsigned char *sha1, enum object_type *type,
1359                         unsigned long *size)
1360{
1361        struct object_id oid;
1362        struct object_info oi = OBJECT_INFO_INIT;
1363        void *content;
1364        oi.typep = type;
1365        oi.sizep = size;
1366        oi.contentp = &content;
1367
1368        hashcpy(oid.hash, sha1);
1369
1370        if (oid_object_info_extended(&oid, &oi, 0) < 0)
1371                return NULL;
1372        return content;
1373}
1374
1375int pretend_object_file(void *buf, unsigned long len, enum object_type type,
1376                        struct object_id *oid)
1377{
1378        struct cached_object *co;
1379
1380        hash_object_file(buf, len, type_name(type), oid);
1381        if (has_sha1_file(oid->hash) || find_cached_object(oid))
1382                return 0;
1383        ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
1384        co = &cached_objects[cached_object_nr++];
1385        co->size = len;
1386        co->type = type;
1387        co->buf = xmalloc(len);
1388        memcpy(co->buf, buf, len);
1389        oidcpy(&co->oid, oid);
1390        return 0;
1391}
1392
1393/*
1394 * This function dies on corrupt objects; the callers who want to
1395 * deal with them should arrange to call read_object() and give error
1396 * messages themselves.
1397 */
1398void *read_object_file_extended(const struct object_id *oid,
1399                                enum object_type *type,
1400                                unsigned long *size,
1401                                int lookup_replace)
1402{
1403        void *data;
1404        const struct packed_git *p;
1405        const char *path;
1406        struct stat st;
1407        const struct object_id *repl = lookup_replace ? lookup_replace_object(oid)
1408                                                      : oid;
1409
1410        errno = 0;
1411        data = read_object(repl->hash, type, size);
1412        if (data)
1413                return data;
1414
1415        if (errno && errno != ENOENT)
1416                die_errno("failed to read object %s", oid_to_hex(oid));
1417
1418        /* die if we replaced an object with one that does not exist */
1419        if (repl != oid)
1420                die("replacement %s not found for %s",
1421                    oid_to_hex(repl), oid_to_hex(oid));
1422
1423        if (!stat_sha1_file(the_repository, repl->hash, &st, &path))
1424                die("loose object %s (stored in %s) is corrupt",
1425                    oid_to_hex(repl), path);
1426
1427        if ((p = has_packed_and_bad(repl->hash)) != NULL)
1428                die("packed object %s (stored in %s) is corrupt",
1429                    oid_to_hex(repl), p->pack_name);
1430
1431        return NULL;
1432}
1433
1434void *read_object_with_reference(const struct object_id *oid,
1435                                 const char *required_type_name,
1436                                 unsigned long *size,
1437                                 struct object_id *actual_oid_return)
1438{
1439        enum object_type type, required_type;
1440        void *buffer;
1441        unsigned long isize;
1442        struct object_id actual_oid;
1443
1444        required_type = type_from_string(required_type_name);
1445        oidcpy(&actual_oid, oid);
1446        while (1) {
1447                int ref_length = -1;
1448                const char *ref_type = NULL;
1449
1450                buffer = read_object_file(&actual_oid, &type, &isize);
1451                if (!buffer)
1452                        return NULL;
1453                if (type == required_type) {
1454                        *size = isize;
1455                        if (actual_oid_return)
1456                                oidcpy(actual_oid_return, &actual_oid);
1457                        return buffer;
1458                }
1459                /* Handle references */
1460                else if (type == OBJ_COMMIT)
1461                        ref_type = "tree ";
1462                else if (type == OBJ_TAG)
1463                        ref_type = "object ";
1464                else {
1465                        free(buffer);
1466                        return NULL;
1467                }
1468                ref_length = strlen(ref_type);
1469
1470                if (ref_length + GIT_SHA1_HEXSZ > isize ||
1471                    memcmp(buffer, ref_type, ref_length) ||
1472                    get_oid_hex((char *) buffer + ref_length, &actual_oid)) {
1473                        free(buffer);
1474                        return NULL;
1475                }
1476                free(buffer);
1477                /* Now we have the ID of the referred-to object in
1478                 * actual_oid.  Check again. */
1479        }
1480}
1481
1482static void write_object_file_prepare(const void *buf, unsigned long len,
1483                                      const char *type, struct object_id *oid,
1484                                      char *hdr, int *hdrlen)
1485{
1486        git_hash_ctx c;
1487
1488        /* Generate the header */
1489        *hdrlen = xsnprintf(hdr, *hdrlen, "%s %lu", type, len)+1;
1490
1491        /* Sha1.. */
1492        the_hash_algo->init_fn(&c);
1493        the_hash_algo->update_fn(&c, hdr, *hdrlen);
1494        the_hash_algo->update_fn(&c, buf, len);
1495        the_hash_algo->final_fn(oid->hash, &c);
1496}
1497
1498/*
1499 * Move the just written object into its final resting place.
1500 */
1501int finalize_object_file(const char *tmpfile, const char *filename)
1502{
1503        int ret = 0;
1504
1505        if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
1506                goto try_rename;
1507        else if (link(tmpfile, filename))
1508                ret = errno;
1509
1510        /*
1511         * Coda hack - coda doesn't like cross-directory links,
1512         * so we fall back to a rename, which will mean that it
1513         * won't be able to check collisions, but that's not a
1514         * big deal.
1515         *
1516         * The same holds for FAT formatted media.
1517         *
1518         * When this succeeds, we just return.  We have nothing
1519         * left to unlink.
1520         */
1521        if (ret && ret != EEXIST) {
1522        try_rename:
1523                if (!rename(tmpfile, filename))
1524                        goto out;
1525                ret = errno;
1526        }
1527        unlink_or_warn(tmpfile);
1528        if (ret) {
1529                if (ret != EEXIST) {
1530                        return error_errno("unable to write sha1 filename %s", filename);
1531                }
1532                /* FIXME!!! Collision check here ? */
1533        }
1534
1535out:
1536        if (adjust_shared_perm(filename))
1537                return error("unable to set permission to '%s'", filename);
1538        return 0;
1539}
1540
1541static int write_buffer(int fd, const void *buf, size_t len)
1542{
1543        if (write_in_full(fd, buf, len) < 0)
1544                return error_errno("file write error");
1545        return 0;
1546}
1547
1548int hash_object_file(const void *buf, unsigned long len, const char *type,
1549                     struct object_id *oid)
1550{
1551        char hdr[MAX_HEADER_LEN];
1552        int hdrlen = sizeof(hdr);
1553        write_object_file_prepare(buf, len, type, oid, hdr, &hdrlen);
1554        return 0;
1555}
1556
1557/* Finalize a file on disk, and close it. */
1558static void close_sha1_file(int fd)
1559{
1560        if (fsync_object_files)
1561                fsync_or_die(fd, "sha1 file");
1562        if (close(fd) != 0)
1563                die_errno("error when closing sha1 file");
1564}
1565
1566/* Size of directory component, including the ending '/' */
1567static inline int directory_size(const char *filename)
1568{
1569        const char *s = strrchr(filename, '/');
1570        if (!s)
1571                return 0;
1572        return s - filename + 1;
1573}
1574
1575/*
1576 * This creates a temporary file in the same directory as the final
1577 * 'filename'
1578 *
1579 * We want to avoid cross-directory filename renames, because those
1580 * can have problems on various filesystems (FAT, NFS, Coda).
1581 */
1582static int create_tmpfile(struct strbuf *tmp, const char *filename)
1583{
1584        int fd, dirlen = directory_size(filename);
1585
1586        strbuf_reset(tmp);
1587        strbuf_add(tmp, filename, dirlen);
1588        strbuf_addstr(tmp, "tmp_obj_XXXXXX");
1589        fd = git_mkstemp_mode(tmp->buf, 0444);
1590        if (fd < 0 && dirlen && errno == ENOENT) {
1591                /*
1592                 * Make sure the directory exists; note that the contents
1593                 * of the buffer are undefined after mkstemp returns an
1594                 * error, so we have to rewrite the whole buffer from
1595                 * scratch.
1596                 */
1597                strbuf_reset(tmp);
1598                strbuf_add(tmp, filename, dirlen - 1);
1599                if (mkdir(tmp->buf, 0777) && errno != EEXIST)
1600                        return -1;
1601                if (adjust_shared_perm(tmp->buf))
1602                        return -1;
1603
1604                /* Try again */
1605                strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
1606                fd = git_mkstemp_mode(tmp->buf, 0444);
1607        }
1608        return fd;
1609}
1610
1611static int write_loose_object(const struct object_id *oid, char *hdr,
1612                              int hdrlen, const void *buf, unsigned long len,
1613                              time_t mtime)
1614{
1615        int fd, ret;
1616        unsigned char compressed[4096];
1617        git_zstream stream;
1618        git_hash_ctx c;
1619        struct object_id parano_oid;
1620        static struct strbuf tmp_file = STRBUF_INIT;
1621        static struct strbuf filename = STRBUF_INIT;
1622
1623        strbuf_reset(&filename);
1624        sha1_file_name(the_repository, &filename, oid->hash);
1625
1626        fd = create_tmpfile(&tmp_file, filename.buf);
1627        if (fd < 0) {
1628                if (errno == EACCES)
1629                        return error("insufficient permission for adding an object to repository database %s", get_object_directory());
1630                else
1631                        return error_errno("unable to create temporary file");
1632        }
1633
1634        /* Set it up */
1635        git_deflate_init(&stream, zlib_compression_level);
1636        stream.next_out = compressed;
1637        stream.avail_out = sizeof(compressed);
1638        the_hash_algo->init_fn(&c);
1639
1640        /* First header.. */
1641        stream.next_in = (unsigned char *)hdr;
1642        stream.avail_in = hdrlen;
1643        while (git_deflate(&stream, 0) == Z_OK)
1644                ; /* nothing */
1645        the_hash_algo->update_fn(&c, hdr, hdrlen);
1646
1647        /* Then the data itself.. */
1648        stream.next_in = (void *)buf;
1649        stream.avail_in = len;
1650        do {
1651                unsigned char *in0 = stream.next_in;
1652                ret = git_deflate(&stream, Z_FINISH);
1653                the_hash_algo->update_fn(&c, in0, stream.next_in - in0);
1654                if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
1655                        die("unable to write sha1 file");
1656                stream.next_out = compressed;
1657                stream.avail_out = sizeof(compressed);
1658        } while (ret == Z_OK);
1659
1660        if (ret != Z_STREAM_END)
1661                die("unable to deflate new object %s (%d)", oid_to_hex(oid),
1662                    ret);
1663        ret = git_deflate_end_gently(&stream);
1664        if (ret != Z_OK)
1665                die("deflateEnd on object %s failed (%d)", oid_to_hex(oid),
1666                    ret);
1667        the_hash_algo->final_fn(parano_oid.hash, &c);
1668        if (oidcmp(oid, &parano_oid) != 0)
1669                die("confused by unstable object source data for %s",
1670                    oid_to_hex(oid));
1671
1672        close_sha1_file(fd);
1673
1674        if (mtime) {
1675                struct utimbuf utb;
1676                utb.actime = mtime;
1677                utb.modtime = mtime;
1678                if (utime(tmp_file.buf, &utb) < 0)
1679                        warning_errno("failed utime() on %s", tmp_file.buf);
1680        }
1681
1682        return finalize_object_file(tmp_file.buf, filename.buf);
1683}
1684
1685static int freshen_loose_object(const struct object_id *oid)
1686{
1687        return check_and_freshen(oid, 1);
1688}
1689
1690static int freshen_packed_object(const struct object_id *oid)
1691{
1692        struct pack_entry e;
1693        if (!find_pack_entry(the_repository, oid, &e))
1694                return 0;
1695        if (e.p->freshened)
1696                return 1;
1697        if (!freshen_file(e.p->pack_name))
1698                return 0;
1699        e.p->freshened = 1;
1700        return 1;
1701}
1702
1703int write_object_file(const void *buf, unsigned long len, const char *type,
1704                      struct object_id *oid)
1705{
1706        char hdr[MAX_HEADER_LEN];
1707        int hdrlen = sizeof(hdr);
1708
1709        /* Normally if we have it in the pack then we do not bother writing
1710         * it out into .git/objects/??/?{38} file.
1711         */
1712        write_object_file_prepare(buf, len, type, oid, hdr, &hdrlen);
1713        if (freshen_packed_object(oid) || freshen_loose_object(oid))
1714                return 0;
1715        return write_loose_object(oid, hdr, hdrlen, buf, len, 0);
1716}
1717
1718int hash_object_file_literally(const void *buf, unsigned long len,
1719                               const char *type, struct object_id *oid,
1720                               unsigned flags)
1721{
1722        char *header;
1723        int hdrlen, status = 0;
1724
1725        /* type string, SP, %lu of the length plus NUL must fit this */
1726        hdrlen = strlen(type) + MAX_HEADER_LEN;
1727        header = xmalloc(hdrlen);
1728        write_object_file_prepare(buf, len, type, oid, header, &hdrlen);
1729
1730        if (!(flags & HASH_WRITE_OBJECT))
1731                goto cleanup;
1732        if (freshen_packed_object(oid) || freshen_loose_object(oid))
1733                goto cleanup;
1734        status = write_loose_object(oid, header, hdrlen, buf, len, 0);
1735
1736cleanup:
1737        free(header);
1738        return status;
1739}
1740
1741int force_object_loose(const struct object_id *oid, time_t mtime)
1742{
1743        void *buf;
1744        unsigned long len;
1745        enum object_type type;
1746        char hdr[MAX_HEADER_LEN];
1747        int hdrlen;
1748        int ret;
1749
1750        if (has_loose_object(oid))
1751                return 0;
1752        buf = read_object(oid->hash, &type, &len);
1753        if (!buf)
1754                return error("cannot read sha1_file for %s", oid_to_hex(oid));
1755        hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", type_name(type), len) + 1;
1756        ret = write_loose_object(oid, hdr, hdrlen, buf, len, mtime);
1757        free(buf);
1758
1759        return ret;
1760}
1761
1762int has_sha1_file_with_flags(const unsigned char *sha1, int flags)
1763{
1764        struct object_id oid;
1765        if (!startup_info->have_repository)
1766                return 0;
1767        hashcpy(oid.hash, sha1);
1768        return oid_object_info_extended(&oid, NULL,
1769                                        flags | OBJECT_INFO_SKIP_CACHED) >= 0;
1770}
1771
1772int has_object_file(const struct object_id *oid)
1773{
1774        return has_sha1_file(oid->hash);
1775}
1776
1777int has_object_file_with_flags(const struct object_id *oid, int flags)
1778{
1779        return has_sha1_file_with_flags(oid->hash, flags);
1780}
1781
1782static void check_tree(const void *buf, size_t size)
1783{
1784        struct tree_desc desc;
1785        struct name_entry entry;
1786
1787        init_tree_desc(&desc, buf, size);
1788        while (tree_entry(&desc, &entry))
1789                /* do nothing
1790                 * tree_entry() will die() on malformed entries */
1791                ;
1792}
1793
1794static void check_commit(const void *buf, size_t size)
1795{
1796        struct commit c;
1797        memset(&c, 0, sizeof(c));
1798        if (parse_commit_buffer(&c, buf, size))
1799                die("corrupt commit");
1800}
1801
1802static void check_tag(const void *buf, size_t size)
1803{
1804        struct tag t;
1805        memset(&t, 0, sizeof(t));
1806        if (parse_tag_buffer(&t, buf, size))
1807                die("corrupt tag");
1808}
1809
1810static int index_mem(struct object_id *oid, void *buf, size_t size,
1811                     enum object_type type,
1812                     const char *path, unsigned flags)
1813{
1814        int ret, re_allocated = 0;
1815        int write_object = flags & HASH_WRITE_OBJECT;
1816
1817        if (!type)
1818                type = OBJ_BLOB;
1819
1820        /*
1821         * Convert blobs to git internal format
1822         */
1823        if ((type == OBJ_BLOB) && path) {
1824                struct strbuf nbuf = STRBUF_INIT;
1825                if (convert_to_git(&the_index, path, buf, size, &nbuf,
1826                                   get_conv_flags(flags))) {
1827                        buf = strbuf_detach(&nbuf, &size);
1828                        re_allocated = 1;
1829                }
1830        }
1831        if (flags & HASH_FORMAT_CHECK) {
1832                if (type == OBJ_TREE)
1833                        check_tree(buf, size);
1834                if (type == OBJ_COMMIT)
1835                        check_commit(buf, size);
1836                if (type == OBJ_TAG)
1837                        check_tag(buf, size);
1838        }
1839
1840        if (write_object)
1841                ret = write_object_file(buf, size, type_name(type), oid);
1842        else
1843                ret = hash_object_file(buf, size, type_name(type), oid);
1844        if (re_allocated)
1845                free(buf);
1846        return ret;
1847}
1848
1849static int index_stream_convert_blob(struct object_id *oid, int fd,
1850                                     const char *path, unsigned flags)
1851{
1852        int ret;
1853        const int write_object = flags & HASH_WRITE_OBJECT;
1854        struct strbuf sbuf = STRBUF_INIT;
1855
1856        assert(path);
1857        assert(would_convert_to_git_filter_fd(path));
1858
1859        convert_to_git_filter_fd(&the_index, path, fd, &sbuf,
1860                                 get_conv_flags(flags));
1861
1862        if (write_object)
1863                ret = write_object_file(sbuf.buf, sbuf.len, type_name(OBJ_BLOB),
1864                                        oid);
1865        else
1866                ret = hash_object_file(sbuf.buf, sbuf.len, type_name(OBJ_BLOB),
1867                                       oid);
1868        strbuf_release(&sbuf);
1869        return ret;
1870}
1871
1872static int index_pipe(struct object_id *oid, int fd, enum object_type type,
1873                      const char *path, unsigned flags)
1874{
1875        struct strbuf sbuf = STRBUF_INIT;
1876        int ret;
1877
1878        if (strbuf_read(&sbuf, fd, 4096) >= 0)
1879                ret = index_mem(oid, sbuf.buf, sbuf.len, type, path, flags);
1880        else
1881                ret = -1;
1882        strbuf_release(&sbuf);
1883        return ret;
1884}
1885
1886#define SMALL_FILE_SIZE (32*1024)
1887
1888static int index_core(struct object_id *oid, int fd, size_t size,
1889                      enum object_type type, const char *path,
1890                      unsigned flags)
1891{
1892        int ret;
1893
1894        if (!size) {
1895                ret = index_mem(oid, "", size, type, path, flags);
1896        } else if (size <= SMALL_FILE_SIZE) {
1897                char *buf = xmalloc(size);
1898                ssize_t read_result = read_in_full(fd, buf, size);
1899                if (read_result < 0)
1900                        ret = error_errno("read error while indexing %s",
1901                                          path ? path : "<unknown>");
1902                else if (read_result != size)
1903                        ret = error("short read while indexing %s",
1904                                    path ? path : "<unknown>");
1905                else
1906                        ret = index_mem(oid, buf, size, type, path, flags);
1907                free(buf);
1908        } else {
1909                void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1910                ret = index_mem(oid, buf, size, type, path, flags);
1911                munmap(buf, size);
1912        }
1913        return ret;
1914}
1915
1916/*
1917 * This creates one packfile per large blob unless bulk-checkin
1918 * machinery is "plugged".
1919 *
1920 * This also bypasses the usual "convert-to-git" dance, and that is on
1921 * purpose. We could write a streaming version of the converting
1922 * functions and insert that before feeding the data to fast-import
1923 * (or equivalent in-core API described above). However, that is
1924 * somewhat complicated, as we do not know the size of the filter
1925 * result, which we need to know beforehand when writing a git object.
1926 * Since the primary motivation for trying to stream from the working
1927 * tree file and to avoid mmaping it in core is to deal with large
1928 * binary blobs, they generally do not want to get any conversion, and
1929 * callers should avoid this code path when filters are requested.
1930 */
1931static int index_stream(struct object_id *oid, int fd, size_t size,
1932                        enum object_type type, const char *path,
1933                        unsigned flags)
1934{
1935        return index_bulk_checkin(oid, fd, size, type, path, flags);
1936}
1937
1938int index_fd(struct object_id *oid, int fd, struct stat *st,
1939             enum object_type type, const char *path, unsigned flags)
1940{
1941        int ret;
1942
1943        /*
1944         * Call xsize_t() only when needed to avoid potentially unnecessary
1945         * die() for large files.
1946         */
1947        if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(path))
1948                ret = index_stream_convert_blob(oid, fd, path, flags);
1949        else if (!S_ISREG(st->st_mode))
1950                ret = index_pipe(oid, fd, type, path, flags);
1951        else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
1952                 (path && would_convert_to_git(&the_index, path)))
1953                ret = index_core(oid, fd, xsize_t(st->st_size), type, path,
1954                                 flags);
1955        else
1956                ret = index_stream(oid, fd, xsize_t(st->st_size), type, path,
1957                                   flags);
1958        close(fd);
1959        return ret;
1960}
1961
1962int index_path(struct object_id *oid, const char *path, struct stat *st, unsigned flags)
1963{
1964        int fd;
1965        struct strbuf sb = STRBUF_INIT;
1966        int rc = 0;
1967
1968        switch (st->st_mode & S_IFMT) {
1969        case S_IFREG:
1970                fd = open(path, O_RDONLY);
1971                if (fd < 0)
1972                        return error_errno("open(\"%s\")", path);
1973                if (index_fd(oid, fd, st, OBJ_BLOB, path, flags) < 0)
1974                        return error("%s: failed to insert into database",
1975                                     path);
1976                break;
1977        case S_IFLNK:
1978                if (strbuf_readlink(&sb, path, st->st_size))
1979                        return error_errno("readlink(\"%s\")", path);
1980                if (!(flags & HASH_WRITE_OBJECT))
1981                        hash_object_file(sb.buf, sb.len, blob_type, oid);
1982                else if (write_object_file(sb.buf, sb.len, blob_type, oid))
1983                        rc = error("%s: failed to insert into database", path);
1984                strbuf_release(&sb);
1985                break;
1986        case S_IFDIR:
1987                return resolve_gitlink_ref(path, "HEAD", oid);
1988        default:
1989                return error("%s: unsupported file type", path);
1990        }
1991        return rc;
1992}
1993
1994int read_pack_header(int fd, struct pack_header *header)
1995{
1996        if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
1997                /* "eof before pack header was fully read" */
1998                return PH_ERROR_EOF;
1999
2000        if (header->hdr_signature != htonl(PACK_SIGNATURE))
2001                /* "protocol error (pack signature mismatch detected)" */
2002                return PH_ERROR_PACK_SIGNATURE;
2003        if (!pack_version_ok(header->hdr_version))
2004                /* "protocol error (pack version unsupported)" */
2005                return PH_ERROR_PROTOCOL;
2006        return 0;
2007}
2008
2009void assert_oid_type(const struct object_id *oid, enum object_type expect)
2010{
2011        enum object_type type = oid_object_info(oid, NULL);
2012        if (type < 0)
2013                die("%s is not a valid object", oid_to_hex(oid));
2014        if (type != expect)
2015                die("%s is not a valid '%s' object", oid_to_hex(oid),
2016                    type_name(expect));
2017}
2018
2019int for_each_file_in_obj_subdir(unsigned int subdir_nr,
2020                                struct strbuf *path,
2021                                each_loose_object_fn obj_cb,
2022                                each_loose_cruft_fn cruft_cb,
2023                                each_loose_subdir_fn subdir_cb,
2024                                void *data)
2025{
2026        size_t origlen, baselen;
2027        DIR *dir;
2028        struct dirent *de;
2029        int r = 0;
2030        struct object_id oid;
2031
2032        if (subdir_nr > 0xff)
2033                BUG("invalid loose object subdirectory: %x", subdir_nr);
2034
2035        origlen = path->len;
2036        strbuf_complete(path, '/');
2037        strbuf_addf(path, "%02x", subdir_nr);
2038
2039        dir = opendir(path->buf);
2040        if (!dir) {
2041                if (errno != ENOENT)
2042                        r = error_errno("unable to open %s", path->buf);
2043                strbuf_setlen(path, origlen);
2044                return r;
2045        }
2046
2047        oid.hash[0] = subdir_nr;
2048        strbuf_addch(path, '/');
2049        baselen = path->len;
2050
2051        while ((de = readdir(dir))) {
2052                size_t namelen;
2053                if (is_dot_or_dotdot(de->d_name))
2054                        continue;
2055
2056                namelen = strlen(de->d_name);
2057                strbuf_setlen(path, baselen);
2058                strbuf_add(path, de->d_name, namelen);
2059                if (namelen == GIT_SHA1_HEXSZ - 2 &&
2060                    !hex_to_bytes(oid.hash + 1, de->d_name,
2061                                  GIT_SHA1_RAWSZ - 1)) {
2062                        if (obj_cb) {
2063                                r = obj_cb(&oid, path->buf, data);
2064                                if (r)
2065                                        break;
2066                        }
2067                        continue;
2068                }
2069
2070                if (cruft_cb) {
2071                        r = cruft_cb(de->d_name, path->buf, data);
2072                        if (r)
2073                                break;
2074                }
2075        }
2076        closedir(dir);
2077
2078        strbuf_setlen(path, baselen - 1);
2079        if (!r && subdir_cb)
2080                r = subdir_cb(subdir_nr, path->buf, data);
2081
2082        strbuf_setlen(path, origlen);
2083
2084        return r;
2085}
2086
2087int for_each_loose_file_in_objdir_buf(struct strbuf *path,
2088                            each_loose_object_fn obj_cb,
2089                            each_loose_cruft_fn cruft_cb,
2090                            each_loose_subdir_fn subdir_cb,
2091                            void *data)
2092{
2093        int r = 0;
2094        int i;
2095
2096        for (i = 0; i < 256; i++) {
2097                r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
2098                                                subdir_cb, data);
2099                if (r)
2100                        break;
2101        }
2102
2103        return r;
2104}
2105
2106int for_each_loose_file_in_objdir(const char *path,
2107                                  each_loose_object_fn obj_cb,
2108                                  each_loose_cruft_fn cruft_cb,
2109                                  each_loose_subdir_fn subdir_cb,
2110                                  void *data)
2111{
2112        struct strbuf buf = STRBUF_INIT;
2113        int r;
2114
2115        strbuf_addstr(&buf, path);
2116        r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2117                                              subdir_cb, data);
2118        strbuf_release(&buf);
2119
2120        return r;
2121}
2122
2123struct loose_alt_odb_data {
2124        each_loose_object_fn *cb;
2125        void *data;
2126};
2127
2128static int loose_from_alt_odb(struct alternate_object_database *alt,
2129                              void *vdata)
2130{
2131        struct loose_alt_odb_data *data = vdata;
2132        struct strbuf buf = STRBUF_INIT;
2133        int r;
2134
2135        strbuf_addstr(&buf, alt->path);
2136        r = for_each_loose_file_in_objdir_buf(&buf,
2137                                              data->cb, NULL, NULL,
2138                                              data->data);
2139        strbuf_release(&buf);
2140        return r;
2141}
2142
2143int for_each_loose_object(each_loose_object_fn cb, void *data, unsigned flags)
2144{
2145        struct loose_alt_odb_data alt;
2146        int r;
2147
2148        r = for_each_loose_file_in_objdir(get_object_directory(),
2149                                          cb, NULL, NULL, data);
2150        if (r)
2151                return r;
2152
2153        if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2154                return 0;
2155
2156        alt.cb = cb;
2157        alt.data = data;
2158        return foreach_alt_odb(loose_from_alt_odb, &alt);
2159}
2160
2161static int check_stream_sha1(git_zstream *stream,
2162                             const char *hdr,
2163                             unsigned long size,
2164                             const char *path,
2165                             const unsigned char *expected_sha1)
2166{
2167        git_hash_ctx c;
2168        unsigned char real_sha1[GIT_MAX_RAWSZ];
2169        unsigned char buf[4096];
2170        unsigned long total_read;
2171        int status = Z_OK;
2172
2173        the_hash_algo->init_fn(&c);
2174        the_hash_algo->update_fn(&c, hdr, stream->total_out);
2175
2176        /*
2177         * We already read some bytes into hdr, but the ones up to the NUL
2178         * do not count against the object's content size.
2179         */
2180        total_read = stream->total_out - strlen(hdr) - 1;
2181
2182        /*
2183         * This size comparison must be "<=" to read the final zlib packets;
2184         * see the comment in unpack_sha1_rest for details.
2185         */
2186        while (total_read <= size &&
2187               (status == Z_OK || status == Z_BUF_ERROR)) {
2188                stream->next_out = buf;
2189                stream->avail_out = sizeof(buf);
2190                if (size - total_read < stream->avail_out)
2191                        stream->avail_out = size - total_read;
2192                status = git_inflate(stream, Z_FINISH);
2193                the_hash_algo->update_fn(&c, buf, stream->next_out - buf);
2194                total_read += stream->next_out - buf;
2195        }
2196        git_inflate_end(stream);
2197
2198        if (status != Z_STREAM_END) {
2199                error("corrupt loose object '%s'", sha1_to_hex(expected_sha1));
2200                return -1;
2201        }
2202        if (stream->avail_in) {
2203                error("garbage at end of loose object '%s'",
2204                      sha1_to_hex(expected_sha1));
2205                return -1;
2206        }
2207
2208        the_hash_algo->final_fn(real_sha1, &c);
2209        if (hashcmp(expected_sha1, real_sha1)) {
2210                error("sha1 mismatch for %s (expected %s)", path,
2211                      sha1_to_hex(expected_sha1));
2212                return -1;
2213        }
2214
2215        return 0;
2216}
2217
2218int read_loose_object(const char *path,
2219                      const struct object_id *expected_oid,
2220                      enum object_type *type,
2221                      unsigned long *size,
2222                      void **contents)
2223{
2224        int ret = -1;
2225        void *map = NULL;
2226        unsigned long mapsize;
2227        git_zstream stream;
2228        char hdr[MAX_HEADER_LEN];
2229
2230        *contents = NULL;
2231
2232        map = map_sha1_file_1(the_repository, path, NULL, &mapsize);
2233        if (!map) {
2234                error_errno("unable to mmap %s", path);
2235                goto out;
2236        }
2237
2238        if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0) {
2239                error("unable to unpack header of %s", path);
2240                goto out;
2241        }
2242
2243        *type = parse_sha1_header(hdr, size);
2244        if (*type < 0) {
2245                error("unable to parse header of %s", path);
2246                git_inflate_end(&stream);
2247                goto out;
2248        }
2249
2250        if (*type == OBJ_BLOB) {
2251                if (check_stream_sha1(&stream, hdr, *size, path, expected_oid->hash) < 0)
2252                        goto out;
2253        } else {
2254                *contents = unpack_sha1_rest(&stream, hdr, *size, expected_oid->hash);
2255                if (!*contents) {
2256                        error("unable to unpack contents of %s", path);
2257                        git_inflate_end(&stream);
2258                        goto out;
2259                }
2260                if (check_object_signature(expected_oid, *contents,
2261                                         *size, type_name(*type))) {
2262                        error("sha1 mismatch for %s (expected %s)", path,
2263                              oid_to_hex(expected_oid));
2264                        free(*contents);
2265                        goto out;
2266                }
2267        }
2268
2269        ret = 0; /* everything checks out */
2270
2271out:
2272        if (map)
2273                munmap(map, mapsize);
2274        return ret;
2275}