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