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