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