abd3b59b578fc2103c71b45bc74be492917bf3a0
   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 "streaming.h"
  26#include "dir.h"
  27#include "mru.h"
  28#include "list.h"
  29#include "mergesort.h"
  30#include "quote.h"
  31#include "packfile.h"
  32
  33const unsigned char null_sha1[20];
  34const struct object_id null_oid;
  35const struct object_id empty_tree_oid = {
  36        EMPTY_TREE_SHA1_BIN_LITERAL
  37};
  38const struct object_id empty_blob_oid = {
  39        EMPTY_BLOB_SHA1_BIN_LITERAL
  40};
  41
  42/*
  43 * This is meant to hold a *small* number of objects that you would
  44 * want read_sha1_file() to be able to return, but yet you do not want
  45 * to write them into the object store (e.g. a browse-only
  46 * application).
  47 */
  48static struct cached_object {
  49        unsigned char sha1[20];
  50        enum object_type type;
  51        void *buf;
  52        unsigned long size;
  53} *cached_objects;
  54static int cached_object_nr, cached_object_alloc;
  55
  56static struct cached_object empty_tree = {
  57        EMPTY_TREE_SHA1_BIN_LITERAL,
  58        OBJ_TREE,
  59        "",
  60        0
  61};
  62
  63static struct cached_object *find_cached_object(const unsigned char *sha1)
  64{
  65        int i;
  66        struct cached_object *co = cached_objects;
  67
  68        for (i = 0; i < cached_object_nr; i++, co++) {
  69                if (!hashcmp(co->sha1, sha1))
  70                        return co;
  71        }
  72        if (!hashcmp(sha1, empty_tree.sha1))
  73                return &empty_tree;
  74        return NULL;
  75}
  76
  77int mkdir_in_gitdir(const char *path)
  78{
  79        if (mkdir(path, 0777)) {
  80                int saved_errno = errno;
  81                struct stat st;
  82                struct strbuf sb = STRBUF_INIT;
  83
  84                if (errno != EEXIST)
  85                        return -1;
  86                /*
  87                 * Are we looking at a path in a symlinked worktree
  88                 * whose original repository does not yet have it?
  89                 * e.g. .git/rr-cache pointing at its original
  90                 * repository in which the user hasn't performed any
  91                 * conflict resolution yet?
  92                 */
  93                if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
  94                    strbuf_readlink(&sb, path, st.st_size) ||
  95                    !is_absolute_path(sb.buf) ||
  96                    mkdir(sb.buf, 0777)) {
  97                        strbuf_release(&sb);
  98                        errno = saved_errno;
  99                        return -1;
 100                }
 101                strbuf_release(&sb);
 102        }
 103        return adjust_shared_perm(path);
 104}
 105
 106enum scld_error safe_create_leading_directories(char *path)
 107{
 108        char *next_component = path + offset_1st_component(path);
 109        enum scld_error ret = SCLD_OK;
 110
 111        while (ret == SCLD_OK && next_component) {
 112                struct stat st;
 113                char *slash = next_component, slash_character;
 114
 115                while (*slash && !is_dir_sep(*slash))
 116                        slash++;
 117
 118                if (!*slash)
 119                        break;
 120
 121                next_component = slash + 1;
 122                while (is_dir_sep(*next_component))
 123                        next_component++;
 124                if (!*next_component)
 125                        break;
 126
 127                slash_character = *slash;
 128                *slash = '\0';
 129                if (!stat(path, &st)) {
 130                        /* path exists */
 131                        if (!S_ISDIR(st.st_mode)) {
 132                                errno = ENOTDIR;
 133                                ret = SCLD_EXISTS;
 134                        }
 135                } else if (mkdir(path, 0777)) {
 136                        if (errno == EEXIST &&
 137                            !stat(path, &st) && S_ISDIR(st.st_mode))
 138                                ; /* somebody created it since we checked */
 139                        else if (errno == ENOENT)
 140                                /*
 141                                 * Either mkdir() failed because
 142                                 * somebody just pruned the containing
 143                                 * directory, or stat() failed because
 144                                 * the file that was in our way was
 145                                 * just removed.  Either way, inform
 146                                 * the caller that it might be worth
 147                                 * trying again:
 148                                 */
 149                                ret = SCLD_VANISHED;
 150                        else
 151                                ret = SCLD_FAILED;
 152                } else if (adjust_shared_perm(path)) {
 153                        ret = SCLD_PERMS;
 154                }
 155                *slash = slash_character;
 156        }
 157        return ret;
 158}
 159
 160enum scld_error safe_create_leading_directories_const(const char *path)
 161{
 162        int save_errno;
 163        /* path points to cache entries, so xstrdup before messing with it */
 164        char *buf = xstrdup(path);
 165        enum scld_error result = safe_create_leading_directories(buf);
 166
 167        save_errno = errno;
 168        free(buf);
 169        errno = save_errno;
 170        return result;
 171}
 172
 173int raceproof_create_file(const char *path, create_file_fn fn, void *cb)
 174{
 175        /*
 176         * The number of times we will try to remove empty directories
 177         * in the way of path. This is only 1 because if another
 178         * process is racily creating directories that conflict with
 179         * us, we don't want to fight against them.
 180         */
 181        int remove_directories_remaining = 1;
 182
 183        /*
 184         * The number of times that we will try to create the
 185         * directories containing path. We are willing to attempt this
 186         * more than once, because another process could be trying to
 187         * clean up empty directories at the same time as we are
 188         * trying to create them.
 189         */
 190        int create_directories_remaining = 3;
 191
 192        /* A scratch copy of path, filled lazily if we need it: */
 193        struct strbuf path_copy = STRBUF_INIT;
 194
 195        int ret, save_errno;
 196
 197        /* Sanity check: */
 198        assert(*path);
 199
 200retry_fn:
 201        ret = fn(path, cb);
 202        save_errno = errno;
 203        if (!ret)
 204                goto out;
 205
 206        if (errno == EISDIR && remove_directories_remaining-- > 0) {
 207                /*
 208                 * A directory is in the way. Maybe it is empty; try
 209                 * to remove it:
 210                 */
 211                if (!path_copy.len)
 212                        strbuf_addstr(&path_copy, path);
 213
 214                if (!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY))
 215                        goto retry_fn;
 216        } else if (errno == ENOENT && create_directories_remaining-- > 0) {
 217                /*
 218                 * Maybe the containing directory didn't exist, or
 219                 * maybe it was just deleted by a process that is
 220                 * racing with us to clean up empty directories. Try
 221                 * to create it:
 222                 */
 223                enum scld_error scld_result;
 224
 225                if (!path_copy.len)
 226                        strbuf_addstr(&path_copy, path);
 227
 228                do {
 229                        scld_result = safe_create_leading_directories(path_copy.buf);
 230                        if (scld_result == SCLD_OK)
 231                                goto retry_fn;
 232                } while (scld_result == SCLD_VANISHED && create_directories_remaining-- > 0);
 233        }
 234
 235out:
 236        strbuf_release(&path_copy);
 237        errno = save_errno;
 238        return ret;
 239}
 240
 241static void fill_sha1_path(struct strbuf *buf, const unsigned char *sha1)
 242{
 243        int i;
 244        for (i = 0; i < 20; i++) {
 245                static char hex[] = "0123456789abcdef";
 246                unsigned int val = sha1[i];
 247                strbuf_addch(buf, hex[val >> 4]);
 248                strbuf_addch(buf, hex[val & 0xf]);
 249                if (!i)
 250                        strbuf_addch(buf, '/');
 251        }
 252}
 253
 254const char *sha1_file_name(const unsigned char *sha1)
 255{
 256        static struct strbuf buf = STRBUF_INIT;
 257
 258        strbuf_reset(&buf);
 259        strbuf_addf(&buf, "%s/", get_object_directory());
 260
 261        fill_sha1_path(&buf, sha1);
 262        return buf.buf;
 263}
 264
 265struct strbuf *alt_scratch_buf(struct alternate_object_database *alt)
 266{
 267        strbuf_setlen(&alt->scratch, alt->base_len);
 268        return &alt->scratch;
 269}
 270
 271static const char *alt_sha1_path(struct alternate_object_database *alt,
 272                                 const unsigned char *sha1)
 273{
 274        struct strbuf *buf = alt_scratch_buf(alt);
 275        fill_sha1_path(buf, sha1);
 276        return buf->buf;
 277}
 278
 279struct alternate_object_database *alt_odb_list;
 280static struct alternate_object_database **alt_odb_tail;
 281
 282/*
 283 * Return non-zero iff the path is usable as an alternate object database.
 284 */
 285static int alt_odb_usable(struct strbuf *path, const char *normalized_objdir)
 286{
 287        struct alternate_object_database *alt;
 288
 289        /* Detect cases where alternate disappeared */
 290        if (!is_directory(path->buf)) {
 291                error("object directory %s does not exist; "
 292                      "check .git/objects/info/alternates.",
 293                      path->buf);
 294                return 0;
 295        }
 296
 297        /*
 298         * Prevent the common mistake of listing the same
 299         * thing twice, or object directory itself.
 300         */
 301        for (alt = alt_odb_list; alt; alt = alt->next) {
 302                if (!fspathcmp(path->buf, alt->path))
 303                        return 0;
 304        }
 305        if (!fspathcmp(path->buf, normalized_objdir))
 306                return 0;
 307
 308        return 1;
 309}
 310
 311/*
 312 * Prepare alternate object database registry.
 313 *
 314 * The variable alt_odb_list points at the list of struct
 315 * alternate_object_database.  The elements on this list come from
 316 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
 317 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
 318 * whose contents is similar to that environment variable but can be
 319 * LF separated.  Its base points at a statically allocated buffer that
 320 * contains "/the/directory/corresponding/to/.git/objects/...", while
 321 * its name points just after the slash at the end of ".git/objects/"
 322 * in the example above, and has enough space to hold 40-byte hex
 323 * SHA1, an extra slash for the first level indirection, and the
 324 * terminating NUL.
 325 */
 326static void read_info_alternates(const char * relative_base, int depth);
 327static int link_alt_odb_entry(const char *entry, const char *relative_base,
 328        int depth, const char *normalized_objdir)
 329{
 330        struct alternate_object_database *ent;
 331        struct strbuf pathbuf = STRBUF_INIT;
 332
 333        if (!is_absolute_path(entry) && relative_base) {
 334                strbuf_realpath(&pathbuf, relative_base, 1);
 335                strbuf_addch(&pathbuf, '/');
 336        }
 337        strbuf_addstr(&pathbuf, entry);
 338
 339        if (strbuf_normalize_path(&pathbuf) < 0 && relative_base) {
 340                error("unable to normalize alternate object path: %s",
 341                      pathbuf.buf);
 342                strbuf_release(&pathbuf);
 343                return -1;
 344        }
 345
 346        /*
 347         * The trailing slash after the directory name is given by
 348         * this function at the end. Remove duplicates.
 349         */
 350        while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
 351                strbuf_setlen(&pathbuf, pathbuf.len - 1);
 352
 353        if (!alt_odb_usable(&pathbuf, normalized_objdir)) {
 354                strbuf_release(&pathbuf);
 355                return -1;
 356        }
 357
 358        ent = alloc_alt_odb(pathbuf.buf);
 359
 360        /* add the alternate entry */
 361        *alt_odb_tail = ent;
 362        alt_odb_tail = &(ent->next);
 363        ent->next = NULL;
 364
 365        /* recursively add alternates */
 366        read_info_alternates(pathbuf.buf, depth + 1);
 367
 368        strbuf_release(&pathbuf);
 369        return 0;
 370}
 371
 372static const char *parse_alt_odb_entry(const char *string,
 373                                       int sep,
 374                                       struct strbuf *out)
 375{
 376        const char *end;
 377
 378        strbuf_reset(out);
 379
 380        if (*string == '#') {
 381                /* comment; consume up to next separator */
 382                end = strchrnul(string, sep);
 383        } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
 384                /*
 385                 * quoted path; unquote_c_style has copied the
 386                 * data for us and set "end". Broken quoting (e.g.,
 387                 * an entry that doesn't end with a quote) falls
 388                 * back to the unquoted case below.
 389                 */
 390        } else {
 391                /* normal, unquoted path */
 392                end = strchrnul(string, sep);
 393                strbuf_add(out, string, end - string);
 394        }
 395
 396        if (*end)
 397                end++;
 398        return end;
 399}
 400
 401static void link_alt_odb_entries(const char *alt, int len, int sep,
 402                                 const char *relative_base, int depth)
 403{
 404        struct strbuf objdirbuf = STRBUF_INIT;
 405        struct strbuf entry = STRBUF_INIT;
 406
 407        if (depth > 5) {
 408                error("%s: ignoring alternate object stores, nesting too deep.",
 409                                relative_base);
 410                return;
 411        }
 412
 413        strbuf_add_absolute_path(&objdirbuf, get_object_directory());
 414        if (strbuf_normalize_path(&objdirbuf) < 0)
 415                die("unable to normalize object directory: %s",
 416                    objdirbuf.buf);
 417
 418        while (*alt) {
 419                alt = parse_alt_odb_entry(alt, sep, &entry);
 420                if (!entry.len)
 421                        continue;
 422                link_alt_odb_entry(entry.buf, relative_base, depth, objdirbuf.buf);
 423        }
 424        strbuf_release(&entry);
 425        strbuf_release(&objdirbuf);
 426}
 427
 428static void read_info_alternates(const char * relative_base, int depth)
 429{
 430        char *map;
 431        size_t mapsz;
 432        struct stat st;
 433        char *path;
 434        int fd;
 435
 436        path = xstrfmt("%s/info/alternates", relative_base);
 437        fd = git_open(path);
 438        free(path);
 439        if (fd < 0)
 440                return;
 441        if (fstat(fd, &st) || (st.st_size == 0)) {
 442                close(fd);
 443                return;
 444        }
 445        mapsz = xsize_t(st.st_size);
 446        map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
 447        close(fd);
 448
 449        link_alt_odb_entries(map, mapsz, '\n', relative_base, depth);
 450
 451        munmap(map, mapsz);
 452}
 453
 454struct alternate_object_database *alloc_alt_odb(const char *dir)
 455{
 456        struct alternate_object_database *ent;
 457
 458        FLEX_ALLOC_STR(ent, path, dir);
 459        strbuf_init(&ent->scratch, 0);
 460        strbuf_addf(&ent->scratch, "%s/", dir);
 461        ent->base_len = ent->scratch.len;
 462
 463        return ent;
 464}
 465
 466void add_to_alternates_file(const char *reference)
 467{
 468        struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
 469        char *alts = git_pathdup("objects/info/alternates");
 470        FILE *in, *out;
 471
 472        hold_lock_file_for_update(lock, alts, LOCK_DIE_ON_ERROR);
 473        out = fdopen_lock_file(lock, "w");
 474        if (!out)
 475                die_errno("unable to fdopen alternates lockfile");
 476
 477        in = fopen(alts, "r");
 478        if (in) {
 479                struct strbuf line = STRBUF_INIT;
 480                int found = 0;
 481
 482                while (strbuf_getline(&line, in) != EOF) {
 483                        if (!strcmp(reference, line.buf)) {
 484                                found = 1;
 485                                break;
 486                        }
 487                        fprintf_or_die(out, "%s\n", line.buf);
 488                }
 489
 490                strbuf_release(&line);
 491                fclose(in);
 492
 493                if (found) {
 494                        rollback_lock_file(lock);
 495                        lock = NULL;
 496                }
 497        }
 498        else if (errno != ENOENT)
 499                die_errno("unable to read alternates file");
 500
 501        if (lock) {
 502                fprintf_or_die(out, "%s\n", reference);
 503                if (commit_lock_file(lock))
 504                        die_errno("unable to move new alternates file into place");
 505                if (alt_odb_tail)
 506                        link_alt_odb_entries(reference, strlen(reference), '\n', NULL, 0);
 507        }
 508        free(alts);
 509}
 510
 511void add_to_alternates_memory(const char *reference)
 512{
 513        /*
 514         * Make sure alternates are initialized, or else our entry may be
 515         * overwritten when they are.
 516         */
 517        prepare_alt_odb();
 518
 519        link_alt_odb_entries(reference, strlen(reference), '\n', NULL, 0);
 520}
 521
 522/*
 523 * Compute the exact path an alternate is at and returns it. In case of
 524 * error NULL is returned and the human readable error is added to `err`
 525 * `path` may be relative and should point to $GITDIR.
 526 * `err` must not be null.
 527 */
 528char *compute_alternate_path(const char *path, struct strbuf *err)
 529{
 530        char *ref_git = NULL;
 531        const char *repo, *ref_git_s;
 532        int seen_error = 0;
 533
 534        ref_git_s = real_path_if_valid(path);
 535        if (!ref_git_s) {
 536                seen_error = 1;
 537                strbuf_addf(err, _("path '%s' does not exist"), path);
 538                goto out;
 539        } else
 540                /*
 541                 * Beware: read_gitfile(), real_path() and mkpath()
 542                 * return static buffer
 543                 */
 544                ref_git = xstrdup(ref_git_s);
 545
 546        repo = read_gitfile(ref_git);
 547        if (!repo)
 548                repo = read_gitfile(mkpath("%s/.git", ref_git));
 549        if (repo) {
 550                free(ref_git);
 551                ref_git = xstrdup(repo);
 552        }
 553
 554        if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
 555                char *ref_git_git = mkpathdup("%s/.git", ref_git);
 556                free(ref_git);
 557                ref_git = ref_git_git;
 558        } else if (!is_directory(mkpath("%s/objects", ref_git))) {
 559                struct strbuf sb = STRBUF_INIT;
 560                seen_error = 1;
 561                if (get_common_dir(&sb, ref_git)) {
 562                        strbuf_addf(err,
 563                                    _("reference repository '%s' as a linked "
 564                                      "checkout is not supported yet."),
 565                                    path);
 566                        goto out;
 567                }
 568
 569                strbuf_addf(err, _("reference repository '%s' is not a "
 570                                        "local repository."), path);
 571                goto out;
 572        }
 573
 574        if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
 575                strbuf_addf(err, _("reference repository '%s' is shallow"),
 576                            path);
 577                seen_error = 1;
 578                goto out;
 579        }
 580
 581        if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
 582                strbuf_addf(err,
 583                            _("reference repository '%s' is grafted"),
 584                            path);
 585                seen_error = 1;
 586                goto out;
 587        }
 588
 589out:
 590        if (seen_error) {
 591                FREE_AND_NULL(ref_git);
 592        }
 593
 594        return ref_git;
 595}
 596
 597int foreach_alt_odb(alt_odb_fn fn, void *cb)
 598{
 599        struct alternate_object_database *ent;
 600        int r = 0;
 601
 602        prepare_alt_odb();
 603        for (ent = alt_odb_list; ent; ent = ent->next) {
 604                r = fn(ent, cb);
 605                if (r)
 606                        break;
 607        }
 608        return r;
 609}
 610
 611void prepare_alt_odb(void)
 612{
 613        const char *alt;
 614
 615        if (alt_odb_tail)
 616                return;
 617
 618        alt = getenv(ALTERNATE_DB_ENVIRONMENT);
 619        if (!alt) alt = "";
 620
 621        alt_odb_tail = &alt_odb_list;
 622        link_alt_odb_entries(alt, strlen(alt), PATH_SEP, NULL, 0);
 623
 624        read_info_alternates(get_object_directory(), 0);
 625}
 626
 627/* Returns 1 if we have successfully freshened the file, 0 otherwise. */
 628static int freshen_file(const char *fn)
 629{
 630        struct utimbuf t;
 631        t.actime = t.modtime = time(NULL);
 632        return !utime(fn, &t);
 633}
 634
 635/*
 636 * All of the check_and_freshen functions return 1 if the file exists and was
 637 * freshened (if freshening was requested), 0 otherwise. If they return
 638 * 0, you should not assume that it is safe to skip a write of the object (it
 639 * either does not exist on disk, or has a stale mtime and may be subject to
 640 * pruning).
 641 */
 642int check_and_freshen_file(const char *fn, int freshen)
 643{
 644        if (access(fn, F_OK))
 645                return 0;
 646        if (freshen && !freshen_file(fn))
 647                return 0;
 648        return 1;
 649}
 650
 651static int check_and_freshen_local(const unsigned char *sha1, int freshen)
 652{
 653        return check_and_freshen_file(sha1_file_name(sha1), freshen);
 654}
 655
 656static int check_and_freshen_nonlocal(const unsigned char *sha1, int freshen)
 657{
 658        struct alternate_object_database *alt;
 659        prepare_alt_odb();
 660        for (alt = alt_odb_list; alt; alt = alt->next) {
 661                const char *path = alt_sha1_path(alt, sha1);
 662                if (check_and_freshen_file(path, freshen))
 663                        return 1;
 664        }
 665        return 0;
 666}
 667
 668static int check_and_freshen(const unsigned char *sha1, int freshen)
 669{
 670        return check_and_freshen_local(sha1, freshen) ||
 671               check_and_freshen_nonlocal(sha1, freshen);
 672}
 673
 674int has_loose_object_nonlocal(const unsigned char *sha1)
 675{
 676        return check_and_freshen_nonlocal(sha1, 0);
 677}
 678
 679static int has_loose_object(const unsigned char *sha1)
 680{
 681        return check_and_freshen(sha1, 0);
 682}
 683
 684static void mmap_limit_check(size_t length)
 685{
 686        static size_t limit = 0;
 687        if (!limit) {
 688                limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
 689                if (!limit)
 690                        limit = SIZE_MAX;
 691        }
 692        if (length > limit)
 693                die("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX,
 694                    (uintmax_t)length, (uintmax_t)limit);
 695}
 696
 697void *xmmap_gently(void *start, size_t length,
 698                  int prot, int flags, int fd, off_t offset)
 699{
 700        void *ret;
 701
 702        mmap_limit_check(length);
 703        ret = mmap(start, length, prot, flags, fd, offset);
 704        if (ret == MAP_FAILED) {
 705                if (!length)
 706                        return NULL;
 707                release_pack_memory(length);
 708                ret = mmap(start, length, prot, flags, fd, offset);
 709        }
 710        return ret;
 711}
 712
 713void *xmmap(void *start, size_t length,
 714        int prot, int flags, int fd, off_t offset)
 715{
 716        void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
 717        if (ret == MAP_FAILED)
 718                die_errno("mmap failed");
 719        return ret;
 720}
 721
 722void unuse_pack(struct pack_window **w_cursor)
 723{
 724        struct pack_window *w = *w_cursor;
 725        if (w) {
 726                w->inuse_cnt--;
 727                *w_cursor = NULL;
 728        }
 729}
 730
 731static struct packed_git *alloc_packed_git(int extra)
 732{
 733        struct packed_git *p = xmalloc(st_add(sizeof(*p), extra));
 734        memset(p, 0, sizeof(*p));
 735        p->pack_fd = -1;
 736        return p;
 737}
 738
 739static void try_to_free_pack_memory(size_t size)
 740{
 741        release_pack_memory(size);
 742}
 743
 744struct packed_git *add_packed_git(const char *path, size_t path_len, int local)
 745{
 746        static int have_set_try_to_free_routine;
 747        struct stat st;
 748        size_t alloc;
 749        struct packed_git *p;
 750
 751        if (!have_set_try_to_free_routine) {
 752                have_set_try_to_free_routine = 1;
 753                set_try_to_free_routine(try_to_free_pack_memory);
 754        }
 755
 756        /*
 757         * Make sure a corresponding .pack file exists and that
 758         * the index looks sane.
 759         */
 760        if (!strip_suffix_mem(path, &path_len, ".idx"))
 761                return NULL;
 762
 763        /*
 764         * ".pack" is long enough to hold any suffix we're adding (and
 765         * the use xsnprintf double-checks that)
 766         */
 767        alloc = st_add3(path_len, strlen(".pack"), 1);
 768        p = alloc_packed_git(alloc);
 769        memcpy(p->pack_name, path, path_len);
 770
 771        xsnprintf(p->pack_name + path_len, alloc - path_len, ".keep");
 772        if (!access(p->pack_name, F_OK))
 773                p->pack_keep = 1;
 774
 775        xsnprintf(p->pack_name + path_len, alloc - path_len, ".pack");
 776        if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
 777                free(p);
 778                return NULL;
 779        }
 780
 781        /* ok, it looks sane as far as we can check without
 782         * actually mapping the pack file.
 783         */
 784        p->pack_size = st.st_size;
 785        p->pack_local = local;
 786        p->mtime = st.st_mtime;
 787        if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
 788                hashclr(p->sha1);
 789        return p;
 790}
 791
 792void install_packed_git(struct packed_git *pack)
 793{
 794        if (pack->pack_fd != -1)
 795                pack_open_fds++;
 796
 797        pack->next = packed_git;
 798        packed_git = pack;
 799}
 800
 801void (*report_garbage)(unsigned seen_bits, const char *path);
 802
 803static void report_helper(const struct string_list *list,
 804                          int seen_bits, int first, int last)
 805{
 806        if (seen_bits == (PACKDIR_FILE_PACK|PACKDIR_FILE_IDX))
 807                return;
 808
 809        for (; first < last; first++)
 810                report_garbage(seen_bits, list->items[first].string);
 811}
 812
 813static void report_pack_garbage(struct string_list *list)
 814{
 815        int i, baselen = -1, first = 0, seen_bits = 0;
 816
 817        if (!report_garbage)
 818                return;
 819
 820        string_list_sort(list);
 821
 822        for (i = 0; i < list->nr; i++) {
 823                const char *path = list->items[i].string;
 824                if (baselen != -1 &&
 825                    strncmp(path, list->items[first].string, baselen)) {
 826                        report_helper(list, seen_bits, first, i);
 827                        baselen = -1;
 828                        seen_bits = 0;
 829                }
 830                if (baselen == -1) {
 831                        const char *dot = strrchr(path, '.');
 832                        if (!dot) {
 833                                report_garbage(PACKDIR_FILE_GARBAGE, path);
 834                                continue;
 835                        }
 836                        baselen = dot - path + 1;
 837                        first = i;
 838                }
 839                if (!strcmp(path + baselen, "pack"))
 840                        seen_bits |= 1;
 841                else if (!strcmp(path + baselen, "idx"))
 842                        seen_bits |= 2;
 843        }
 844        report_helper(list, seen_bits, first, list->nr);
 845}
 846
 847static void prepare_packed_git_one(char *objdir, int local)
 848{
 849        struct strbuf path = STRBUF_INIT;
 850        size_t dirnamelen;
 851        DIR *dir;
 852        struct dirent *de;
 853        struct string_list garbage = STRING_LIST_INIT_DUP;
 854
 855        strbuf_addstr(&path, objdir);
 856        strbuf_addstr(&path, "/pack");
 857        dir = opendir(path.buf);
 858        if (!dir) {
 859                if (errno != ENOENT)
 860                        error_errno("unable to open object pack directory: %s",
 861                                    path.buf);
 862                strbuf_release(&path);
 863                return;
 864        }
 865        strbuf_addch(&path, '/');
 866        dirnamelen = path.len;
 867        while ((de = readdir(dir)) != NULL) {
 868                struct packed_git *p;
 869                size_t base_len;
 870
 871                if (is_dot_or_dotdot(de->d_name))
 872                        continue;
 873
 874                strbuf_setlen(&path, dirnamelen);
 875                strbuf_addstr(&path, de->d_name);
 876
 877                base_len = path.len;
 878                if (strip_suffix_mem(path.buf, &base_len, ".idx")) {
 879                        /* Don't reopen a pack we already have. */
 880                        for (p = packed_git; p; p = p->next) {
 881                                size_t len;
 882                                if (strip_suffix(p->pack_name, ".pack", &len) &&
 883                                    len == base_len &&
 884                                    !memcmp(p->pack_name, path.buf, len))
 885                                        break;
 886                        }
 887                        if (p == NULL &&
 888                            /*
 889                             * See if it really is a valid .idx file with
 890                             * corresponding .pack file that we can map.
 891                             */
 892                            (p = add_packed_git(path.buf, path.len, local)) != NULL)
 893                                install_packed_git(p);
 894                }
 895
 896                if (!report_garbage)
 897                        continue;
 898
 899                if (ends_with(de->d_name, ".idx") ||
 900                    ends_with(de->d_name, ".pack") ||
 901                    ends_with(de->d_name, ".bitmap") ||
 902                    ends_with(de->d_name, ".keep"))
 903                        string_list_append(&garbage, path.buf);
 904                else
 905                        report_garbage(PACKDIR_FILE_GARBAGE, path.buf);
 906        }
 907        closedir(dir);
 908        report_pack_garbage(&garbage);
 909        string_list_clear(&garbage, 0);
 910        strbuf_release(&path);
 911}
 912
 913static int approximate_object_count_valid;
 914
 915/*
 916 * Give a fast, rough count of the number of objects in the repository. This
 917 * ignores loose objects completely. If you have a lot of them, then either
 918 * you should repack because your performance will be awful, or they are
 919 * all unreachable objects about to be pruned, in which case they're not really
 920 * interesting as a measure of repo size in the first place.
 921 */
 922unsigned long approximate_object_count(void)
 923{
 924        static unsigned long count;
 925        if (!approximate_object_count_valid) {
 926                struct packed_git *p;
 927
 928                prepare_packed_git();
 929                count = 0;
 930                for (p = packed_git; p; p = p->next) {
 931                        if (open_pack_index(p))
 932                                continue;
 933                        count += p->num_objects;
 934                }
 935        }
 936        return count;
 937}
 938
 939static void *get_next_packed_git(const void *p)
 940{
 941        return ((const struct packed_git *)p)->next;
 942}
 943
 944static void set_next_packed_git(void *p, void *next)
 945{
 946        ((struct packed_git *)p)->next = next;
 947}
 948
 949static int sort_pack(const void *a_, const void *b_)
 950{
 951        const struct packed_git *a = a_;
 952        const struct packed_git *b = b_;
 953        int st;
 954
 955        /*
 956         * Local packs tend to contain objects specific to our
 957         * variant of the project than remote ones.  In addition,
 958         * remote ones could be on a network mounted filesystem.
 959         * Favor local ones for these reasons.
 960         */
 961        st = a->pack_local - b->pack_local;
 962        if (st)
 963                return -st;
 964
 965        /*
 966         * Younger packs tend to contain more recent objects,
 967         * and more recent objects tend to get accessed more
 968         * often.
 969         */
 970        if (a->mtime < b->mtime)
 971                return 1;
 972        else if (a->mtime == b->mtime)
 973                return 0;
 974        return -1;
 975}
 976
 977static void rearrange_packed_git(void)
 978{
 979        packed_git = llist_mergesort(packed_git, get_next_packed_git,
 980                                     set_next_packed_git, sort_pack);
 981}
 982
 983static void prepare_packed_git_mru(void)
 984{
 985        struct packed_git *p;
 986
 987        mru_clear(packed_git_mru);
 988        for (p = packed_git; p; p = p->next)
 989                mru_append(packed_git_mru, p);
 990}
 991
 992static int prepare_packed_git_run_once = 0;
 993void prepare_packed_git(void)
 994{
 995        struct alternate_object_database *alt;
 996
 997        if (prepare_packed_git_run_once)
 998                return;
 999        prepare_packed_git_one(get_object_directory(), 1);
1000        prepare_alt_odb();
1001        for (alt = alt_odb_list; alt; alt = alt->next)
1002                prepare_packed_git_one(alt->path, 0);
1003        rearrange_packed_git();
1004        prepare_packed_git_mru();
1005        prepare_packed_git_run_once = 1;
1006}
1007
1008void reprepare_packed_git(void)
1009{
1010        approximate_object_count_valid = 0;
1011        prepare_packed_git_run_once = 0;
1012        prepare_packed_git();
1013}
1014
1015static void mark_bad_packed_object(struct packed_git *p,
1016                                   const unsigned char *sha1)
1017{
1018        unsigned i;
1019        for (i = 0; i < p->num_bad_objects; i++)
1020                if (!hashcmp(sha1, p->bad_object_sha1 + GIT_SHA1_RAWSZ * i))
1021                        return;
1022        p->bad_object_sha1 = xrealloc(p->bad_object_sha1,
1023                                      st_mult(GIT_MAX_RAWSZ,
1024                                              st_add(p->num_bad_objects, 1)));
1025        hashcpy(p->bad_object_sha1 + GIT_SHA1_RAWSZ * p->num_bad_objects, sha1);
1026        p->num_bad_objects++;
1027}
1028
1029static const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
1030{
1031        struct packed_git *p;
1032        unsigned i;
1033
1034        for (p = packed_git; p; p = p->next)
1035                for (i = 0; i < p->num_bad_objects; i++)
1036                        if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1037                                return p;
1038        return NULL;
1039}
1040
1041/*
1042 * With an in-core object data in "map", rehash it to make sure the
1043 * object name actually matches "sha1" to detect object corruption.
1044 * With "map" == NULL, try reading the object named with "sha1" using
1045 * the streaming interface and rehash it to do the same.
1046 */
1047int check_sha1_signature(const unsigned char *sha1, void *map,
1048                         unsigned long size, const char *type)
1049{
1050        unsigned char real_sha1[20];
1051        enum object_type obj_type;
1052        struct git_istream *st;
1053        git_SHA_CTX c;
1054        char hdr[32];
1055        int hdrlen;
1056
1057        if (map) {
1058                hash_sha1_file(map, size, type, real_sha1);
1059                return hashcmp(sha1, real_sha1) ? -1 : 0;
1060        }
1061
1062        st = open_istream(sha1, &obj_type, &size, NULL);
1063        if (!st)
1064                return -1;
1065
1066        /* Generate the header */
1067        hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(obj_type), size) + 1;
1068
1069        /* Sha1.. */
1070        git_SHA1_Init(&c);
1071        git_SHA1_Update(&c, hdr, hdrlen);
1072        for (;;) {
1073                char buf[1024 * 16];
1074                ssize_t readlen = read_istream(st, buf, sizeof(buf));
1075
1076                if (readlen < 0) {
1077                        close_istream(st);
1078                        return -1;
1079                }
1080                if (!readlen)
1081                        break;
1082                git_SHA1_Update(&c, buf, readlen);
1083        }
1084        git_SHA1_Final(real_sha1, &c);
1085        close_istream(st);
1086        return hashcmp(sha1, real_sha1) ? -1 : 0;
1087}
1088
1089int git_open_cloexec(const char *name, int flags)
1090{
1091        int fd;
1092        static int o_cloexec = O_CLOEXEC;
1093
1094        fd = open(name, flags | o_cloexec);
1095        if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
1096                /* Try again w/o O_CLOEXEC: the kernel might not support it */
1097                o_cloexec &= ~O_CLOEXEC;
1098                fd = open(name, flags | o_cloexec);
1099        }
1100
1101#if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
1102        {
1103                static int fd_cloexec = FD_CLOEXEC;
1104
1105                if (!o_cloexec && 0 <= fd && fd_cloexec) {
1106                        /* Opened w/o O_CLOEXEC?  try with fcntl(2) to add it */
1107                        int flags = fcntl(fd, F_GETFD);
1108                        if (fcntl(fd, F_SETFD, flags | fd_cloexec))
1109                                fd_cloexec = 0;
1110                }
1111        }
1112#endif
1113        return fd;
1114}
1115
1116/*
1117 * Find "sha1" as a loose object in the local repository or in an alternate.
1118 * Returns 0 on success, negative on failure.
1119 *
1120 * The "path" out-parameter will give the path of the object we found (if any).
1121 * Note that it may point to static storage and is only valid until another
1122 * call to sha1_file_name(), etc.
1123 */
1124static int stat_sha1_file(const unsigned char *sha1, struct stat *st,
1125                          const char **path)
1126{
1127        struct alternate_object_database *alt;
1128
1129        *path = sha1_file_name(sha1);
1130        if (!lstat(*path, st))
1131                return 0;
1132
1133        prepare_alt_odb();
1134        errno = ENOENT;
1135        for (alt = alt_odb_list; alt; alt = alt->next) {
1136                *path = alt_sha1_path(alt, sha1);
1137                if (!lstat(*path, st))
1138                        return 0;
1139        }
1140
1141        return -1;
1142}
1143
1144/*
1145 * Like stat_sha1_file(), but actually open the object and return the
1146 * descriptor. See the caveats on the "path" parameter above.
1147 */
1148static int open_sha1_file(const unsigned char *sha1, const char **path)
1149{
1150        int fd;
1151        struct alternate_object_database *alt;
1152        int most_interesting_errno;
1153
1154        *path = sha1_file_name(sha1);
1155        fd = git_open(*path);
1156        if (fd >= 0)
1157                return fd;
1158        most_interesting_errno = errno;
1159
1160        prepare_alt_odb();
1161        for (alt = alt_odb_list; alt; alt = alt->next) {
1162                *path = alt_sha1_path(alt, sha1);
1163                fd = git_open(*path);
1164                if (fd >= 0)
1165                        return fd;
1166                if (most_interesting_errno == ENOENT)
1167                        most_interesting_errno = errno;
1168        }
1169        errno = most_interesting_errno;
1170        return -1;
1171}
1172
1173/*
1174 * Map the loose object at "path" if it is not NULL, or the path found by
1175 * searching for a loose object named "sha1".
1176 */
1177static void *map_sha1_file_1(const char *path,
1178                             const unsigned char *sha1,
1179                             unsigned long *size)
1180{
1181        void *map;
1182        int fd;
1183
1184        if (path)
1185                fd = git_open(path);
1186        else
1187                fd = open_sha1_file(sha1, &path);
1188        map = NULL;
1189        if (fd >= 0) {
1190                struct stat st;
1191
1192                if (!fstat(fd, &st)) {
1193                        *size = xsize_t(st.st_size);
1194                        if (!*size) {
1195                                /* mmap() is forbidden on empty files */
1196                                error("object file %s is empty", path);
1197                                return NULL;
1198                        }
1199                        map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1200                }
1201                close(fd);
1202        }
1203        return map;
1204}
1205
1206void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1207{
1208        return map_sha1_file_1(NULL, sha1, size);
1209}
1210
1211unsigned long unpack_object_header_buffer(const unsigned char *buf,
1212                unsigned long len, enum object_type *type, unsigned long *sizep)
1213{
1214        unsigned shift;
1215        unsigned long size, c;
1216        unsigned long used = 0;
1217
1218        c = buf[used++];
1219        *type = (c >> 4) & 7;
1220        size = c & 15;
1221        shift = 4;
1222        while (c & 0x80) {
1223                if (len <= used || bitsizeof(long) <= shift) {
1224                        error("bad object header");
1225                        size = used = 0;
1226                        break;
1227                }
1228                c = buf[used++];
1229                size += (c & 0x7f) << shift;
1230                shift += 7;
1231        }
1232        *sizep = size;
1233        return used;
1234}
1235
1236static int unpack_sha1_short_header(git_zstream *stream,
1237                                    unsigned char *map, unsigned long mapsize,
1238                                    void *buffer, unsigned long bufsiz)
1239{
1240        /* Get the data stream */
1241        memset(stream, 0, sizeof(*stream));
1242        stream->next_in = map;
1243        stream->avail_in = mapsize;
1244        stream->next_out = buffer;
1245        stream->avail_out = bufsiz;
1246
1247        git_inflate_init(stream);
1248        return git_inflate(stream, 0);
1249}
1250
1251int unpack_sha1_header(git_zstream *stream,
1252                       unsigned char *map, unsigned long mapsize,
1253                       void *buffer, unsigned long bufsiz)
1254{
1255        int status = unpack_sha1_short_header(stream, map, mapsize,
1256                                              buffer, bufsiz);
1257
1258        if (status < Z_OK)
1259                return status;
1260
1261        /* Make sure we have the terminating NUL */
1262        if (!memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1263                return -1;
1264        return 0;
1265}
1266
1267static int unpack_sha1_header_to_strbuf(git_zstream *stream, unsigned char *map,
1268                                        unsigned long mapsize, void *buffer,
1269                                        unsigned long bufsiz, struct strbuf *header)
1270{
1271        int status;
1272
1273        status = unpack_sha1_short_header(stream, map, mapsize, buffer, bufsiz);
1274        if (status < Z_OK)
1275                return -1;
1276
1277        /*
1278         * Check if entire header is unpacked in the first iteration.
1279         */
1280        if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1281                return 0;
1282
1283        /*
1284         * buffer[0..bufsiz] was not large enough.  Copy the partial
1285         * result out to header, and then append the result of further
1286         * reading the stream.
1287         */
1288        strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1289        stream->next_out = buffer;
1290        stream->avail_out = bufsiz;
1291
1292        do {
1293                status = git_inflate(stream, 0);
1294                strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1295                if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1296                        return 0;
1297                stream->next_out = buffer;
1298                stream->avail_out = bufsiz;
1299        } while (status != Z_STREAM_END);
1300        return -1;
1301}
1302
1303static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1304{
1305        int bytes = strlen(buffer) + 1;
1306        unsigned char *buf = xmallocz(size);
1307        unsigned long n;
1308        int status = Z_OK;
1309
1310        n = stream->total_out - bytes;
1311        if (n > size)
1312                n = size;
1313        memcpy(buf, (char *) buffer + bytes, n);
1314        bytes = n;
1315        if (bytes <= size) {
1316                /*
1317                 * The above condition must be (bytes <= size), not
1318                 * (bytes < size).  In other words, even though we
1319                 * expect no more output and set avail_out to zero,
1320                 * the input zlib stream may have bytes that express
1321                 * "this concludes the stream", and we *do* want to
1322                 * eat that input.
1323                 *
1324                 * Otherwise we would not be able to test that we
1325                 * consumed all the input to reach the expected size;
1326                 * we also want to check that zlib tells us that all
1327                 * went well with status == Z_STREAM_END at the end.
1328                 */
1329                stream->next_out = buf + bytes;
1330                stream->avail_out = size - bytes;
1331                while (status == Z_OK)
1332                        status = git_inflate(stream, Z_FINISH);
1333        }
1334        if (status == Z_STREAM_END && !stream->avail_in) {
1335                git_inflate_end(stream);
1336                return buf;
1337        }
1338
1339        if (status < 0)
1340                error("corrupt loose object '%s'", sha1_to_hex(sha1));
1341        else if (stream->avail_in)
1342                error("garbage at end of loose object '%s'",
1343                      sha1_to_hex(sha1));
1344        free(buf);
1345        return NULL;
1346}
1347
1348/*
1349 * We used to just use "sscanf()", but that's actually way
1350 * too permissive for what we want to check. So do an anal
1351 * object header parse by hand.
1352 */
1353static int parse_sha1_header_extended(const char *hdr, struct object_info *oi,
1354                               unsigned int flags)
1355{
1356        const char *type_buf = hdr;
1357        unsigned long size;
1358        int type, type_len = 0;
1359
1360        /*
1361         * The type can be of any size but is followed by
1362         * a space.
1363         */
1364        for (;;) {
1365                char c = *hdr++;
1366                if (!c)
1367                        return -1;
1368                if (c == ' ')
1369                        break;
1370                type_len++;
1371        }
1372
1373        type = type_from_string_gently(type_buf, type_len, 1);
1374        if (oi->typename)
1375                strbuf_add(oi->typename, type_buf, type_len);
1376        /*
1377         * Set type to 0 if its an unknown object and
1378         * we're obtaining the type using '--allow-unknown-type'
1379         * option.
1380         */
1381        if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE) && (type < 0))
1382                type = 0;
1383        else if (type < 0)
1384                die("invalid object type");
1385        if (oi->typep)
1386                *oi->typep = type;
1387
1388        /*
1389         * The length must follow immediately, and be in canonical
1390         * decimal format (ie "010" is not valid).
1391         */
1392        size = *hdr++ - '0';
1393        if (size > 9)
1394                return -1;
1395        if (size) {
1396                for (;;) {
1397                        unsigned long c = *hdr - '0';
1398                        if (c > 9)
1399                                break;
1400                        hdr++;
1401                        size = size * 10 + c;
1402                }
1403        }
1404
1405        if (oi->sizep)
1406                *oi->sizep = size;
1407
1408        /*
1409         * The length must be followed by a zero byte
1410         */
1411        return *hdr ? -1 : type;
1412}
1413
1414int parse_sha1_header(const char *hdr, unsigned long *sizep)
1415{
1416        struct object_info oi = OBJECT_INFO_INIT;
1417
1418        oi.sizep = sizep;
1419        return parse_sha1_header_extended(hdr, &oi, 0);
1420}
1421
1422unsigned long get_size_from_delta(struct packed_git *p,
1423                                  struct pack_window **w_curs,
1424                                  off_t curpos)
1425{
1426        const unsigned char *data;
1427        unsigned char delta_head[20], *in;
1428        git_zstream stream;
1429        int st;
1430
1431        memset(&stream, 0, sizeof(stream));
1432        stream.next_out = delta_head;
1433        stream.avail_out = sizeof(delta_head);
1434
1435        git_inflate_init(&stream);
1436        do {
1437                in = use_pack(p, w_curs, curpos, &stream.avail_in);
1438                stream.next_in = in;
1439                st = git_inflate(&stream, Z_FINISH);
1440                curpos += stream.next_in - in;
1441        } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1442                 stream.total_out < sizeof(delta_head));
1443        git_inflate_end(&stream);
1444        if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1445                error("delta data unpack-initial failed");
1446                return 0;
1447        }
1448
1449        /* Examine the initial part of the delta to figure out
1450         * the result size.
1451         */
1452        data = delta_head;
1453
1454        /* ignore base size */
1455        get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1456
1457        /* Read the result size */
1458        return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1459}
1460
1461static off_t get_delta_base(struct packed_git *p,
1462                                    struct pack_window **w_curs,
1463                                    off_t *curpos,
1464                                    enum object_type type,
1465                                    off_t delta_obj_offset)
1466{
1467        unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1468        off_t base_offset;
1469
1470        /* use_pack() assured us we have [base_info, base_info + 20)
1471         * as a range that we can look at without walking off the
1472         * end of the mapped window.  Its actually the hash size
1473         * that is assured.  An OFS_DELTA longer than the hash size
1474         * is stupid, as then a REF_DELTA would be smaller to store.
1475         */
1476        if (type == OBJ_OFS_DELTA) {
1477                unsigned used = 0;
1478                unsigned char c = base_info[used++];
1479                base_offset = c & 127;
1480                while (c & 128) {
1481                        base_offset += 1;
1482                        if (!base_offset || MSB(base_offset, 7))
1483                                return 0;  /* overflow */
1484                        c = base_info[used++];
1485                        base_offset = (base_offset << 7) + (c & 127);
1486                }
1487                base_offset = delta_obj_offset - base_offset;
1488                if (base_offset <= 0 || base_offset >= delta_obj_offset)
1489                        return 0;  /* out of bound */
1490                *curpos += used;
1491        } else if (type == OBJ_REF_DELTA) {
1492                /* The base entry _must_ be in the same pack */
1493                base_offset = find_pack_entry_one(base_info, p);
1494                *curpos += 20;
1495        } else
1496                die("I am totally screwed");
1497        return base_offset;
1498}
1499
1500/*
1501 * Like get_delta_base above, but we return the sha1 instead of the pack
1502 * offset. This means it is cheaper for REF deltas (we do not have to do
1503 * the final object lookup), but more expensive for OFS deltas (we
1504 * have to load the revidx to convert the offset back into a sha1).
1505 */
1506static const unsigned char *get_delta_base_sha1(struct packed_git *p,
1507                                                struct pack_window **w_curs,
1508                                                off_t curpos,
1509                                                enum object_type type,
1510                                                off_t delta_obj_offset)
1511{
1512        if (type == OBJ_REF_DELTA) {
1513                unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1514                return base;
1515        } else if (type == OBJ_OFS_DELTA) {
1516                struct revindex_entry *revidx;
1517                off_t base_offset = get_delta_base(p, w_curs, &curpos,
1518                                                   type, delta_obj_offset);
1519
1520                if (!base_offset)
1521                        return NULL;
1522
1523                revidx = find_pack_revindex(p, base_offset);
1524                if (!revidx)
1525                        return NULL;
1526
1527                return nth_packed_object_sha1(p, revidx->nr);
1528        } else
1529                return NULL;
1530}
1531
1532int unpack_object_header(struct packed_git *p,
1533                         struct pack_window **w_curs,
1534                         off_t *curpos,
1535                         unsigned long *sizep)
1536{
1537        unsigned char *base;
1538        unsigned long left;
1539        unsigned long used;
1540        enum object_type type;
1541
1542        /* use_pack() assures us we have [base, base + 20) available
1543         * as a range that we can look at.  (Its actually the hash
1544         * size that is assured.)  With our object header encoding
1545         * the maximum deflated object size is 2^137, which is just
1546         * insane, so we know won't exceed what we have been given.
1547         */
1548        base = use_pack(p, w_curs, *curpos, &left);
1549        used = unpack_object_header_buffer(base, left, &type, sizep);
1550        if (!used) {
1551                type = OBJ_BAD;
1552        } else
1553                *curpos += used;
1554
1555        return type;
1556}
1557
1558static int retry_bad_packed_offset(struct packed_git *p, off_t obj_offset)
1559{
1560        int type;
1561        struct revindex_entry *revidx;
1562        const unsigned char *sha1;
1563        revidx = find_pack_revindex(p, obj_offset);
1564        if (!revidx)
1565                return OBJ_BAD;
1566        sha1 = nth_packed_object_sha1(p, revidx->nr);
1567        mark_bad_packed_object(p, sha1);
1568        type = sha1_object_info(sha1, NULL);
1569        if (type <= OBJ_NONE)
1570                return OBJ_BAD;
1571        return type;
1572}
1573
1574#define POI_STACK_PREALLOC 64
1575
1576static enum object_type packed_to_object_type(struct packed_git *p,
1577                                              off_t obj_offset,
1578                                              enum object_type type,
1579                                              struct pack_window **w_curs,
1580                                              off_t curpos)
1581{
1582        off_t small_poi_stack[POI_STACK_PREALLOC];
1583        off_t *poi_stack = small_poi_stack;
1584        int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1585
1586        while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1587                off_t base_offset;
1588                unsigned long size;
1589                /* Push the object we're going to leave behind */
1590                if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1591                        poi_stack_alloc = alloc_nr(poi_stack_nr);
1592                        ALLOC_ARRAY(poi_stack, poi_stack_alloc);
1593                        memcpy(poi_stack, small_poi_stack, sizeof(off_t)*poi_stack_nr);
1594                } else {
1595                        ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1596                }
1597                poi_stack[poi_stack_nr++] = obj_offset;
1598                /* If parsing the base offset fails, just unwind */
1599                base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1600                if (!base_offset)
1601                        goto unwind;
1602                curpos = obj_offset = base_offset;
1603                type = unpack_object_header(p, w_curs, &curpos, &size);
1604                if (type <= OBJ_NONE) {
1605                        /* If getting the base itself fails, we first
1606                         * retry the base, otherwise unwind */
1607                        type = retry_bad_packed_offset(p, base_offset);
1608                        if (type > OBJ_NONE)
1609                                goto out;
1610                        goto unwind;
1611                }
1612        }
1613
1614        switch (type) {
1615        case OBJ_BAD:
1616        case OBJ_COMMIT:
1617        case OBJ_TREE:
1618        case OBJ_BLOB:
1619        case OBJ_TAG:
1620                break;
1621        default:
1622                error("unknown object type %i at offset %"PRIuMAX" in %s",
1623                      type, (uintmax_t)obj_offset, p->pack_name);
1624                type = OBJ_BAD;
1625        }
1626
1627out:
1628        if (poi_stack != small_poi_stack)
1629                free(poi_stack);
1630        return type;
1631
1632unwind:
1633        while (poi_stack_nr) {
1634                obj_offset = poi_stack[--poi_stack_nr];
1635                type = retry_bad_packed_offset(p, obj_offset);
1636                if (type > OBJ_NONE)
1637                        goto out;
1638        }
1639        type = OBJ_BAD;
1640        goto out;
1641}
1642
1643static struct hashmap delta_base_cache;
1644static size_t delta_base_cached;
1645
1646static LIST_HEAD(delta_base_cache_lru);
1647
1648struct delta_base_cache_key {
1649        struct packed_git *p;
1650        off_t base_offset;
1651};
1652
1653struct delta_base_cache_entry {
1654        struct hashmap hash;
1655        struct delta_base_cache_key key;
1656        struct list_head lru;
1657        void *data;
1658        unsigned long size;
1659        enum object_type type;
1660};
1661
1662static unsigned int pack_entry_hash(struct packed_git *p, off_t base_offset)
1663{
1664        unsigned int hash;
1665
1666        hash = (unsigned int)(intptr_t)p + (unsigned int)base_offset;
1667        hash += (hash >> 8) + (hash >> 16);
1668        return hash;
1669}
1670
1671static struct delta_base_cache_entry *
1672get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
1673{
1674        struct hashmap_entry entry;
1675        struct delta_base_cache_key key;
1676
1677        if (!delta_base_cache.cmpfn)
1678                return NULL;
1679
1680        hashmap_entry_init(&entry, pack_entry_hash(p, base_offset));
1681        key.p = p;
1682        key.base_offset = base_offset;
1683        return hashmap_get(&delta_base_cache, &entry, &key);
1684}
1685
1686static int delta_base_cache_key_eq(const struct delta_base_cache_key *a,
1687                                   const struct delta_base_cache_key *b)
1688{
1689        return a->p == b->p && a->base_offset == b->base_offset;
1690}
1691
1692static int delta_base_cache_hash_cmp(const void *unused_cmp_data,
1693                                     const void *va, const void *vb,
1694                                     const void *vkey)
1695{
1696        const struct delta_base_cache_entry *a = va, *b = vb;
1697        const struct delta_base_cache_key *key = vkey;
1698        if (key)
1699                return !delta_base_cache_key_eq(&a->key, key);
1700        else
1701                return !delta_base_cache_key_eq(&a->key, &b->key);
1702}
1703
1704static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
1705{
1706        return !!get_delta_base_cache_entry(p, base_offset);
1707}
1708
1709/*
1710 * Remove the entry from the cache, but do _not_ free the associated
1711 * entry data. The caller takes ownership of the "data" buffer, and
1712 * should copy out any fields it wants before detaching.
1713 */
1714static void detach_delta_base_cache_entry(struct delta_base_cache_entry *ent)
1715{
1716        hashmap_remove(&delta_base_cache, ent, &ent->key);
1717        list_del(&ent->lru);
1718        delta_base_cached -= ent->size;
1719        free(ent);
1720}
1721
1722static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
1723        unsigned long *base_size, enum object_type *type)
1724{
1725        struct delta_base_cache_entry *ent;
1726
1727        ent = get_delta_base_cache_entry(p, base_offset);
1728        if (!ent)
1729                return unpack_entry(p, base_offset, type, base_size);
1730
1731        if (type)
1732                *type = ent->type;
1733        if (base_size)
1734                *base_size = ent->size;
1735        return xmemdupz(ent->data, ent->size);
1736}
1737
1738static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1739{
1740        free(ent->data);
1741        detach_delta_base_cache_entry(ent);
1742}
1743
1744void clear_delta_base_cache(void)
1745{
1746        struct list_head *lru, *tmp;
1747        list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1748                struct delta_base_cache_entry *entry =
1749                        list_entry(lru, struct delta_base_cache_entry, lru);
1750                release_delta_base_cache(entry);
1751        }
1752}
1753
1754static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1755        void *base, unsigned long base_size, enum object_type type)
1756{
1757        struct delta_base_cache_entry *ent = xmalloc(sizeof(*ent));
1758        struct list_head *lru, *tmp;
1759
1760        delta_base_cached += base_size;
1761
1762        list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1763                struct delta_base_cache_entry *f =
1764                        list_entry(lru, struct delta_base_cache_entry, lru);
1765                if (delta_base_cached <= delta_base_cache_limit)
1766                        break;
1767                release_delta_base_cache(f);
1768        }
1769
1770        ent->key.p = p;
1771        ent->key.base_offset = base_offset;
1772        ent->type = type;
1773        ent->data = base;
1774        ent->size = base_size;
1775        list_add_tail(&ent->lru, &delta_base_cache_lru);
1776
1777        if (!delta_base_cache.cmpfn)
1778                hashmap_init(&delta_base_cache, delta_base_cache_hash_cmp, NULL, 0);
1779        hashmap_entry_init(ent, pack_entry_hash(p, base_offset));
1780        hashmap_add(&delta_base_cache, ent);
1781}
1782
1783int packed_object_info(struct packed_git *p, off_t obj_offset,
1784                       struct object_info *oi)
1785{
1786        struct pack_window *w_curs = NULL;
1787        unsigned long size;
1788        off_t curpos = obj_offset;
1789        enum object_type type;
1790
1791        /*
1792         * We always get the representation type, but only convert it to
1793         * a "real" type later if the caller is interested.
1794         */
1795        if (oi->contentp) {
1796                *oi->contentp = cache_or_unpack_entry(p, obj_offset, oi->sizep,
1797                                                      &type);
1798                if (!*oi->contentp)
1799                        type = OBJ_BAD;
1800        } else {
1801                type = unpack_object_header(p, &w_curs, &curpos, &size);
1802        }
1803
1804        if (!oi->contentp && oi->sizep) {
1805                if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1806                        off_t tmp_pos = curpos;
1807                        off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1808                                                           type, obj_offset);
1809                        if (!base_offset) {
1810                                type = OBJ_BAD;
1811                                goto out;
1812                        }
1813                        *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
1814                        if (*oi->sizep == 0) {
1815                                type = OBJ_BAD;
1816                                goto out;
1817                        }
1818                } else {
1819                        *oi->sizep = size;
1820                }
1821        }
1822
1823        if (oi->disk_sizep) {
1824                struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1825                *oi->disk_sizep = revidx[1].offset - obj_offset;
1826        }
1827
1828        if (oi->typep || oi->typename) {
1829                enum object_type ptot;
1830                ptot = packed_to_object_type(p, obj_offset, type, &w_curs,
1831                                             curpos);
1832                if (oi->typep)
1833                        *oi->typep = ptot;
1834                if (oi->typename) {
1835                        const char *tn = typename(ptot);
1836                        if (tn)
1837                                strbuf_addstr(oi->typename, tn);
1838                }
1839                if (ptot < 0) {
1840                        type = OBJ_BAD;
1841                        goto out;
1842                }
1843        }
1844
1845        if (oi->delta_base_sha1) {
1846                if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1847                        const unsigned char *base;
1848
1849                        base = get_delta_base_sha1(p, &w_curs, curpos,
1850                                                   type, obj_offset);
1851                        if (!base) {
1852                                type = OBJ_BAD;
1853                                goto out;
1854                        }
1855
1856                        hashcpy(oi->delta_base_sha1, base);
1857                } else
1858                        hashclr(oi->delta_base_sha1);
1859        }
1860
1861        oi->whence = in_delta_base_cache(p, obj_offset) ? OI_DBCACHED :
1862                                                          OI_PACKED;
1863
1864out:
1865        unuse_pack(&w_curs);
1866        return type;
1867}
1868
1869static void *unpack_compressed_entry(struct packed_git *p,
1870                                    struct pack_window **w_curs,
1871                                    off_t curpos,
1872                                    unsigned long size)
1873{
1874        int st;
1875        git_zstream stream;
1876        unsigned char *buffer, *in;
1877
1878        buffer = xmallocz_gently(size);
1879        if (!buffer)
1880                return NULL;
1881        memset(&stream, 0, sizeof(stream));
1882        stream.next_out = buffer;
1883        stream.avail_out = size + 1;
1884
1885        git_inflate_init(&stream);
1886        do {
1887                in = use_pack(p, w_curs, curpos, &stream.avail_in);
1888                stream.next_in = in;
1889                st = git_inflate(&stream, Z_FINISH);
1890                if (!stream.avail_out)
1891                        break; /* the payload is larger than it should be */
1892                curpos += stream.next_in - in;
1893        } while (st == Z_OK || st == Z_BUF_ERROR);
1894        git_inflate_end(&stream);
1895        if ((st != Z_STREAM_END) || stream.total_out != size) {
1896                free(buffer);
1897                return NULL;
1898        }
1899
1900        return buffer;
1901}
1902
1903static void *read_object(const unsigned char *sha1, enum object_type *type,
1904                         unsigned long *size);
1905
1906static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
1907{
1908        static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
1909        trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
1910                         p->pack_name, (uintmax_t)obj_offset);
1911}
1912
1913int do_check_packed_object_crc;
1914
1915#define UNPACK_ENTRY_STACK_PREALLOC 64
1916struct unpack_entry_stack_ent {
1917        off_t obj_offset;
1918        off_t curpos;
1919        unsigned long size;
1920};
1921
1922void *unpack_entry(struct packed_git *p, off_t obj_offset,
1923                   enum object_type *final_type, unsigned long *final_size)
1924{
1925        struct pack_window *w_curs = NULL;
1926        off_t curpos = obj_offset;
1927        void *data = NULL;
1928        unsigned long size;
1929        enum object_type type;
1930        struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
1931        struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
1932        int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
1933        int base_from_cache = 0;
1934
1935        write_pack_access_log(p, obj_offset);
1936
1937        /* PHASE 1: drill down to the innermost base object */
1938        for (;;) {
1939                off_t base_offset;
1940                int i;
1941                struct delta_base_cache_entry *ent;
1942
1943                ent = get_delta_base_cache_entry(p, curpos);
1944                if (ent) {
1945                        type = ent->type;
1946                        data = ent->data;
1947                        size = ent->size;
1948                        detach_delta_base_cache_entry(ent);
1949                        base_from_cache = 1;
1950                        break;
1951                }
1952
1953                if (do_check_packed_object_crc && p->index_version > 1) {
1954                        struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1955                        off_t len = revidx[1].offset - obj_offset;
1956                        if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
1957                                const unsigned char *sha1 =
1958                                        nth_packed_object_sha1(p, revidx->nr);
1959                                error("bad packed object CRC for %s",
1960                                      sha1_to_hex(sha1));
1961                                mark_bad_packed_object(p, sha1);
1962                                data = NULL;
1963                                goto out;
1964                        }
1965                }
1966
1967                type = unpack_object_header(p, &w_curs, &curpos, &size);
1968                if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
1969                        break;
1970
1971                base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1972                if (!base_offset) {
1973                        error("failed to validate delta base reference "
1974                              "at offset %"PRIuMAX" from %s",
1975                              (uintmax_t)curpos, p->pack_name);
1976                        /* bail to phase 2, in hopes of recovery */
1977                        data = NULL;
1978                        break;
1979                }
1980
1981                /* push object, proceed to base */
1982                if (delta_stack_nr >= delta_stack_alloc
1983                    && delta_stack == small_delta_stack) {
1984                        delta_stack_alloc = alloc_nr(delta_stack_nr);
1985                        ALLOC_ARRAY(delta_stack, delta_stack_alloc);
1986                        memcpy(delta_stack, small_delta_stack,
1987                               sizeof(*delta_stack)*delta_stack_nr);
1988                } else {
1989                        ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
1990                }
1991                i = delta_stack_nr++;
1992                delta_stack[i].obj_offset = obj_offset;
1993                delta_stack[i].curpos = curpos;
1994                delta_stack[i].size = size;
1995
1996                curpos = obj_offset = base_offset;
1997        }
1998
1999        /* PHASE 2: handle the base */
2000        switch (type) {
2001        case OBJ_OFS_DELTA:
2002        case OBJ_REF_DELTA:
2003                if (data)
2004                        die("BUG: unpack_entry: left loop at a valid delta");
2005                break;
2006        case OBJ_COMMIT:
2007        case OBJ_TREE:
2008        case OBJ_BLOB:
2009        case OBJ_TAG:
2010                if (!base_from_cache)
2011                        data = unpack_compressed_entry(p, &w_curs, curpos, size);
2012                break;
2013        default:
2014                data = NULL;
2015                error("unknown object type %i at offset %"PRIuMAX" in %s",
2016                      type, (uintmax_t)obj_offset, p->pack_name);
2017        }
2018
2019        /* PHASE 3: apply deltas in order */
2020
2021        /* invariants:
2022         *   'data' holds the base data, or NULL if there was corruption
2023         */
2024        while (delta_stack_nr) {
2025                void *delta_data;
2026                void *base = data;
2027                void *external_base = NULL;
2028                unsigned long delta_size, base_size = size;
2029                int i;
2030
2031                data = NULL;
2032
2033                if (base)
2034                        add_delta_base_cache(p, obj_offset, base, base_size, type);
2035
2036                if (!base) {
2037                        /*
2038                         * We're probably in deep shit, but let's try to fetch
2039                         * the required base anyway from another pack or loose.
2040                         * This is costly but should happen only in the presence
2041                         * of a corrupted pack, and is better than failing outright.
2042                         */
2043                        struct revindex_entry *revidx;
2044                        const unsigned char *base_sha1;
2045                        revidx = find_pack_revindex(p, obj_offset);
2046                        if (revidx) {
2047                                base_sha1 = nth_packed_object_sha1(p, revidx->nr);
2048                                error("failed to read delta base object %s"
2049                                      " at offset %"PRIuMAX" from %s",
2050                                      sha1_to_hex(base_sha1), (uintmax_t)obj_offset,
2051                                      p->pack_name);
2052                                mark_bad_packed_object(p, base_sha1);
2053                                base = read_object(base_sha1, &type, &base_size);
2054                                external_base = base;
2055                        }
2056                }
2057
2058                i = --delta_stack_nr;
2059                obj_offset = delta_stack[i].obj_offset;
2060                curpos = delta_stack[i].curpos;
2061                delta_size = delta_stack[i].size;
2062
2063                if (!base)
2064                        continue;
2065
2066                delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
2067
2068                if (!delta_data) {
2069                        error("failed to unpack compressed delta "
2070                              "at offset %"PRIuMAX" from %s",
2071                              (uintmax_t)curpos, p->pack_name);
2072                        data = NULL;
2073                        free(external_base);
2074                        continue;
2075                }
2076
2077                data = patch_delta(base, base_size,
2078                                   delta_data, delta_size,
2079                                   &size);
2080
2081                /*
2082                 * We could not apply the delta; warn the user, but keep going.
2083                 * Our failure will be noticed either in the next iteration of
2084                 * the loop, or if this is the final delta, in the caller when
2085                 * we return NULL. Those code paths will take care of making
2086                 * a more explicit warning and retrying with another copy of
2087                 * the object.
2088                 */
2089                if (!data)
2090                        error("failed to apply delta");
2091
2092                free(delta_data);
2093                free(external_base);
2094        }
2095
2096        if (final_type)
2097                *final_type = type;
2098        if (final_size)
2099                *final_size = size;
2100
2101out:
2102        unuse_pack(&w_curs);
2103
2104        if (delta_stack != small_delta_stack)
2105                free(delta_stack);
2106
2107        return data;
2108}
2109
2110const unsigned char *nth_packed_object_sha1(struct packed_git *p,
2111                                            uint32_t n)
2112{
2113        const unsigned char *index = p->index_data;
2114        if (!index) {
2115                if (open_pack_index(p))
2116                        return NULL;
2117                index = p->index_data;
2118        }
2119        if (n >= p->num_objects)
2120                return NULL;
2121        index += 4 * 256;
2122        if (p->index_version == 1) {
2123                return index + 24 * n + 4;
2124        } else {
2125                index += 8;
2126                return index + 20 * n;
2127        }
2128}
2129
2130const struct object_id *nth_packed_object_oid(struct object_id *oid,
2131                                              struct packed_git *p,
2132                                              uint32_t n)
2133{
2134        const unsigned char *hash = nth_packed_object_sha1(p, n);
2135        if (!hash)
2136                return NULL;
2137        hashcpy(oid->hash, hash);
2138        return oid;
2139}
2140
2141void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
2142{
2143        const unsigned char *ptr = vptr;
2144        const unsigned char *start = p->index_data;
2145        const unsigned char *end = start + p->index_size;
2146        if (ptr < start)
2147                die(_("offset before start of pack index for %s (corrupt index?)"),
2148                    p->pack_name);
2149        /* No need to check for underflow; .idx files must be at least 8 bytes */
2150        if (ptr >= end - 8)
2151                die(_("offset beyond end of pack index for %s (truncated index?)"),
2152                    p->pack_name);
2153}
2154
2155off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
2156{
2157        const unsigned char *index = p->index_data;
2158        index += 4 * 256;
2159        if (p->index_version == 1) {
2160                return ntohl(*((uint32_t *)(index + 24 * n)));
2161        } else {
2162                uint32_t off;
2163                index += 8 + p->num_objects * (20 + 4);
2164                off = ntohl(*((uint32_t *)(index + 4 * n)));
2165                if (!(off & 0x80000000))
2166                        return off;
2167                index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
2168                check_pack_index_ptr(p, index);
2169                return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
2170                                   ntohl(*((uint32_t *)(index + 4)));
2171        }
2172}
2173
2174off_t find_pack_entry_one(const unsigned char *sha1,
2175                                  struct packed_git *p)
2176{
2177        const uint32_t *level1_ofs = p->index_data;
2178        const unsigned char *index = p->index_data;
2179        unsigned hi, lo, stride;
2180        static int debug_lookup = -1;
2181
2182        if (debug_lookup < 0)
2183                debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
2184
2185        if (!index) {
2186                if (open_pack_index(p))
2187                        return 0;
2188                level1_ofs = p->index_data;
2189                index = p->index_data;
2190        }
2191        if (p->index_version > 1) {
2192                level1_ofs += 2;
2193                index += 8;
2194        }
2195        index += 4 * 256;
2196        hi = ntohl(level1_ofs[*sha1]);
2197        lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
2198        if (p->index_version > 1) {
2199                stride = 20;
2200        } else {
2201                stride = 24;
2202                index += 4;
2203        }
2204
2205        if (debug_lookup)
2206                printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
2207                       sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
2208
2209        while (lo < hi) {
2210                unsigned mi = (lo + hi) / 2;
2211                int cmp = hashcmp(index + mi * stride, sha1);
2212
2213                if (debug_lookup)
2214                        printf("lo %u hi %u rg %u mi %u\n",
2215                               lo, hi, hi - lo, mi);
2216                if (!cmp)
2217                        return nth_packed_object_offset(p, mi);
2218                if (cmp > 0)
2219                        hi = mi;
2220                else
2221                        lo = mi+1;
2222        }
2223        return 0;
2224}
2225
2226int is_pack_valid(struct packed_git *p)
2227{
2228        /* An already open pack is known to be valid. */
2229        if (p->pack_fd != -1)
2230                return 1;
2231
2232        /* If the pack has one window completely covering the
2233         * file size, the pack is known to be valid even if
2234         * the descriptor is not currently open.
2235         */
2236        if (p->windows) {
2237                struct pack_window *w = p->windows;
2238
2239                if (!w->offset && w->len == p->pack_size)
2240                        return 1;
2241        }
2242
2243        /* Force the pack to open to prove its valid. */
2244        return !open_packed_git(p);
2245}
2246
2247static int fill_pack_entry(const unsigned char *sha1,
2248                           struct pack_entry *e,
2249                           struct packed_git *p)
2250{
2251        off_t offset;
2252
2253        if (p->num_bad_objects) {
2254                unsigned i;
2255                for (i = 0; i < p->num_bad_objects; i++)
2256                        if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
2257                                return 0;
2258        }
2259
2260        offset = find_pack_entry_one(sha1, p);
2261        if (!offset)
2262                return 0;
2263
2264        /*
2265         * We are about to tell the caller where they can locate the
2266         * requested object.  We better make sure the packfile is
2267         * still here and can be accessed before supplying that
2268         * answer, as it may have been deleted since the index was
2269         * loaded!
2270         */
2271        if (!is_pack_valid(p))
2272                return 0;
2273        e->offset = offset;
2274        e->p = p;
2275        hashcpy(e->sha1, sha1);
2276        return 1;
2277}
2278
2279/*
2280 * Iff a pack file contains the object named by sha1, return true and
2281 * store its location to e.
2282 */
2283static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
2284{
2285        struct mru_entry *p;
2286
2287        prepare_packed_git();
2288        if (!packed_git)
2289                return 0;
2290
2291        for (p = packed_git_mru->head; p; p = p->next) {
2292                if (fill_pack_entry(sha1, e, p->item)) {
2293                        mru_mark(packed_git_mru, p);
2294                        return 1;
2295                }
2296        }
2297        return 0;
2298}
2299
2300struct packed_git *find_sha1_pack(const unsigned char *sha1,
2301                                  struct packed_git *packs)
2302{
2303        struct packed_git *p;
2304
2305        for (p = packs; p; p = p->next) {
2306                if (find_pack_entry_one(sha1, p))
2307                        return p;
2308        }
2309        return NULL;
2310
2311}
2312
2313static int sha1_loose_object_info(const unsigned char *sha1,
2314                                  struct object_info *oi,
2315                                  int flags)
2316{
2317        int status = 0;
2318        unsigned long mapsize;
2319        void *map;
2320        git_zstream stream;
2321        char hdr[32];
2322        struct strbuf hdrbuf = STRBUF_INIT;
2323        unsigned long size_scratch;
2324
2325        if (oi->delta_base_sha1)
2326                hashclr(oi->delta_base_sha1);
2327
2328        /*
2329         * If we don't care about type or size, then we don't
2330         * need to look inside the object at all. Note that we
2331         * do not optimize out the stat call, even if the
2332         * caller doesn't care about the disk-size, since our
2333         * return value implicitly indicates whether the
2334         * object even exists.
2335         */
2336        if (!oi->typep && !oi->typename && !oi->sizep && !oi->contentp) {
2337                const char *path;
2338                struct stat st;
2339                if (stat_sha1_file(sha1, &st, &path) < 0)
2340                        return -1;
2341                if (oi->disk_sizep)
2342                        *oi->disk_sizep = st.st_size;
2343                return 0;
2344        }
2345
2346        map = map_sha1_file(sha1, &mapsize);
2347        if (!map)
2348                return -1;
2349
2350        if (!oi->sizep)
2351                oi->sizep = &size_scratch;
2352
2353        if (oi->disk_sizep)
2354                *oi->disk_sizep = mapsize;
2355        if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE)) {
2356                if (unpack_sha1_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
2357                        status = error("unable to unpack %s header with --allow-unknown-type",
2358                                       sha1_to_hex(sha1));
2359        } else if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
2360                status = error("unable to unpack %s header",
2361                               sha1_to_hex(sha1));
2362        if (status < 0)
2363                ; /* Do nothing */
2364        else if (hdrbuf.len) {
2365                if ((status = parse_sha1_header_extended(hdrbuf.buf, oi, flags)) < 0)
2366                        status = error("unable to parse %s header with --allow-unknown-type",
2367                                       sha1_to_hex(sha1));
2368        } else if ((status = parse_sha1_header_extended(hdr, oi, flags)) < 0)
2369                status = error("unable to parse %s header", sha1_to_hex(sha1));
2370
2371        if (status >= 0 && oi->contentp)
2372                *oi->contentp = unpack_sha1_rest(&stream, hdr,
2373                                                 *oi->sizep, sha1);
2374        else
2375                git_inflate_end(&stream);
2376
2377        munmap(map, mapsize);
2378        if (status && oi->typep)
2379                *oi->typep = status;
2380        if (oi->sizep == &size_scratch)
2381                oi->sizep = NULL;
2382        strbuf_release(&hdrbuf);
2383        oi->whence = OI_LOOSE;
2384        return (status < 0) ? status : 0;
2385}
2386
2387int sha1_object_info_extended(const unsigned char *sha1, struct object_info *oi, unsigned flags)
2388{
2389        static struct object_info blank_oi = OBJECT_INFO_INIT;
2390        struct pack_entry e;
2391        int rtype;
2392        const unsigned char *real = (flags & OBJECT_INFO_LOOKUP_REPLACE) ?
2393                                    lookup_replace_object(sha1) :
2394                                    sha1;
2395
2396        if (!oi)
2397                oi = &blank_oi;
2398
2399        if (!(flags & OBJECT_INFO_SKIP_CACHED)) {
2400                struct cached_object *co = find_cached_object(real);
2401                if (co) {
2402                        if (oi->typep)
2403                                *(oi->typep) = co->type;
2404                        if (oi->sizep)
2405                                *(oi->sizep) = co->size;
2406                        if (oi->disk_sizep)
2407                                *(oi->disk_sizep) = 0;
2408                        if (oi->delta_base_sha1)
2409                                hashclr(oi->delta_base_sha1);
2410                        if (oi->typename)
2411                                strbuf_addstr(oi->typename, typename(co->type));
2412                        if (oi->contentp)
2413                                *oi->contentp = xmemdupz(co->buf, co->size);
2414                        oi->whence = OI_CACHED;
2415                        return 0;
2416                }
2417        }
2418
2419        if (!find_pack_entry(real, &e)) {
2420                /* Most likely it's a loose object. */
2421                if (!sha1_loose_object_info(real, oi, flags))
2422                        return 0;
2423
2424                /* Not a loose object; someone else may have just packed it. */
2425                if (flags & OBJECT_INFO_QUICK) {
2426                        return -1;
2427                } else {
2428                        reprepare_packed_git();
2429                        if (!find_pack_entry(real, &e))
2430                                return -1;
2431                }
2432        }
2433
2434        if (oi == &blank_oi)
2435                /*
2436                 * We know that the caller doesn't actually need the
2437                 * information below, so return early.
2438                 */
2439                return 0;
2440
2441        rtype = packed_object_info(e.p, e.offset, oi);
2442        if (rtype < 0) {
2443                mark_bad_packed_object(e.p, real);
2444                return sha1_object_info_extended(real, oi, 0);
2445        } else if (oi->whence == OI_PACKED) {
2446                oi->u.packed.offset = e.offset;
2447                oi->u.packed.pack = e.p;
2448                oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
2449                                         rtype == OBJ_OFS_DELTA);
2450        }
2451
2452        return 0;
2453}
2454
2455/* returns enum object_type or negative */
2456int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
2457{
2458        enum object_type type;
2459        struct object_info oi = OBJECT_INFO_INIT;
2460
2461        oi.typep = &type;
2462        oi.sizep = sizep;
2463        if (sha1_object_info_extended(sha1, &oi,
2464                                      OBJECT_INFO_LOOKUP_REPLACE) < 0)
2465                return -1;
2466        return type;
2467}
2468
2469int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2470                      unsigned char *sha1)
2471{
2472        struct cached_object *co;
2473
2474        hash_sha1_file(buf, len, typename(type), sha1);
2475        if (has_sha1_file(sha1) || find_cached_object(sha1))
2476                return 0;
2477        ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
2478        co = &cached_objects[cached_object_nr++];
2479        co->size = len;
2480        co->type = type;
2481        co->buf = xmalloc(len);
2482        memcpy(co->buf, buf, len);
2483        hashcpy(co->sha1, sha1);
2484        return 0;
2485}
2486
2487static void *read_object(const unsigned char *sha1, enum object_type *type,
2488                         unsigned long *size)
2489{
2490        struct object_info oi = OBJECT_INFO_INIT;
2491        void *content;
2492        oi.typep = type;
2493        oi.sizep = size;
2494        oi.contentp = &content;
2495
2496        if (sha1_object_info_extended(sha1, &oi, 0) < 0)
2497                return NULL;
2498        return content;
2499}
2500
2501/*
2502 * This function dies on corrupt objects; the callers who want to
2503 * deal with them should arrange to call read_object() and give error
2504 * messages themselves.
2505 */
2506void *read_sha1_file_extended(const unsigned char *sha1,
2507                              enum object_type *type,
2508                              unsigned long *size,
2509                              int lookup_replace)
2510{
2511        void *data;
2512        const struct packed_git *p;
2513        const char *path;
2514        struct stat st;
2515        const unsigned char *repl = lookup_replace ? lookup_replace_object(sha1)
2516                                                   : sha1;
2517
2518        errno = 0;
2519        data = read_object(repl, type, size);
2520        if (data)
2521                return data;
2522
2523        if (errno && errno != ENOENT)
2524                die_errno("failed to read object %s", sha1_to_hex(sha1));
2525
2526        /* die if we replaced an object with one that does not exist */
2527        if (repl != sha1)
2528                die("replacement %s not found for %s",
2529                    sha1_to_hex(repl), sha1_to_hex(sha1));
2530
2531        if (!stat_sha1_file(repl, &st, &path))
2532                die("loose object %s (stored in %s) is corrupt",
2533                    sha1_to_hex(repl), path);
2534
2535        if ((p = has_packed_and_bad(repl)) != NULL)
2536                die("packed object %s (stored in %s) is corrupt",
2537                    sha1_to_hex(repl), p->pack_name);
2538
2539        return NULL;
2540}
2541
2542void *read_object_with_reference(const unsigned char *sha1,
2543                                 const char *required_type_name,
2544                                 unsigned long *size,
2545                                 unsigned char *actual_sha1_return)
2546{
2547        enum object_type type, required_type;
2548        void *buffer;
2549        unsigned long isize;
2550        unsigned char actual_sha1[20];
2551
2552        required_type = type_from_string(required_type_name);
2553        hashcpy(actual_sha1, sha1);
2554        while (1) {
2555                int ref_length = -1;
2556                const char *ref_type = NULL;
2557
2558                buffer = read_sha1_file(actual_sha1, &type, &isize);
2559                if (!buffer)
2560                        return NULL;
2561                if (type == required_type) {
2562                        *size = isize;
2563                        if (actual_sha1_return)
2564                                hashcpy(actual_sha1_return, actual_sha1);
2565                        return buffer;
2566                }
2567                /* Handle references */
2568                else if (type == OBJ_COMMIT)
2569                        ref_type = "tree ";
2570                else if (type == OBJ_TAG)
2571                        ref_type = "object ";
2572                else {
2573                        free(buffer);
2574                        return NULL;
2575                }
2576                ref_length = strlen(ref_type);
2577
2578                if (ref_length + 40 > isize ||
2579                    memcmp(buffer, ref_type, ref_length) ||
2580                    get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2581                        free(buffer);
2582                        return NULL;
2583                }
2584                free(buffer);
2585                /* Now we have the ID of the referred-to object in
2586                 * actual_sha1.  Check again. */
2587        }
2588}
2589
2590static void write_sha1_file_prepare(const void *buf, unsigned long len,
2591                                    const char *type, unsigned char *sha1,
2592                                    char *hdr, int *hdrlen)
2593{
2594        git_SHA_CTX c;
2595
2596        /* Generate the header */
2597        *hdrlen = xsnprintf(hdr, *hdrlen, "%s %lu", type, len)+1;
2598
2599        /* Sha1.. */
2600        git_SHA1_Init(&c);
2601        git_SHA1_Update(&c, hdr, *hdrlen);
2602        git_SHA1_Update(&c, buf, len);
2603        git_SHA1_Final(sha1, &c);
2604}
2605
2606/*
2607 * Move the just written object into its final resting place.
2608 */
2609int finalize_object_file(const char *tmpfile, const char *filename)
2610{
2611        int ret = 0;
2612
2613        if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
2614                goto try_rename;
2615        else if (link(tmpfile, filename))
2616                ret = errno;
2617
2618        /*
2619         * Coda hack - coda doesn't like cross-directory links,
2620         * so we fall back to a rename, which will mean that it
2621         * won't be able to check collisions, but that's not a
2622         * big deal.
2623         *
2624         * The same holds for FAT formatted media.
2625         *
2626         * When this succeeds, we just return.  We have nothing
2627         * left to unlink.
2628         */
2629        if (ret && ret != EEXIST) {
2630        try_rename:
2631                if (!rename(tmpfile, filename))
2632                        goto out;
2633                ret = errno;
2634        }
2635        unlink_or_warn(tmpfile);
2636        if (ret) {
2637                if (ret != EEXIST) {
2638                        return error_errno("unable to write sha1 filename %s", filename);
2639                }
2640                /* FIXME!!! Collision check here ? */
2641        }
2642
2643out:
2644        if (adjust_shared_perm(filename))
2645                return error("unable to set permission to '%s'", filename);
2646        return 0;
2647}
2648
2649static int write_buffer(int fd, const void *buf, size_t len)
2650{
2651        if (write_in_full(fd, buf, len) < 0)
2652                return error_errno("file write error");
2653        return 0;
2654}
2655
2656int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2657                   unsigned char *sha1)
2658{
2659        char hdr[32];
2660        int hdrlen = sizeof(hdr);
2661        write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2662        return 0;
2663}
2664
2665/* Finalize a file on disk, and close it. */
2666static void close_sha1_file(int fd)
2667{
2668        if (fsync_object_files)
2669                fsync_or_die(fd, "sha1 file");
2670        if (close(fd) != 0)
2671                die_errno("error when closing sha1 file");
2672}
2673
2674/* Size of directory component, including the ending '/' */
2675static inline int directory_size(const char *filename)
2676{
2677        const char *s = strrchr(filename, '/');
2678        if (!s)
2679                return 0;
2680        return s - filename + 1;
2681}
2682
2683/*
2684 * This creates a temporary file in the same directory as the final
2685 * 'filename'
2686 *
2687 * We want to avoid cross-directory filename renames, because those
2688 * can have problems on various filesystems (FAT, NFS, Coda).
2689 */
2690static int create_tmpfile(struct strbuf *tmp, const char *filename)
2691{
2692        int fd, dirlen = directory_size(filename);
2693
2694        strbuf_reset(tmp);
2695        strbuf_add(tmp, filename, dirlen);
2696        strbuf_addstr(tmp, "tmp_obj_XXXXXX");
2697        fd = git_mkstemp_mode(tmp->buf, 0444);
2698        if (fd < 0 && dirlen && errno == ENOENT) {
2699                /*
2700                 * Make sure the directory exists; note that the contents
2701                 * of the buffer are undefined after mkstemp returns an
2702                 * error, so we have to rewrite the whole buffer from
2703                 * scratch.
2704                 */
2705                strbuf_reset(tmp);
2706                strbuf_add(tmp, filename, dirlen - 1);
2707                if (mkdir(tmp->buf, 0777) && errno != EEXIST)
2708                        return -1;
2709                if (adjust_shared_perm(tmp->buf))
2710                        return -1;
2711
2712                /* Try again */
2713                strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
2714                fd = git_mkstemp_mode(tmp->buf, 0444);
2715        }
2716        return fd;
2717}
2718
2719static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
2720                              const void *buf, unsigned long len, time_t mtime)
2721{
2722        int fd, ret;
2723        unsigned char compressed[4096];
2724        git_zstream stream;
2725        git_SHA_CTX c;
2726        unsigned char parano_sha1[20];
2727        static struct strbuf tmp_file = STRBUF_INIT;
2728        const char *filename = sha1_file_name(sha1);
2729
2730        fd = create_tmpfile(&tmp_file, filename);
2731        if (fd < 0) {
2732                if (errno == EACCES)
2733                        return error("insufficient permission for adding an object to repository database %s", get_object_directory());
2734                else
2735                        return error_errno("unable to create temporary file");
2736        }
2737
2738        /* Set it up */
2739        git_deflate_init(&stream, zlib_compression_level);
2740        stream.next_out = compressed;
2741        stream.avail_out = sizeof(compressed);
2742        git_SHA1_Init(&c);
2743
2744        /* First header.. */
2745        stream.next_in = (unsigned char *)hdr;
2746        stream.avail_in = hdrlen;
2747        while (git_deflate(&stream, 0) == Z_OK)
2748                ; /* nothing */
2749        git_SHA1_Update(&c, hdr, hdrlen);
2750
2751        /* Then the data itself.. */
2752        stream.next_in = (void *)buf;
2753        stream.avail_in = len;
2754        do {
2755                unsigned char *in0 = stream.next_in;
2756                ret = git_deflate(&stream, Z_FINISH);
2757                git_SHA1_Update(&c, in0, stream.next_in - in0);
2758                if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
2759                        die("unable to write sha1 file");
2760                stream.next_out = compressed;
2761                stream.avail_out = sizeof(compressed);
2762        } while (ret == Z_OK);
2763
2764        if (ret != Z_STREAM_END)
2765                die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2766        ret = git_deflate_end_gently(&stream);
2767        if (ret != Z_OK)
2768                die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2769        git_SHA1_Final(parano_sha1, &c);
2770        if (hashcmp(sha1, parano_sha1) != 0)
2771                die("confused by unstable object source data for %s", sha1_to_hex(sha1));
2772
2773        close_sha1_file(fd);
2774
2775        if (mtime) {
2776                struct utimbuf utb;
2777                utb.actime = mtime;
2778                utb.modtime = mtime;
2779                if (utime(tmp_file.buf, &utb) < 0)
2780                        warning_errno("failed utime() on %s", tmp_file.buf);
2781        }
2782
2783        return finalize_object_file(tmp_file.buf, filename);
2784}
2785
2786static int freshen_loose_object(const unsigned char *sha1)
2787{
2788        return check_and_freshen(sha1, 1);
2789}
2790
2791static int freshen_packed_object(const unsigned char *sha1)
2792{
2793        struct pack_entry e;
2794        if (!find_pack_entry(sha1, &e))
2795                return 0;
2796        if (e.p->freshened)
2797                return 1;
2798        if (!freshen_file(e.p->pack_name))
2799                return 0;
2800        e.p->freshened = 1;
2801        return 1;
2802}
2803
2804int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *sha1)
2805{
2806        char hdr[32];
2807        int hdrlen = sizeof(hdr);
2808
2809        /* Normally if we have it in the pack then we do not bother writing
2810         * it out into .git/objects/??/?{38} file.
2811         */
2812        write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2813        if (freshen_packed_object(sha1) || freshen_loose_object(sha1))
2814                return 0;
2815        return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
2816}
2817
2818int hash_sha1_file_literally(const void *buf, unsigned long len, const char *type,
2819                             unsigned char *sha1, unsigned flags)
2820{
2821        char *header;
2822        int hdrlen, status = 0;
2823
2824        /* type string, SP, %lu of the length plus NUL must fit this */
2825        hdrlen = strlen(type) + 32;
2826        header = xmalloc(hdrlen);
2827        write_sha1_file_prepare(buf, len, type, sha1, header, &hdrlen);
2828
2829        if (!(flags & HASH_WRITE_OBJECT))
2830                goto cleanup;
2831        if (freshen_packed_object(sha1) || freshen_loose_object(sha1))
2832                goto cleanup;
2833        status = write_loose_object(sha1, header, hdrlen, buf, len, 0);
2834
2835cleanup:
2836        free(header);
2837        return status;
2838}
2839
2840int force_object_loose(const unsigned char *sha1, time_t mtime)
2841{
2842        void *buf;
2843        unsigned long len;
2844        enum object_type type;
2845        char hdr[32];
2846        int hdrlen;
2847        int ret;
2848
2849        if (has_loose_object(sha1))
2850                return 0;
2851        buf = read_object(sha1, &type, &len);
2852        if (!buf)
2853                return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2854        hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(type), len) + 1;
2855        ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
2856        free(buf);
2857
2858        return ret;
2859}
2860
2861int has_pack_index(const unsigned char *sha1)
2862{
2863        struct stat st;
2864        if (stat(sha1_pack_index_name(sha1), &st))
2865                return 0;
2866        return 1;
2867}
2868
2869int has_sha1_pack(const unsigned char *sha1)
2870{
2871        struct pack_entry e;
2872        return find_pack_entry(sha1, &e);
2873}
2874
2875int has_sha1_file_with_flags(const unsigned char *sha1, int flags)
2876{
2877        if (!startup_info->have_repository)
2878                return 0;
2879        return sha1_object_info_extended(sha1, NULL,
2880                                         flags | OBJECT_INFO_SKIP_CACHED) >= 0;
2881}
2882
2883int has_object_file(const struct object_id *oid)
2884{
2885        return has_sha1_file(oid->hash);
2886}
2887
2888int has_object_file_with_flags(const struct object_id *oid, int flags)
2889{
2890        return has_sha1_file_with_flags(oid->hash, flags);
2891}
2892
2893static void check_tree(const void *buf, size_t size)
2894{
2895        struct tree_desc desc;
2896        struct name_entry entry;
2897
2898        init_tree_desc(&desc, buf, size);
2899        while (tree_entry(&desc, &entry))
2900                /* do nothing
2901                 * tree_entry() will die() on malformed entries */
2902                ;
2903}
2904
2905static void check_commit(const void *buf, size_t size)
2906{
2907        struct commit c;
2908        memset(&c, 0, sizeof(c));
2909        if (parse_commit_buffer(&c, buf, size))
2910                die("corrupt commit");
2911}
2912
2913static void check_tag(const void *buf, size_t size)
2914{
2915        struct tag t;
2916        memset(&t, 0, sizeof(t));
2917        if (parse_tag_buffer(&t, buf, size))
2918                die("corrupt tag");
2919}
2920
2921static int index_mem(unsigned char *sha1, void *buf, size_t size,
2922                     enum object_type type,
2923                     const char *path, unsigned flags)
2924{
2925        int ret, re_allocated = 0;
2926        int write_object = flags & HASH_WRITE_OBJECT;
2927
2928        if (!type)
2929                type = OBJ_BLOB;
2930
2931        /*
2932         * Convert blobs to git internal format
2933         */
2934        if ((type == OBJ_BLOB) && path) {
2935                struct strbuf nbuf = STRBUF_INIT;
2936                if (convert_to_git(&the_index, path, buf, size, &nbuf,
2937                                   write_object ? safe_crlf : SAFE_CRLF_FALSE)) {
2938                        buf = strbuf_detach(&nbuf, &size);
2939                        re_allocated = 1;
2940                }
2941        }
2942        if (flags & HASH_FORMAT_CHECK) {
2943                if (type == OBJ_TREE)
2944                        check_tree(buf, size);
2945                if (type == OBJ_COMMIT)
2946                        check_commit(buf, size);
2947                if (type == OBJ_TAG)
2948                        check_tag(buf, size);
2949        }
2950
2951        if (write_object)
2952                ret = write_sha1_file(buf, size, typename(type), sha1);
2953        else
2954                ret = hash_sha1_file(buf, size, typename(type), sha1);
2955        if (re_allocated)
2956                free(buf);
2957        return ret;
2958}
2959
2960static int index_stream_convert_blob(unsigned char *sha1, int fd,
2961                                     const char *path, unsigned flags)
2962{
2963        int ret;
2964        const int write_object = flags & HASH_WRITE_OBJECT;
2965        struct strbuf sbuf = STRBUF_INIT;
2966
2967        assert(path);
2968        assert(would_convert_to_git_filter_fd(path));
2969
2970        convert_to_git_filter_fd(&the_index, path, fd, &sbuf,
2971                                 write_object ? safe_crlf : SAFE_CRLF_FALSE);
2972
2973        if (write_object)
2974                ret = write_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
2975                                      sha1);
2976        else
2977                ret = hash_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
2978                                     sha1);
2979        strbuf_release(&sbuf);
2980        return ret;
2981}
2982
2983static int index_pipe(unsigned char *sha1, int fd, enum object_type type,
2984                      const char *path, unsigned flags)
2985{
2986        struct strbuf sbuf = STRBUF_INIT;
2987        int ret;
2988
2989        if (strbuf_read(&sbuf, fd, 4096) >= 0)
2990                ret = index_mem(sha1, sbuf.buf, sbuf.len, type, path, flags);
2991        else
2992                ret = -1;
2993        strbuf_release(&sbuf);
2994        return ret;
2995}
2996
2997#define SMALL_FILE_SIZE (32*1024)
2998
2999static int index_core(unsigned char *sha1, int fd, size_t size,
3000                      enum object_type type, const char *path,
3001                      unsigned flags)
3002{
3003        int ret;
3004
3005        if (!size) {
3006                ret = index_mem(sha1, "", size, type, path, flags);
3007        } else if (size <= SMALL_FILE_SIZE) {
3008                char *buf = xmalloc(size);
3009                if (size == read_in_full(fd, buf, size))
3010                        ret = index_mem(sha1, buf, size, type, path, flags);
3011                else
3012                        ret = error_errno("short read");
3013                free(buf);
3014        } else {
3015                void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
3016                ret = index_mem(sha1, buf, size, type, path, flags);
3017                munmap(buf, size);
3018        }
3019        return ret;
3020}
3021
3022/*
3023 * This creates one packfile per large blob unless bulk-checkin
3024 * machinery is "plugged".
3025 *
3026 * This also bypasses the usual "convert-to-git" dance, and that is on
3027 * purpose. We could write a streaming version of the converting
3028 * functions and insert that before feeding the data to fast-import
3029 * (or equivalent in-core API described above). However, that is
3030 * somewhat complicated, as we do not know the size of the filter
3031 * result, which we need to know beforehand when writing a git object.
3032 * Since the primary motivation for trying to stream from the working
3033 * tree file and to avoid mmaping it in core is to deal with large
3034 * binary blobs, they generally do not want to get any conversion, and
3035 * callers should avoid this code path when filters are requested.
3036 */
3037static int index_stream(unsigned char *sha1, int fd, size_t size,
3038                        enum object_type type, const char *path,
3039                        unsigned flags)
3040{
3041        return index_bulk_checkin(sha1, fd, size, type, path, flags);
3042}
3043
3044int index_fd(unsigned char *sha1, int fd, struct stat *st,
3045             enum object_type type, const char *path, unsigned flags)
3046{
3047        int ret;
3048
3049        /*
3050         * Call xsize_t() only when needed to avoid potentially unnecessary
3051         * die() for large files.
3052         */
3053        if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(path))
3054                ret = index_stream_convert_blob(sha1, fd, path, flags);
3055        else if (!S_ISREG(st->st_mode))
3056                ret = index_pipe(sha1, fd, type, path, flags);
3057        else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
3058                 (path && would_convert_to_git(&the_index, path)))
3059                ret = index_core(sha1, fd, xsize_t(st->st_size), type, path,
3060                                 flags);
3061        else
3062                ret = index_stream(sha1, fd, xsize_t(st->st_size), type, path,
3063                                   flags);
3064        close(fd);
3065        return ret;
3066}
3067
3068int index_path(unsigned char *sha1, const char *path, struct stat *st, unsigned flags)
3069{
3070        int fd;
3071        struct strbuf sb = STRBUF_INIT;
3072
3073        switch (st->st_mode & S_IFMT) {
3074        case S_IFREG:
3075                fd = open(path, O_RDONLY);
3076                if (fd < 0)
3077                        return error_errno("open(\"%s\")", path);
3078                if (index_fd(sha1, fd, st, OBJ_BLOB, path, flags) < 0)
3079                        return error("%s: failed to insert into database",
3080                                     path);
3081                break;
3082        case S_IFLNK:
3083                if (strbuf_readlink(&sb, path, st->st_size))
3084                        return error_errno("readlink(\"%s\")", path);
3085                if (!(flags & HASH_WRITE_OBJECT))
3086                        hash_sha1_file(sb.buf, sb.len, blob_type, sha1);
3087                else if (write_sha1_file(sb.buf, sb.len, blob_type, sha1))
3088                        return error("%s: failed to insert into database",
3089                                     path);
3090                strbuf_release(&sb);
3091                break;
3092        case S_IFDIR:
3093                return resolve_gitlink_ref(path, "HEAD", sha1);
3094        default:
3095                return error("%s: unsupported file type", path);
3096        }
3097        return 0;
3098}
3099
3100int read_pack_header(int fd, struct pack_header *header)
3101{
3102        if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
3103                /* "eof before pack header was fully read" */
3104                return PH_ERROR_EOF;
3105
3106        if (header->hdr_signature != htonl(PACK_SIGNATURE))
3107                /* "protocol error (pack signature mismatch detected)" */
3108                return PH_ERROR_PACK_SIGNATURE;
3109        if (!pack_version_ok(header->hdr_version))
3110                /* "protocol error (pack version unsupported)" */
3111                return PH_ERROR_PROTOCOL;
3112        return 0;
3113}
3114
3115void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
3116{
3117        enum object_type type = sha1_object_info(sha1, NULL);
3118        if (type < 0)
3119                die("%s is not a valid object", sha1_to_hex(sha1));
3120        if (type != expect)
3121                die("%s is not a valid '%s' object", sha1_to_hex(sha1),
3122                    typename(expect));
3123}
3124
3125int for_each_file_in_obj_subdir(unsigned int subdir_nr,
3126                                struct strbuf *path,
3127                                each_loose_object_fn obj_cb,
3128                                each_loose_cruft_fn cruft_cb,
3129                                each_loose_subdir_fn subdir_cb,
3130                                void *data)
3131{
3132        size_t origlen, baselen;
3133        DIR *dir;
3134        struct dirent *de;
3135        int r = 0;
3136
3137        if (subdir_nr > 0xff)
3138                BUG("invalid loose object subdirectory: %x", subdir_nr);
3139
3140        origlen = path->len;
3141        strbuf_complete(path, '/');
3142        strbuf_addf(path, "%02x", subdir_nr);
3143        baselen = path->len;
3144
3145        dir = opendir(path->buf);
3146        if (!dir) {
3147                if (errno != ENOENT)
3148                        r = error_errno("unable to open %s", path->buf);
3149                strbuf_setlen(path, origlen);
3150                return r;
3151        }
3152
3153        while ((de = readdir(dir))) {
3154                if (is_dot_or_dotdot(de->d_name))
3155                        continue;
3156
3157                strbuf_setlen(path, baselen);
3158                strbuf_addf(path, "/%s", de->d_name);
3159
3160                if (strlen(de->d_name) == GIT_SHA1_HEXSZ - 2)  {
3161                        char hex[GIT_MAX_HEXSZ+1];
3162                        struct object_id oid;
3163
3164                        xsnprintf(hex, sizeof(hex), "%02x%s",
3165                                  subdir_nr, de->d_name);
3166                        if (!get_oid_hex(hex, &oid)) {
3167                                if (obj_cb) {
3168                                        r = obj_cb(&oid, path->buf, data);
3169                                        if (r)
3170                                                break;
3171                                }
3172                                continue;
3173                        }
3174                }
3175
3176                if (cruft_cb) {
3177                        r = cruft_cb(de->d_name, path->buf, data);
3178                        if (r)
3179                                break;
3180                }
3181        }
3182        closedir(dir);
3183
3184        strbuf_setlen(path, baselen);
3185        if (!r && subdir_cb)
3186                r = subdir_cb(subdir_nr, path->buf, data);
3187
3188        strbuf_setlen(path, origlen);
3189
3190        return r;
3191}
3192
3193int for_each_loose_file_in_objdir_buf(struct strbuf *path,
3194                            each_loose_object_fn obj_cb,
3195                            each_loose_cruft_fn cruft_cb,
3196                            each_loose_subdir_fn subdir_cb,
3197                            void *data)
3198{
3199        int r = 0;
3200        int i;
3201
3202        for (i = 0; i < 256; i++) {
3203                r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
3204                                                subdir_cb, data);
3205                if (r)
3206                        break;
3207        }
3208
3209        return r;
3210}
3211
3212int for_each_loose_file_in_objdir(const char *path,
3213                                  each_loose_object_fn obj_cb,
3214                                  each_loose_cruft_fn cruft_cb,
3215                                  each_loose_subdir_fn subdir_cb,
3216                                  void *data)
3217{
3218        struct strbuf buf = STRBUF_INIT;
3219        int r;
3220
3221        strbuf_addstr(&buf, path);
3222        r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
3223                                              subdir_cb, data);
3224        strbuf_release(&buf);
3225
3226        return r;
3227}
3228
3229struct loose_alt_odb_data {
3230        each_loose_object_fn *cb;
3231        void *data;
3232};
3233
3234static int loose_from_alt_odb(struct alternate_object_database *alt,
3235                              void *vdata)
3236{
3237        struct loose_alt_odb_data *data = vdata;
3238        struct strbuf buf = STRBUF_INIT;
3239        int r;
3240
3241        strbuf_addstr(&buf, alt->path);
3242        r = for_each_loose_file_in_objdir_buf(&buf,
3243                                              data->cb, NULL, NULL,
3244                                              data->data);
3245        strbuf_release(&buf);
3246        return r;
3247}
3248
3249int for_each_loose_object(each_loose_object_fn cb, void *data, unsigned flags)
3250{
3251        struct loose_alt_odb_data alt;
3252        int r;
3253
3254        r = for_each_loose_file_in_objdir(get_object_directory(),
3255                                          cb, NULL, NULL, data);
3256        if (r)
3257                return r;
3258
3259        if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
3260                return 0;
3261
3262        alt.cb = cb;
3263        alt.data = data;
3264        return foreach_alt_odb(loose_from_alt_odb, &alt);
3265}
3266
3267static int for_each_object_in_pack(struct packed_git *p, each_packed_object_fn cb, void *data)
3268{
3269        uint32_t i;
3270        int r = 0;
3271
3272        for (i = 0; i < p->num_objects; i++) {
3273                struct object_id oid;
3274
3275                if (!nth_packed_object_oid(&oid, p, i))
3276                        return error("unable to get sha1 of object %u in %s",
3277                                     i, p->pack_name);
3278
3279                r = cb(&oid, p, i, data);
3280                if (r)
3281                        break;
3282        }
3283        return r;
3284}
3285
3286int for_each_packed_object(each_packed_object_fn cb, void *data, unsigned flags)
3287{
3288        struct packed_git *p;
3289        int r = 0;
3290        int pack_errors = 0;
3291
3292        prepare_packed_git();
3293        for (p = packed_git; p; p = p->next) {
3294                if ((flags & FOR_EACH_OBJECT_LOCAL_ONLY) && !p->pack_local)
3295                        continue;
3296                if (open_pack_index(p)) {
3297                        pack_errors = 1;
3298                        continue;
3299                }
3300                r = for_each_object_in_pack(p, cb, data);
3301                if (r)
3302                        break;
3303        }
3304        return r ? r : pack_errors;
3305}
3306
3307static int check_stream_sha1(git_zstream *stream,
3308                             const char *hdr,
3309                             unsigned long size,
3310                             const char *path,
3311                             const unsigned char *expected_sha1)
3312{
3313        git_SHA_CTX c;
3314        unsigned char real_sha1[GIT_MAX_RAWSZ];
3315        unsigned char buf[4096];
3316        unsigned long total_read;
3317        int status = Z_OK;
3318
3319        git_SHA1_Init(&c);
3320        git_SHA1_Update(&c, hdr, stream->total_out);
3321
3322        /*
3323         * We already read some bytes into hdr, but the ones up to the NUL
3324         * do not count against the object's content size.
3325         */
3326        total_read = stream->total_out - strlen(hdr) - 1;
3327
3328        /*
3329         * This size comparison must be "<=" to read the final zlib packets;
3330         * see the comment in unpack_sha1_rest for details.
3331         */
3332        while (total_read <= size &&
3333               (status == Z_OK || status == Z_BUF_ERROR)) {
3334                stream->next_out = buf;
3335                stream->avail_out = sizeof(buf);
3336                if (size - total_read < stream->avail_out)
3337                        stream->avail_out = size - total_read;
3338                status = git_inflate(stream, Z_FINISH);
3339                git_SHA1_Update(&c, buf, stream->next_out - buf);
3340                total_read += stream->next_out - buf;
3341        }
3342        git_inflate_end(stream);
3343
3344        if (status != Z_STREAM_END) {
3345                error("corrupt loose object '%s'", sha1_to_hex(expected_sha1));
3346                return -1;
3347        }
3348        if (stream->avail_in) {
3349                error("garbage at end of loose object '%s'",
3350                      sha1_to_hex(expected_sha1));
3351                return -1;
3352        }
3353
3354        git_SHA1_Final(real_sha1, &c);
3355        if (hashcmp(expected_sha1, real_sha1)) {
3356                error("sha1 mismatch for %s (expected %s)", path,
3357                      sha1_to_hex(expected_sha1));
3358                return -1;
3359        }
3360
3361        return 0;
3362}
3363
3364int read_loose_object(const char *path,
3365                      const unsigned char *expected_sha1,
3366                      enum object_type *type,
3367                      unsigned long *size,
3368                      void **contents)
3369{
3370        int ret = -1;
3371        void *map = NULL;
3372        unsigned long mapsize;
3373        git_zstream stream;
3374        char hdr[32];
3375
3376        *contents = NULL;
3377
3378        map = map_sha1_file_1(path, NULL, &mapsize);
3379        if (!map) {
3380                error_errno("unable to mmap %s", path);
3381                goto out;
3382        }
3383
3384        if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0) {
3385                error("unable to unpack header of %s", path);
3386                goto out;
3387        }
3388
3389        *type = parse_sha1_header(hdr, size);
3390        if (*type < 0) {
3391                error("unable to parse header of %s", path);
3392                git_inflate_end(&stream);
3393                goto out;
3394        }
3395
3396        if (*type == OBJ_BLOB) {
3397                if (check_stream_sha1(&stream, hdr, *size, path, expected_sha1) < 0)
3398                        goto out;
3399        } else {
3400                *contents = unpack_sha1_rest(&stream, hdr, *size, expected_sha1);
3401                if (!*contents) {
3402                        error("unable to unpack contents of %s", path);
3403                        git_inflate_end(&stream);
3404                        goto out;
3405                }
3406                if (check_sha1_signature(expected_sha1, *contents,
3407                                         *size, typename(*type))) {
3408                        error("sha1 mismatch for %s (expected %s)", path,
3409                              sha1_to_hex(expected_sha1));
3410                        free(*contents);
3411                        goto out;
3412                }
3413        }
3414
3415        ret = 0; /* everything checks out */
3416
3417out:
3418        if (map)
3419                munmap(map, mapsize);
3420        return ret;
3421}