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