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