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