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