adb116350bd38db0390f4f731e509f3fe703a1c1
   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 "delta.h"
  11#include "pack.h"
  12#include "blob.h"
  13#include "commit.h"
  14#include "tag.h"
  15#include "tree.h"
  16#include "refs.h"
  17#include "pack-revindex.h"
  18#include "sha1-lookup.h"
  19
  20#ifndef O_NOATIME
  21#if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
  22#define O_NOATIME 01000000
  23#else
  24#define O_NOATIME 0
  25#endif
  26#endif
  27
  28#ifdef NO_C99_FORMAT
  29#define SZ_FMT "lu"
  30static unsigned long sz_fmt(size_t s) { return (unsigned long)s; }
  31#else
  32#define SZ_FMT "zu"
  33static size_t sz_fmt(size_t s) { return s; }
  34#endif
  35
  36const unsigned char null_sha1[20];
  37
  38const signed char hexval_table[256] = {
  39         -1, -1, -1, -1, -1, -1, -1, -1,                /* 00-07 */
  40         -1, -1, -1, -1, -1, -1, -1, -1,                /* 08-0f */
  41         -1, -1, -1, -1, -1, -1, -1, -1,                /* 10-17 */
  42         -1, -1, -1, -1, -1, -1, -1, -1,                /* 18-1f */
  43         -1, -1, -1, -1, -1, -1, -1, -1,                /* 20-27 */
  44         -1, -1, -1, -1, -1, -1, -1, -1,                /* 28-2f */
  45          0,  1,  2,  3,  4,  5,  6,  7,                /* 30-37 */
  46          8,  9, -1, -1, -1, -1, -1, -1,                /* 38-3f */
  47         -1, 10, 11, 12, 13, 14, 15, -1,                /* 40-47 */
  48         -1, -1, -1, -1, -1, -1, -1, -1,                /* 48-4f */
  49         -1, -1, -1, -1, -1, -1, -1, -1,                /* 50-57 */
  50         -1, -1, -1, -1, -1, -1, -1, -1,                /* 58-5f */
  51         -1, 10, 11, 12, 13, 14, 15, -1,                /* 60-67 */
  52         -1, -1, -1, -1, -1, -1, -1, -1,                /* 68-67 */
  53         -1, -1, -1, -1, -1, -1, -1, -1,                /* 70-77 */
  54         -1, -1, -1, -1, -1, -1, -1, -1,                /* 78-7f */
  55         -1, -1, -1, -1, -1, -1, -1, -1,                /* 80-87 */
  56         -1, -1, -1, -1, -1, -1, -1, -1,                /* 88-8f */
  57         -1, -1, -1, -1, -1, -1, -1, -1,                /* 90-97 */
  58         -1, -1, -1, -1, -1, -1, -1, -1,                /* 98-9f */
  59         -1, -1, -1, -1, -1, -1, -1, -1,                /* a0-a7 */
  60         -1, -1, -1, -1, -1, -1, -1, -1,                /* a8-af */
  61         -1, -1, -1, -1, -1, -1, -1, -1,                /* b0-b7 */
  62         -1, -1, -1, -1, -1, -1, -1, -1,                /* b8-bf */
  63         -1, -1, -1, -1, -1, -1, -1, -1,                /* c0-c7 */
  64         -1, -1, -1, -1, -1, -1, -1, -1,                /* c8-cf */
  65         -1, -1, -1, -1, -1, -1, -1, -1,                /* d0-d7 */
  66         -1, -1, -1, -1, -1, -1, -1, -1,                /* d8-df */
  67         -1, -1, -1, -1, -1, -1, -1, -1,                /* e0-e7 */
  68         -1, -1, -1, -1, -1, -1, -1, -1,                /* e8-ef */
  69         -1, -1, -1, -1, -1, -1, -1, -1,                /* f0-f7 */
  70         -1, -1, -1, -1, -1, -1, -1, -1,                /* f8-ff */
  71};
  72
  73int get_sha1_hex(const char *hex, unsigned char *sha1)
  74{
  75        int i;
  76        for (i = 0; i < 20; i++) {
  77                unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
  78                if (val & ~0xff)
  79                        return -1;
  80                *sha1++ = val;
  81                hex += 2;
  82        }
  83        return 0;
  84}
  85
  86static inline int offset_1st_component(const char *path)
  87{
  88        if (has_dos_drive_prefix(path))
  89                return 2 + (path[2] == '/');
  90        return *path == '/';
  91}
  92
  93int safe_create_leading_directories(char *path)
  94{
  95        char *pos = path + offset_1st_component(path);
  96        struct stat st;
  97
  98        while (pos) {
  99                pos = strchr(pos, '/');
 100                if (!pos)
 101                        break;
 102                *pos = 0;
 103                if (!stat(path, &st)) {
 104                        /* path exists */
 105                        if (!S_ISDIR(st.st_mode)) {
 106                                *pos = '/';
 107                                return -3;
 108                        }
 109                }
 110                else if (mkdir(path, 0777)) {
 111                        *pos = '/';
 112                        return -1;
 113                }
 114                else if (adjust_shared_perm(path)) {
 115                        *pos = '/';
 116                        return -2;
 117                }
 118                *pos++ = '/';
 119        }
 120        return 0;
 121}
 122
 123int safe_create_leading_directories_const(const char *path)
 124{
 125        /* path points to cache entries, so xstrdup before messing with it */
 126        char *buf = xstrdup(path);
 127        int result = safe_create_leading_directories(buf);
 128        free(buf);
 129        return result;
 130}
 131
 132char *sha1_to_hex(const unsigned char *sha1)
 133{
 134        static int bufno;
 135        static char hexbuffer[4][50];
 136        static const char hex[] = "0123456789abcdef";
 137        char *buffer = hexbuffer[3 & ++bufno], *buf = buffer;
 138        int i;
 139
 140        for (i = 0; i < 20; i++) {
 141                unsigned int val = *sha1++;
 142                *buf++ = hex[val >> 4];
 143                *buf++ = hex[val & 0xf];
 144        }
 145        *buf = '\0';
 146
 147        return buffer;
 148}
 149
 150static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
 151{
 152        int i;
 153        for (i = 0; i < 20; i++) {
 154                static char hex[] = "0123456789abcdef";
 155                unsigned int val = sha1[i];
 156                char *pos = pathbuf + i*2 + (i > 0);
 157                *pos++ = hex[val >> 4];
 158                *pos = hex[val & 0xf];
 159        }
 160}
 161
 162/*
 163 * NOTE! This returns a statically allocated buffer, so you have to be
 164 * careful about using it. Do an "xstrdup()" if you need to save the
 165 * filename.
 166 *
 167 * Also note that this returns the location for creating.  Reading
 168 * SHA1 file can happen from any alternate directory listed in the
 169 * DB_ENVIRONMENT environment variable if it is not found in
 170 * the primary object database.
 171 */
 172char *sha1_file_name(const unsigned char *sha1)
 173{
 174        static char *name, *base;
 175
 176        if (!base) {
 177                const char *sha1_file_directory = get_object_directory();
 178                int len = strlen(sha1_file_directory);
 179                base = xmalloc(len + 60);
 180                memcpy(base, sha1_file_directory, len);
 181                memset(base+len, 0, 60);
 182                base[len] = '/';
 183                base[len+3] = '/';
 184                name = base + len + 1;
 185        }
 186        fill_sha1_path(name, sha1);
 187        return base;
 188}
 189
 190static char *sha1_get_pack_name(const unsigned char *sha1,
 191                                char **name, char **base, const char *which)
 192{
 193        static const char hex[] = "0123456789abcdef";
 194        char *buf;
 195        int i;
 196
 197        if (!*base) {
 198                const char *sha1_file_directory = get_object_directory();
 199                int len = strlen(sha1_file_directory);
 200                *base = xmalloc(len + 60);
 201                sprintf(*base, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
 202                        sha1_file_directory, which);
 203                *name = *base + len + 11;
 204        }
 205
 206        buf = *name;
 207
 208        for (i = 0; i < 20; i++) {
 209                unsigned int val = *sha1++;
 210                *buf++ = hex[val >> 4];
 211                *buf++ = hex[val & 0xf];
 212        }
 213
 214        return *base;
 215}
 216
 217char *sha1_pack_name(const unsigned char *sha1)
 218{
 219        static char *name, *base;
 220
 221        return sha1_get_pack_name(sha1, &name, &base, "pack");
 222}
 223
 224char *sha1_pack_index_name(const unsigned char *sha1)
 225{
 226        static char *name, *base;
 227
 228        return sha1_get_pack_name(sha1, &name, &base, "idx");
 229}
 230
 231struct alternate_object_database *alt_odb_list;
 232static struct alternate_object_database **alt_odb_tail;
 233
 234static void read_info_alternates(const char * alternates, int depth);
 235
 236/*
 237 * Prepare alternate object database registry.
 238 *
 239 * The variable alt_odb_list points at the list of struct
 240 * alternate_object_database.  The elements on this list come from
 241 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
 242 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
 243 * whose contents is similar to that environment variable but can be
 244 * LF separated.  Its base points at a statically allocated buffer that
 245 * contains "/the/directory/corresponding/to/.git/objects/...", while
 246 * its name points just after the slash at the end of ".git/objects/"
 247 * in the example above, and has enough space to hold 40-byte hex
 248 * SHA1, an extra slash for the first level indirection, and the
 249 * terminating NUL.
 250 */
 251static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
 252{
 253        struct stat st;
 254        const char *objdir = get_object_directory();
 255        struct alternate_object_database *ent;
 256        struct alternate_object_database *alt;
 257        /* 43 = 40-byte + 2 '/' + terminating NUL */
 258        int pfxlen = len;
 259        int entlen = pfxlen + 43;
 260        int base_len = -1;
 261
 262        if (!is_absolute_path(entry) && relative_base) {
 263                /* Relative alt-odb */
 264                if (base_len < 0)
 265                        base_len = strlen(relative_base) + 1;
 266                entlen += base_len;
 267                pfxlen += base_len;
 268        }
 269        ent = xmalloc(sizeof(*ent) + entlen);
 270
 271        if (!is_absolute_path(entry) && relative_base) {
 272                memcpy(ent->base, relative_base, base_len - 1);
 273                ent->base[base_len - 1] = '/';
 274                memcpy(ent->base + base_len, entry, len);
 275        }
 276        else
 277                memcpy(ent->base, entry, pfxlen);
 278
 279        ent->name = ent->base + pfxlen + 1;
 280        ent->base[pfxlen + 3] = '/';
 281        ent->base[pfxlen] = ent->base[entlen-1] = 0;
 282
 283        /* Detect cases where alternate disappeared */
 284        if (stat(ent->base, &st) || !S_ISDIR(st.st_mode)) {
 285                error("object directory %s does not exist; "
 286                      "check .git/objects/info/alternates.",
 287                      ent->base);
 288                free(ent);
 289                return -1;
 290        }
 291
 292        /* Prevent the common mistake of listing the same
 293         * thing twice, or object directory itself.
 294         */
 295        for (alt = alt_odb_list; alt; alt = alt->next) {
 296                if (!memcmp(ent->base, alt->base, pfxlen)) {
 297                        free(ent);
 298                        return -1;
 299                }
 300        }
 301        if (!memcmp(ent->base, objdir, pfxlen)) {
 302                free(ent);
 303                return -1;
 304        }
 305
 306        /* add the alternate entry */
 307        *alt_odb_tail = ent;
 308        alt_odb_tail = &(ent->next);
 309        ent->next = NULL;
 310
 311        /* recursively add alternates */
 312        read_info_alternates(ent->base, depth + 1);
 313
 314        ent->base[pfxlen] = '/';
 315
 316        return 0;
 317}
 318
 319static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
 320                                 const char *relative_base, int depth)
 321{
 322        const char *cp, *last;
 323
 324        if (depth > 5) {
 325                error("%s: ignoring alternate object stores, nesting too deep.",
 326                                relative_base);
 327                return;
 328        }
 329
 330        last = alt;
 331        while (last < ep) {
 332                cp = last;
 333                if (cp < ep && *cp == '#') {
 334                        while (cp < ep && *cp != sep)
 335                                cp++;
 336                        last = cp + 1;
 337                        continue;
 338                }
 339                while (cp < ep && *cp != sep)
 340                        cp++;
 341                if (last != cp) {
 342                        if (!is_absolute_path(last) && depth) {
 343                                error("%s: ignoring relative alternate object store %s",
 344                                                relative_base, last);
 345                        } else {
 346                                link_alt_odb_entry(last, cp - last,
 347                                                relative_base, depth);
 348                        }
 349                }
 350                while (cp < ep && *cp == sep)
 351                        cp++;
 352                last = cp;
 353        }
 354}
 355
 356static void read_info_alternates(const char * relative_base, int depth)
 357{
 358        char *map;
 359        size_t mapsz;
 360        struct stat st;
 361        const char alt_file_name[] = "info/alternates";
 362        /* Given that relative_base is no longer than PATH_MAX,
 363           ensure that "path" has enough space to append "/", the
 364           file name, "info/alternates", and a trailing NUL.  */
 365        char path[PATH_MAX + 1 + sizeof alt_file_name];
 366        int fd;
 367
 368        sprintf(path, "%s/%s", relative_base, alt_file_name);
 369        fd = open(path, O_RDONLY);
 370        if (fd < 0)
 371                return;
 372        if (fstat(fd, &st) || (st.st_size == 0)) {
 373                close(fd);
 374                return;
 375        }
 376        mapsz = xsize_t(st.st_size);
 377        map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
 378        close(fd);
 379
 380        link_alt_odb_entries(map, map + mapsz, '\n', relative_base, depth);
 381
 382        munmap(map, mapsz);
 383}
 384
 385void add_to_alternates_file(const char *reference)
 386{
 387        struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
 388        int fd = hold_lock_file_for_append(lock, git_path("objects/info/alternates"), LOCK_DIE_ON_ERROR);
 389        char *alt = mkpath("%s/objects\n", reference);
 390        write_or_die(fd, alt, strlen(alt));
 391        if (commit_lock_file(lock))
 392                die("could not close alternates file");
 393        if (alt_odb_tail)
 394                link_alt_odb_entries(alt, alt + strlen(alt), '\n', NULL, 0);
 395}
 396
 397void prepare_alt_odb(void)
 398{
 399        const char *alt;
 400
 401        if (alt_odb_tail)
 402                return;
 403
 404        alt = getenv(ALTERNATE_DB_ENVIRONMENT);
 405        if (!alt) alt = "";
 406
 407        alt_odb_tail = &alt_odb_list;
 408        link_alt_odb_entries(alt, alt + strlen(alt), PATH_SEP, NULL, 0);
 409
 410        read_info_alternates(get_object_directory(), 0);
 411}
 412
 413static int has_loose_object(const unsigned char *sha1)
 414{
 415        char *name = sha1_file_name(sha1);
 416        struct alternate_object_database *alt;
 417
 418        if (!access(name, F_OK))
 419                return 1;
 420        prepare_alt_odb();
 421        for (alt = alt_odb_list; alt; alt = alt->next) {
 422                name = alt->name;
 423                fill_sha1_path(name, sha1);
 424                if (!access(alt->base, F_OK))
 425                        return 1;
 426        }
 427        return 0;
 428}
 429
 430static unsigned int pack_used_ctr;
 431static unsigned int pack_mmap_calls;
 432static unsigned int peak_pack_open_windows;
 433static unsigned int pack_open_windows;
 434static size_t peak_pack_mapped;
 435static size_t pack_mapped;
 436struct packed_git *packed_git;
 437
 438void pack_report(void)
 439{
 440        fprintf(stderr,
 441                "pack_report: getpagesize()            = %10" SZ_FMT "\n"
 442                "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
 443                "pack_report: core.packedGitLimit      = %10" SZ_FMT "\n",
 444                sz_fmt(getpagesize()),
 445                sz_fmt(packed_git_window_size),
 446                sz_fmt(packed_git_limit));
 447        fprintf(stderr,
 448                "pack_report: pack_used_ctr            = %10u\n"
 449                "pack_report: pack_mmap_calls          = %10u\n"
 450                "pack_report: pack_open_windows        = %10u / %10u\n"
 451                "pack_report: pack_mapped              = "
 452                        "%10" SZ_FMT " / %10" SZ_FMT "\n",
 453                pack_used_ctr,
 454                pack_mmap_calls,
 455                pack_open_windows, peak_pack_open_windows,
 456                sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
 457}
 458
 459static int check_packed_git_idx(const char *path,  struct packed_git *p)
 460{
 461        void *idx_map;
 462        struct pack_idx_header *hdr;
 463        size_t idx_size;
 464        uint32_t version, nr, i, *index;
 465        int fd = open(path, O_RDONLY);
 466        struct stat st;
 467
 468        if (fd < 0)
 469                return -1;
 470        if (fstat(fd, &st)) {
 471                close(fd);
 472                return -1;
 473        }
 474        idx_size = xsize_t(st.st_size);
 475        if (idx_size < 4 * 256 + 20 + 20) {
 476                close(fd);
 477                return error("index file %s is too small", path);
 478        }
 479        idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
 480        close(fd);
 481
 482        hdr = idx_map;
 483        if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
 484                version = ntohl(hdr->idx_version);
 485                if (version < 2 || version > 2) {
 486                        munmap(idx_map, idx_size);
 487                        return error("index file %s is version %"PRIu32
 488                                     " and is not supported by this binary"
 489                                     " (try upgrading GIT to a newer version)",
 490                                     path, version);
 491                }
 492        } else
 493                version = 1;
 494
 495        nr = 0;
 496        index = idx_map;
 497        if (version > 1)
 498                index += 2;  /* skip index header */
 499        for (i = 0; i < 256; i++) {
 500                uint32_t n = ntohl(index[i]);
 501                if (n < nr) {
 502                        munmap(idx_map, idx_size);
 503                        return error("non-monotonic index %s", path);
 504                }
 505                nr = n;
 506        }
 507
 508        if (version == 1) {
 509                /*
 510                 * Total size:
 511                 *  - 256 index entries 4 bytes each
 512                 *  - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
 513                 *  - 20-byte SHA1 of the packfile
 514                 *  - 20-byte SHA1 file checksum
 515                 */
 516                if (idx_size != 4*256 + nr * 24 + 20 + 20) {
 517                        munmap(idx_map, idx_size);
 518                        return error("wrong index v1 file size in %s", path);
 519                }
 520        } else if (version == 2) {
 521                /*
 522                 * Minimum size:
 523                 *  - 8 bytes of header
 524                 *  - 256 index entries 4 bytes each
 525                 *  - 20-byte sha1 entry * nr
 526                 *  - 4-byte crc entry * nr
 527                 *  - 4-byte offset entry * nr
 528                 *  - 20-byte SHA1 of the packfile
 529                 *  - 20-byte SHA1 file checksum
 530                 * And after the 4-byte offset table might be a
 531                 * variable sized table containing 8-byte entries
 532                 * for offsets larger than 2^31.
 533                 */
 534                unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
 535                unsigned long max_size = min_size;
 536                if (nr)
 537                        max_size += (nr - 1)*8;
 538                if (idx_size < min_size || idx_size > max_size) {
 539                        munmap(idx_map, idx_size);
 540                        return error("wrong index v2 file size in %s", path);
 541                }
 542                if (idx_size != min_size &&
 543                    /*
 544                     * make sure we can deal with large pack offsets.
 545                     * 31-bit signed offset won't be enough, neither
 546                     * 32-bit unsigned one will be.
 547                     */
 548                    (sizeof(off_t) <= 4)) {
 549                        munmap(idx_map, idx_size);
 550                        return error("pack too large for current definition of off_t in %s", path);
 551                }
 552        }
 553
 554        p->index_version = version;
 555        p->index_data = idx_map;
 556        p->index_size = idx_size;
 557        p->num_objects = nr;
 558        return 0;
 559}
 560
 561int open_pack_index(struct packed_git *p)
 562{
 563        char *idx_name;
 564        int ret;
 565
 566        if (p->index_data)
 567                return 0;
 568
 569        idx_name = xstrdup(p->pack_name);
 570        strcpy(idx_name + strlen(idx_name) - strlen(".pack"), ".idx");
 571        ret = check_packed_git_idx(idx_name, p);
 572        free(idx_name);
 573        return ret;
 574}
 575
 576static void scan_windows(struct packed_git *p,
 577        struct packed_git **lru_p,
 578        struct pack_window **lru_w,
 579        struct pack_window **lru_l)
 580{
 581        struct pack_window *w, *w_l;
 582
 583        for (w_l = NULL, w = p->windows; w; w = w->next) {
 584                if (!w->inuse_cnt) {
 585                        if (!*lru_w || w->last_used < (*lru_w)->last_used) {
 586                                *lru_p = p;
 587                                *lru_w = w;
 588                                *lru_l = w_l;
 589                        }
 590                }
 591                w_l = w;
 592        }
 593}
 594
 595static int unuse_one_window(struct packed_git *current, int keep_fd)
 596{
 597        struct packed_git *p, *lru_p = NULL;
 598        struct pack_window *lru_w = NULL, *lru_l = NULL;
 599
 600        if (current)
 601                scan_windows(current, &lru_p, &lru_w, &lru_l);
 602        for (p = packed_git; p; p = p->next)
 603                scan_windows(p, &lru_p, &lru_w, &lru_l);
 604        if (lru_p) {
 605                munmap(lru_w->base, lru_w->len);
 606                pack_mapped -= lru_w->len;
 607                if (lru_l)
 608                        lru_l->next = lru_w->next;
 609                else {
 610                        lru_p->windows = lru_w->next;
 611                        if (!lru_p->windows && lru_p->pack_fd != keep_fd) {
 612                                close(lru_p->pack_fd);
 613                                lru_p->pack_fd = -1;
 614                        }
 615                }
 616                free(lru_w);
 617                pack_open_windows--;
 618                return 1;
 619        }
 620        return 0;
 621}
 622
 623void release_pack_memory(size_t need, int fd)
 624{
 625        size_t cur = pack_mapped;
 626        while (need >= (cur - pack_mapped) && unuse_one_window(NULL, fd))
 627                ; /* nothing */
 628}
 629
 630void close_pack_windows(struct packed_git *p)
 631{
 632        while (p->windows) {
 633                struct pack_window *w = p->windows;
 634
 635                if (w->inuse_cnt)
 636                        die("pack '%s' still has open windows to it",
 637                            p->pack_name);
 638                munmap(w->base, w->len);
 639                pack_mapped -= w->len;
 640                pack_open_windows--;
 641                p->windows = w->next;
 642                free(w);
 643        }
 644}
 645
 646void unuse_pack(struct pack_window **w_cursor)
 647{
 648        struct pack_window *w = *w_cursor;
 649        if (w) {
 650                w->inuse_cnt--;
 651                *w_cursor = NULL;
 652        }
 653}
 654
 655/*
 656 * Do not call this directly as this leaks p->pack_fd on error return;
 657 * call open_packed_git() instead.
 658 */
 659static int open_packed_git_1(struct packed_git *p)
 660{
 661        struct stat st;
 662        struct pack_header hdr;
 663        unsigned char sha1[20];
 664        unsigned char *idx_sha1;
 665        long fd_flag;
 666
 667        if (!p->index_data && open_pack_index(p))
 668                return error("packfile %s index unavailable", p->pack_name);
 669
 670        p->pack_fd = open(p->pack_name, O_RDONLY);
 671        if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
 672                return -1;
 673
 674        /* If we created the struct before we had the pack we lack size. */
 675        if (!p->pack_size) {
 676                if (!S_ISREG(st.st_mode))
 677                        return error("packfile %s not a regular file", p->pack_name);
 678                p->pack_size = st.st_size;
 679        } else if (p->pack_size != st.st_size)
 680                return error("packfile %s size changed", p->pack_name);
 681
 682        /* We leave these file descriptors open with sliding mmap;
 683         * there is no point keeping them open across exec(), though.
 684         */
 685        fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
 686        if (fd_flag < 0)
 687                return error("cannot determine file descriptor flags");
 688        fd_flag |= FD_CLOEXEC;
 689        if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
 690                return error("cannot set FD_CLOEXEC");
 691
 692        /* Verify we recognize this pack file format. */
 693        if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
 694                return error("file %s is far too short to be a packfile", p->pack_name);
 695        if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
 696                return error("file %s is not a GIT packfile", p->pack_name);
 697        if (!pack_version_ok(hdr.hdr_version))
 698                return error("packfile %s is version %"PRIu32" and not"
 699                        " supported (try upgrading GIT to a newer version)",
 700                        p->pack_name, ntohl(hdr.hdr_version));
 701
 702        /* Verify the pack matches its index. */
 703        if (p->num_objects != ntohl(hdr.hdr_entries))
 704                return error("packfile %s claims to have %"PRIu32" objects"
 705                             " while index indicates %"PRIu32" objects",
 706                             p->pack_name, ntohl(hdr.hdr_entries),
 707                             p->num_objects);
 708        if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
 709                return error("end of packfile %s is unavailable", p->pack_name);
 710        if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
 711                return error("packfile %s signature is unavailable", p->pack_name);
 712        idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
 713        if (hashcmp(sha1, idx_sha1))
 714                return error("packfile %s does not match index", p->pack_name);
 715        return 0;
 716}
 717
 718static int open_packed_git(struct packed_git *p)
 719{
 720        if (!open_packed_git_1(p))
 721                return 0;
 722        if (p->pack_fd != -1) {
 723                close(p->pack_fd);
 724                p->pack_fd = -1;
 725        }
 726        return -1;
 727}
 728
 729static int in_window(struct pack_window *win, off_t offset)
 730{
 731        /* We must promise at least 20 bytes (one hash) after the
 732         * offset is available from this window, otherwise the offset
 733         * is not actually in this window and a different window (which
 734         * has that one hash excess) must be used.  This is to support
 735         * the object header and delta base parsing routines below.
 736         */
 737        off_t win_off = win->offset;
 738        return win_off <= offset
 739                && (offset + 20) <= (win_off + win->len);
 740}
 741
 742unsigned char* use_pack(struct packed_git *p,
 743                struct pack_window **w_cursor,
 744                off_t offset,
 745                unsigned int *left)
 746{
 747        struct pack_window *win = *w_cursor;
 748
 749        if (p->pack_fd == -1 && open_packed_git(p))
 750                die("packfile %s cannot be accessed", p->pack_name);
 751
 752        /* Since packfiles end in a hash of their content and its
 753         * pointless to ask for an offset into the middle of that
 754         * hash, and the in_window function above wouldn't match
 755         * don't allow an offset too close to the end of the file.
 756         */
 757        if (offset > (p->pack_size - 20))
 758                die("offset beyond end of packfile (truncated pack?)");
 759
 760        if (!win || !in_window(win, offset)) {
 761                if (win)
 762                        win->inuse_cnt--;
 763                for (win = p->windows; win; win = win->next) {
 764                        if (in_window(win, offset))
 765                                break;
 766                }
 767                if (!win) {
 768                        size_t window_align = packed_git_window_size / 2;
 769                        off_t len;
 770                        win = xcalloc(1, sizeof(*win));
 771                        win->offset = (offset / window_align) * window_align;
 772                        len = p->pack_size - win->offset;
 773                        if (len > packed_git_window_size)
 774                                len = packed_git_window_size;
 775                        win->len = (size_t)len;
 776                        pack_mapped += win->len;
 777                        while (packed_git_limit < pack_mapped
 778                                && unuse_one_window(p, p->pack_fd))
 779                                ; /* nothing */
 780                        win->base = xmmap(NULL, win->len,
 781                                PROT_READ, MAP_PRIVATE,
 782                                p->pack_fd, win->offset);
 783                        if (win->base == MAP_FAILED)
 784                                die("packfile %s cannot be mapped: %s",
 785                                        p->pack_name,
 786                                        strerror(errno));
 787                        pack_mmap_calls++;
 788                        pack_open_windows++;
 789                        if (pack_mapped > peak_pack_mapped)
 790                                peak_pack_mapped = pack_mapped;
 791                        if (pack_open_windows > peak_pack_open_windows)
 792                                peak_pack_open_windows = pack_open_windows;
 793                        win->next = p->windows;
 794                        p->windows = win;
 795                }
 796        }
 797        if (win != *w_cursor) {
 798                win->last_used = pack_used_ctr++;
 799                win->inuse_cnt++;
 800                *w_cursor = win;
 801        }
 802        offset -= win->offset;
 803        if (left)
 804                *left = win->len - xsize_t(offset);
 805        return win->base + offset;
 806}
 807
 808static struct packed_git *alloc_packed_git(int extra)
 809{
 810        struct packed_git *p = xmalloc(sizeof(*p) + extra);
 811        memset(p, 0, sizeof(*p));
 812        p->pack_fd = -1;
 813        return p;
 814}
 815
 816struct packed_git *add_packed_git(const char *path, int path_len, int local)
 817{
 818        struct stat st;
 819        struct packed_git *p = alloc_packed_git(path_len + 2);
 820
 821        /*
 822         * Make sure a corresponding .pack file exists and that
 823         * the index looks sane.
 824         */
 825        path_len -= strlen(".idx");
 826        if (path_len < 1) {
 827                free(p);
 828                return NULL;
 829        }
 830        memcpy(p->pack_name, path, path_len);
 831
 832        strcpy(p->pack_name + path_len, ".keep");
 833        if (!access(p->pack_name, F_OK))
 834                p->pack_keep = 1;
 835
 836        strcpy(p->pack_name + path_len, ".pack");
 837        if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
 838                free(p);
 839                return NULL;
 840        }
 841
 842        /* ok, it looks sane as far as we can check without
 843         * actually mapping the pack file.
 844         */
 845        p->pack_size = st.st_size;
 846        p->pack_local = local;
 847        p->mtime = st.st_mtime;
 848        if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
 849                hashclr(p->sha1);
 850        return p;
 851}
 852
 853struct packed_git *parse_pack_index(unsigned char *sha1)
 854{
 855        const char *idx_path = sha1_pack_index_name(sha1);
 856        const char *path = sha1_pack_name(sha1);
 857        struct packed_git *p = alloc_packed_git(strlen(path) + 1);
 858
 859        strcpy(p->pack_name, path);
 860        hashcpy(p->sha1, sha1);
 861        if (check_packed_git_idx(idx_path, p)) {
 862                free(p);
 863                return NULL;
 864        }
 865
 866        return p;
 867}
 868
 869void install_packed_git(struct packed_git *pack)
 870{
 871        pack->next = packed_git;
 872        packed_git = pack;
 873}
 874
 875static void prepare_packed_git_one(char *objdir, int local)
 876{
 877        /* Ensure that this buffer is large enough so that we can
 878           append "/pack/" without clobbering the stack even if
 879           strlen(objdir) were PATH_MAX.  */
 880        char path[PATH_MAX + 1 + 4 + 1 + 1];
 881        int len;
 882        DIR *dir;
 883        struct dirent *de;
 884
 885        sprintf(path, "%s/pack", objdir);
 886        len = strlen(path);
 887        dir = opendir(path);
 888        if (!dir) {
 889                if (errno != ENOENT)
 890                        error("unable to open object pack directory: %s: %s",
 891                              path, strerror(errno));
 892                return;
 893        }
 894        path[len++] = '/';
 895        while ((de = readdir(dir)) != NULL) {
 896                int namelen = strlen(de->d_name);
 897                struct packed_git *p;
 898
 899                if (!has_extension(de->d_name, ".idx"))
 900                        continue;
 901
 902                if (len + namelen + 1 > sizeof(path))
 903                        continue;
 904
 905                /* Don't reopen a pack we already have. */
 906                strcpy(path + len, de->d_name);
 907                for (p = packed_git; p; p = p->next) {
 908                        if (!memcmp(path, p->pack_name, len + namelen - 4))
 909                                break;
 910                }
 911                if (p)
 912                        continue;
 913                /* See if it really is a valid .idx file with corresponding
 914                 * .pack file that we can map.
 915                 */
 916                p = add_packed_git(path, len + namelen, local);
 917                if (!p)
 918                        continue;
 919                install_packed_git(p);
 920        }
 921        closedir(dir);
 922}
 923
 924static int sort_pack(const void *a_, const void *b_)
 925{
 926        struct packed_git *a = *((struct packed_git **)a_);
 927        struct packed_git *b = *((struct packed_git **)b_);
 928        int st;
 929
 930        /*
 931         * Local packs tend to contain objects specific to our
 932         * variant of the project than remote ones.  In addition,
 933         * remote ones could be on a network mounted filesystem.
 934         * Favor local ones for these reasons.
 935         */
 936        st = a->pack_local - b->pack_local;
 937        if (st)
 938                return -st;
 939
 940        /*
 941         * Younger packs tend to contain more recent objects,
 942         * and more recent objects tend to get accessed more
 943         * often.
 944         */
 945        if (a->mtime < b->mtime)
 946                return 1;
 947        else if (a->mtime == b->mtime)
 948                return 0;
 949        return -1;
 950}
 951
 952static void rearrange_packed_git(void)
 953{
 954        struct packed_git **ary, *p;
 955        int i, n;
 956
 957        for (n = 0, p = packed_git; p; p = p->next)
 958                n++;
 959        if (n < 2)
 960                return;
 961
 962        /* prepare an array of packed_git for easier sorting */
 963        ary = xcalloc(n, sizeof(struct packed_git *));
 964        for (n = 0, p = packed_git; p; p = p->next)
 965                ary[n++] = p;
 966
 967        qsort(ary, n, sizeof(struct packed_git *), sort_pack);
 968
 969        /* link them back again */
 970        for (i = 0; i < n - 1; i++)
 971                ary[i]->next = ary[i + 1];
 972        ary[n - 1]->next = NULL;
 973        packed_git = ary[0];
 974
 975        free(ary);
 976}
 977
 978static int prepare_packed_git_run_once = 0;
 979void prepare_packed_git(void)
 980{
 981        struct alternate_object_database *alt;
 982
 983        if (prepare_packed_git_run_once)
 984                return;
 985        prepare_packed_git_one(get_object_directory(), 1);
 986        prepare_alt_odb();
 987        for (alt = alt_odb_list; alt; alt = alt->next) {
 988                alt->name[-1] = 0;
 989                prepare_packed_git_one(alt->base, 0);
 990                alt->name[-1] = '/';
 991        }
 992        rearrange_packed_git();
 993        prepare_packed_git_run_once = 1;
 994}
 995
 996void reprepare_packed_git(void)
 997{
 998        discard_revindex();
 999        prepare_packed_git_run_once = 0;
1000        prepare_packed_git();
1001}
1002
1003static void mark_bad_packed_object(struct packed_git *p,
1004                                   const unsigned char *sha1)
1005{
1006        unsigned i;
1007        for (i = 0; i < p->num_bad_objects; i++)
1008                if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1009                        return;
1010        p->bad_object_sha1 = xrealloc(p->bad_object_sha1, 20 * (p->num_bad_objects + 1));
1011        hashcpy(p->bad_object_sha1 + 20 * p->num_bad_objects, sha1);
1012        p->num_bad_objects++;
1013}
1014
1015static int has_packed_and_bad(const unsigned char *sha1)
1016{
1017        struct packed_git *p;
1018        unsigned i;
1019
1020        for (p = packed_git; p; p = p->next)
1021                for (i = 0; i < p->num_bad_objects; i++)
1022                        if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1023                                return 1;
1024        return 0;
1025}
1026
1027int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
1028{
1029        unsigned char real_sha1[20];
1030        hash_sha1_file(map, size, type, real_sha1);
1031        return hashcmp(sha1, real_sha1) ? -1 : 0;
1032}
1033
1034static int git_open_noatime(const char *name)
1035{
1036        static int sha1_file_open_flag = O_NOATIME;
1037        int fd = open(name, O_RDONLY | sha1_file_open_flag);
1038
1039        /* Might the failure be due to O_NOATIME? */
1040        if (fd < 0 && errno != ENOENT && sha1_file_open_flag) {
1041                fd = open(name, O_RDONLY);
1042                if (fd >= 0)
1043                        sha1_file_open_flag = 0;
1044        }
1045        return fd;
1046}
1047
1048static int open_sha1_file(const unsigned char *sha1)
1049{
1050        int fd;
1051        char *name = sha1_file_name(sha1);
1052        struct alternate_object_database *alt;
1053
1054        fd = git_open_noatime(name);
1055        if (fd >= 0)
1056                return fd;
1057
1058        prepare_alt_odb();
1059        errno = ENOENT;
1060        for (alt = alt_odb_list; alt; alt = alt->next) {
1061                name = alt->name;
1062                fill_sha1_path(name, sha1);
1063                fd = git_open_noatime(alt->base);
1064                if (fd >= 0)
1065                        return fd;
1066        }
1067        return -1;
1068}
1069
1070static void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1071{
1072        void *map;
1073        int fd;
1074
1075        fd = open_sha1_file(sha1);
1076        map = NULL;
1077        if (fd >= 0) {
1078                struct stat st;
1079
1080                if (!fstat(fd, &st)) {
1081                        *size = xsize_t(st.st_size);
1082                        map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1083                }
1084                close(fd);
1085        }
1086        return map;
1087}
1088
1089static int legacy_loose_object(unsigned char *map)
1090{
1091        unsigned int word;
1092
1093        /*
1094         * Is it a zlib-compressed buffer? If so, the first byte
1095         * must be 0x78 (15-bit window size, deflated), and the
1096         * first 16-bit word is evenly divisible by 31
1097         */
1098        word = (map[0] << 8) + map[1];
1099        if (map[0] == 0x78 && !(word % 31))
1100                return 1;
1101        else
1102                return 0;
1103}
1104
1105unsigned long unpack_object_header_gently(const unsigned char *buf, unsigned long len, enum object_type *type, unsigned long *sizep)
1106{
1107        unsigned shift;
1108        unsigned char c;
1109        unsigned long size;
1110        unsigned long used = 0;
1111
1112        c = buf[used++];
1113        *type = (c >> 4) & 7;
1114        size = c & 15;
1115        shift = 4;
1116        while (c & 0x80) {
1117                if (len <= used)
1118                        return 0;
1119                if (sizeof(long) * 8 <= shift)
1120                        return 0;
1121                c = buf[used++];
1122                size += (c & 0x7f) << shift;
1123                shift += 7;
1124        }
1125        *sizep = size;
1126        return used;
1127}
1128
1129static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1130{
1131        unsigned long size, used;
1132        static const char valid_loose_object_type[8] = {
1133                0, /* OBJ_EXT */
1134                1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
1135                0, /* "delta" and others are invalid in a loose object */
1136        };
1137        enum object_type type;
1138
1139        /* Get the data stream */
1140        memset(stream, 0, sizeof(*stream));
1141        stream->next_in = map;
1142        stream->avail_in = mapsize;
1143        stream->next_out = buffer;
1144        stream->avail_out = bufsiz;
1145
1146        if (legacy_loose_object(map)) {
1147                inflateInit(stream);
1148                return inflate(stream, 0);
1149        }
1150
1151
1152        /*
1153         * There used to be a second loose object header format which
1154         * was meant to mimic the in-pack format, allowing for direct
1155         * copy of the object data.  This format turned up not to be
1156         * really worth it and we don't write it any longer.  But we
1157         * can still read it.
1158         */
1159        used = unpack_object_header_gently(map, mapsize, &type, &size);
1160        if (!used || !valid_loose_object_type[type])
1161                return -1;
1162        map += used;
1163        mapsize -= used;
1164
1165        /* Set up the stream for the rest.. */
1166        stream->next_in = map;
1167        stream->avail_in = mapsize;
1168        inflateInit(stream);
1169
1170        /* And generate the fake traditional header */
1171        stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
1172                                         typename(type), size);
1173        return 0;
1174}
1175
1176static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1177{
1178        int bytes = strlen(buffer) + 1;
1179        unsigned char *buf = xmalloc(1+size);
1180        unsigned long n;
1181        int status = Z_OK;
1182
1183        n = stream->total_out - bytes;
1184        if (n > size)
1185                n = size;
1186        memcpy(buf, (char *) buffer + bytes, n);
1187        bytes = n;
1188        if (bytes <= size) {
1189                /*
1190                 * The above condition must be (bytes <= size), not
1191                 * (bytes < size).  In other words, even though we
1192                 * expect no more output and set avail_out to zer0,
1193                 * the input zlib stream may have bytes that express
1194                 * "this concludes the stream", and we *do* want to
1195                 * eat that input.
1196                 *
1197                 * Otherwise we would not be able to test that we
1198                 * consumed all the input to reach the expected size;
1199                 * we also want to check that zlib tells us that all
1200                 * went well with status == Z_STREAM_END at the end.
1201                 */
1202                stream->next_out = buf + bytes;
1203                stream->avail_out = size - bytes;
1204                while (status == Z_OK)
1205                        status = inflate(stream, Z_FINISH);
1206        }
1207        buf[size] = 0;
1208        if (status == Z_STREAM_END && !stream->avail_in) {
1209                inflateEnd(stream);
1210                return buf;
1211        }
1212
1213        if (status < 0)
1214                error("corrupt loose object '%s'", sha1_to_hex(sha1));
1215        else if (stream->avail_in)
1216                error("garbage at end of loose object '%s'",
1217                      sha1_to_hex(sha1));
1218        free(buf);
1219        return NULL;
1220}
1221
1222/*
1223 * We used to just use "sscanf()", but that's actually way
1224 * too permissive for what we want to check. So do an anal
1225 * object header parse by hand.
1226 */
1227static int parse_sha1_header(const char *hdr, unsigned long *sizep)
1228{
1229        char type[10];
1230        int i;
1231        unsigned long size;
1232
1233        /*
1234         * The type can be at most ten bytes (including the
1235         * terminating '\0' that we add), and is followed by
1236         * a space.
1237         */
1238        i = 0;
1239        for (;;) {
1240                char c = *hdr++;
1241                if (c == ' ')
1242                        break;
1243                type[i++] = c;
1244                if (i >= sizeof(type))
1245                        return -1;
1246        }
1247        type[i] = 0;
1248
1249        /*
1250         * The length must follow immediately, and be in canonical
1251         * decimal format (ie "010" is not valid).
1252         */
1253        size = *hdr++ - '0';
1254        if (size > 9)
1255                return -1;
1256        if (size) {
1257                for (;;) {
1258                        unsigned long c = *hdr - '0';
1259                        if (c > 9)
1260                                break;
1261                        hdr++;
1262                        size = size * 10 + c;
1263                }
1264        }
1265        *sizep = size;
1266
1267        /*
1268         * The length must be followed by a zero byte
1269         */
1270        return *hdr ? -1 : type_from_string(type);
1271}
1272
1273static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1274{
1275        int ret;
1276        z_stream stream;
1277        char hdr[8192];
1278
1279        ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1280        if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1281                return NULL;
1282
1283        return unpack_sha1_rest(&stream, hdr, *size, sha1);
1284}
1285
1286unsigned long get_size_from_delta(struct packed_git *p,
1287                                  struct pack_window **w_curs,
1288                                  off_t curpos)
1289{
1290        const unsigned char *data;
1291        unsigned char delta_head[20], *in;
1292        z_stream stream;
1293        int st;
1294
1295        memset(&stream, 0, sizeof(stream));
1296        stream.next_out = delta_head;
1297        stream.avail_out = sizeof(delta_head);
1298
1299        inflateInit(&stream);
1300        do {
1301                in = use_pack(p, w_curs, curpos, &stream.avail_in);
1302                stream.next_in = in;
1303                st = inflate(&stream, Z_FINISH);
1304                curpos += stream.next_in - in;
1305        } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1306                 stream.total_out < sizeof(delta_head));
1307        inflateEnd(&stream);
1308        if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head))
1309                die("delta data unpack-initial failed");
1310
1311        /* Examine the initial part of the delta to figure out
1312         * the result size.
1313         */
1314        data = delta_head;
1315
1316        /* ignore base size */
1317        get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1318
1319        /* Read the result size */
1320        return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1321}
1322
1323static off_t get_delta_base(struct packed_git *p,
1324                                    struct pack_window **w_curs,
1325                                    off_t *curpos,
1326                                    enum object_type type,
1327                                    off_t delta_obj_offset)
1328{
1329        unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1330        off_t base_offset;
1331
1332        /* use_pack() assured us we have [base_info, base_info + 20)
1333         * as a range that we can look at without walking off the
1334         * end of the mapped window.  Its actually the hash size
1335         * that is assured.  An OFS_DELTA longer than the hash size
1336         * is stupid, as then a REF_DELTA would be smaller to store.
1337         */
1338        if (type == OBJ_OFS_DELTA) {
1339                unsigned used = 0;
1340                unsigned char c = base_info[used++];
1341                base_offset = c & 127;
1342                while (c & 128) {
1343                        base_offset += 1;
1344                        if (!base_offset || MSB(base_offset, 7))
1345                                return 0;  /* overflow */
1346                        c = base_info[used++];
1347                        base_offset = (base_offset << 7) + (c & 127);
1348                }
1349                base_offset = delta_obj_offset - base_offset;
1350                if (base_offset >= delta_obj_offset)
1351                        return 0;  /* out of bound */
1352                *curpos += used;
1353        } else if (type == OBJ_REF_DELTA) {
1354                /* The base entry _must_ be in the same pack */
1355                base_offset = find_pack_entry_one(base_info, p);
1356                *curpos += 20;
1357        } else
1358                die("I am totally screwed");
1359        return base_offset;
1360}
1361
1362/* forward declaration for a mutually recursive function */
1363static int packed_object_info(struct packed_git *p, off_t offset,
1364                              unsigned long *sizep);
1365
1366static int packed_delta_info(struct packed_git *p,
1367                             struct pack_window **w_curs,
1368                             off_t curpos,
1369                             enum object_type type,
1370                             off_t obj_offset,
1371                             unsigned long *sizep)
1372{
1373        off_t base_offset;
1374
1375        base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1376        type = packed_object_info(p, base_offset, NULL);
1377
1378        /* We choose to only get the type of the base object and
1379         * ignore potentially corrupt pack file that expects the delta
1380         * based on a base with a wrong size.  This saves tons of
1381         * inflate() calls.
1382         */
1383        if (sizep)
1384                *sizep = get_size_from_delta(p, w_curs, curpos);
1385
1386        return type;
1387}
1388
1389static int unpack_object_header(struct packed_git *p,
1390                                struct pack_window **w_curs,
1391                                off_t *curpos,
1392                                unsigned long *sizep)
1393{
1394        unsigned char *base;
1395        unsigned int left;
1396        unsigned long used;
1397        enum object_type type;
1398
1399        /* use_pack() assures us we have [base, base + 20) available
1400         * as a range that we can look at at.  (Its actually the hash
1401         * size that is assured.)  With our object header encoding
1402         * the maximum deflated object size is 2^137, which is just
1403         * insane, so we know won't exceed what we have been given.
1404         */
1405        base = use_pack(p, w_curs, *curpos, &left);
1406        used = unpack_object_header_gently(base, left, &type, sizep);
1407        if (!used)
1408                die("object offset outside of pack file");
1409        *curpos += used;
1410
1411        return type;
1412}
1413
1414const char *packed_object_info_detail(struct packed_git *p,
1415                                      off_t obj_offset,
1416                                      unsigned long *size,
1417                                      unsigned long *store_size,
1418                                      unsigned int *delta_chain_length,
1419                                      unsigned char *base_sha1)
1420{
1421        struct pack_window *w_curs = NULL;
1422        off_t curpos;
1423        unsigned long dummy;
1424        unsigned char *next_sha1;
1425        enum object_type type;
1426        struct revindex_entry *revidx;
1427
1428        *delta_chain_length = 0;
1429        curpos = obj_offset;
1430        type = unpack_object_header(p, &w_curs, &curpos, size);
1431
1432        revidx = find_pack_revindex(p, obj_offset);
1433        *store_size = revidx[1].offset - obj_offset;
1434
1435        for (;;) {
1436                switch (type) {
1437                default:
1438                        die("pack %s contains unknown object type %d",
1439                            p->pack_name, type);
1440                case OBJ_COMMIT:
1441                case OBJ_TREE:
1442                case OBJ_BLOB:
1443                case OBJ_TAG:
1444                        unuse_pack(&w_curs);
1445                        return typename(type);
1446                case OBJ_OFS_DELTA:
1447                        obj_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1448                        if (!obj_offset)
1449                                die("pack %s contains bad delta base reference of type %s",
1450                                    p->pack_name, typename(type));
1451                        if (*delta_chain_length == 0) {
1452                                revidx = find_pack_revindex(p, obj_offset);
1453                                hashcpy(base_sha1, nth_packed_object_sha1(p, revidx->nr));
1454                        }
1455                        break;
1456                case OBJ_REF_DELTA:
1457                        next_sha1 = use_pack(p, &w_curs, curpos, NULL);
1458                        if (*delta_chain_length == 0)
1459                                hashcpy(base_sha1, next_sha1);
1460                        obj_offset = find_pack_entry_one(next_sha1, p);
1461                        break;
1462                }
1463                (*delta_chain_length)++;
1464                curpos = obj_offset;
1465                type = unpack_object_header(p, &w_curs, &curpos, &dummy);
1466        }
1467}
1468
1469static int packed_object_info(struct packed_git *p, off_t obj_offset,
1470                              unsigned long *sizep)
1471{
1472        struct pack_window *w_curs = NULL;
1473        unsigned long size;
1474        off_t curpos = obj_offset;
1475        enum object_type type;
1476
1477        type = unpack_object_header(p, &w_curs, &curpos, &size);
1478
1479        switch (type) {
1480        case OBJ_OFS_DELTA:
1481        case OBJ_REF_DELTA:
1482                type = packed_delta_info(p, &w_curs, curpos,
1483                                         type, obj_offset, sizep);
1484                break;
1485        case OBJ_COMMIT:
1486        case OBJ_TREE:
1487        case OBJ_BLOB:
1488        case OBJ_TAG:
1489                if (sizep)
1490                        *sizep = size;
1491                break;
1492        default:
1493                die("pack %s contains unknown object type %d",
1494                    p->pack_name, type);
1495        }
1496        unuse_pack(&w_curs);
1497        return type;
1498}
1499
1500static void *unpack_compressed_entry(struct packed_git *p,
1501                                    struct pack_window **w_curs,
1502                                    off_t curpos,
1503                                    unsigned long size)
1504{
1505        int st;
1506        z_stream stream;
1507        unsigned char *buffer, *in;
1508
1509        buffer = xmalloc(size + 1);
1510        buffer[size] = 0;
1511        memset(&stream, 0, sizeof(stream));
1512        stream.next_out = buffer;
1513        stream.avail_out = size;
1514
1515        inflateInit(&stream);
1516        do {
1517                in = use_pack(p, w_curs, curpos, &stream.avail_in);
1518                stream.next_in = in;
1519                st = inflate(&stream, Z_FINISH);
1520                curpos += stream.next_in - in;
1521        } while (st == Z_OK || st == Z_BUF_ERROR);
1522        inflateEnd(&stream);
1523        if ((st != Z_STREAM_END) || stream.total_out != size) {
1524                free(buffer);
1525                return NULL;
1526        }
1527
1528        return buffer;
1529}
1530
1531#define MAX_DELTA_CACHE (256)
1532
1533static size_t delta_base_cached;
1534
1535static struct delta_base_cache_lru_list {
1536        struct delta_base_cache_lru_list *prev;
1537        struct delta_base_cache_lru_list *next;
1538} delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
1539
1540static struct delta_base_cache_entry {
1541        struct delta_base_cache_lru_list lru;
1542        void *data;
1543        struct packed_git *p;
1544        off_t base_offset;
1545        unsigned long size;
1546        enum object_type type;
1547} delta_base_cache[MAX_DELTA_CACHE];
1548
1549static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
1550{
1551        unsigned long hash;
1552
1553        hash = (unsigned long)p + (unsigned long)base_offset;
1554        hash += (hash >> 8) + (hash >> 16);
1555        return hash % MAX_DELTA_CACHE;
1556}
1557
1558static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
1559        unsigned long *base_size, enum object_type *type, int keep_cache)
1560{
1561        void *ret;
1562        unsigned long hash = pack_entry_hash(p, base_offset);
1563        struct delta_base_cache_entry *ent = delta_base_cache + hash;
1564
1565        ret = ent->data;
1566        if (ret && ent->p == p && ent->base_offset == base_offset)
1567                goto found_cache_entry;
1568        return unpack_entry(p, base_offset, type, base_size);
1569
1570found_cache_entry:
1571        if (!keep_cache) {
1572                ent->data = NULL;
1573                ent->lru.next->prev = ent->lru.prev;
1574                ent->lru.prev->next = ent->lru.next;
1575                delta_base_cached -= ent->size;
1576        } else {
1577                ret = xmemdupz(ent->data, ent->size);
1578        }
1579        *type = ent->type;
1580        *base_size = ent->size;
1581        return ret;
1582}
1583
1584static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1585{
1586        if (ent->data) {
1587                free(ent->data);
1588                ent->data = NULL;
1589                ent->lru.next->prev = ent->lru.prev;
1590                ent->lru.prev->next = ent->lru.next;
1591                delta_base_cached -= ent->size;
1592        }
1593}
1594
1595static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1596        void *base, unsigned long base_size, enum object_type type)
1597{
1598        unsigned long hash = pack_entry_hash(p, base_offset);
1599        struct delta_base_cache_entry *ent = delta_base_cache + hash;
1600        struct delta_base_cache_lru_list *lru;
1601
1602        release_delta_base_cache(ent);
1603        delta_base_cached += base_size;
1604
1605        for (lru = delta_base_cache_lru.next;
1606             delta_base_cached > delta_base_cache_limit
1607             && lru != &delta_base_cache_lru;
1608             lru = lru->next) {
1609                struct delta_base_cache_entry *f = (void *)lru;
1610                if (f->type == OBJ_BLOB)
1611                        release_delta_base_cache(f);
1612        }
1613        for (lru = delta_base_cache_lru.next;
1614             delta_base_cached > delta_base_cache_limit
1615             && lru != &delta_base_cache_lru;
1616             lru = lru->next) {
1617                struct delta_base_cache_entry *f = (void *)lru;
1618                release_delta_base_cache(f);
1619        }
1620
1621        ent->p = p;
1622        ent->base_offset = base_offset;
1623        ent->type = type;
1624        ent->data = base;
1625        ent->size = base_size;
1626        ent->lru.next = &delta_base_cache_lru;
1627        ent->lru.prev = delta_base_cache_lru.prev;
1628        delta_base_cache_lru.prev->next = &ent->lru;
1629        delta_base_cache_lru.prev = &ent->lru;
1630}
1631
1632static void *unpack_delta_entry(struct packed_git *p,
1633                                struct pack_window **w_curs,
1634                                off_t curpos,
1635                                unsigned long delta_size,
1636                                off_t obj_offset,
1637                                enum object_type *type,
1638                                unsigned long *sizep)
1639{
1640        void *delta_data, *result, *base;
1641        unsigned long base_size;
1642        off_t base_offset;
1643
1644        base_offset = get_delta_base(p, w_curs, &curpos, *type, obj_offset);
1645        if (!base_offset) {
1646                error("failed to validate delta base reference "
1647                      "at offset %"PRIuMAX" from %s",
1648                      (uintmax_t)curpos, p->pack_name);
1649                return NULL;
1650        }
1651        unuse_pack(w_curs);
1652        base = cache_or_unpack_entry(p, base_offset, &base_size, type, 0);
1653        if (!base) {
1654                /*
1655                 * We're probably in deep shit, but let's try to fetch
1656                 * the required base anyway from another pack or loose.
1657                 * This is costly but should happen only in the presence
1658                 * of a corrupted pack, and is better than failing outright.
1659                 */
1660                struct revindex_entry *revidx = find_pack_revindex(p, base_offset);
1661                const unsigned char *base_sha1 =
1662                                        nth_packed_object_sha1(p, revidx->nr);
1663                error("failed to read delta base object %s"
1664                      " at offset %"PRIuMAX" from %s",
1665                      sha1_to_hex(base_sha1), (uintmax_t)base_offset,
1666                      p->pack_name);
1667                mark_bad_packed_object(p, base_sha1);
1668                base = read_object(base_sha1, type, &base_size);
1669                if (!base)
1670                        return NULL;
1671        }
1672
1673        delta_data = unpack_compressed_entry(p, w_curs, curpos, delta_size);
1674        if (!delta_data) {
1675                error("failed to unpack compressed delta "
1676                      "at offset %"PRIuMAX" from %s",
1677                      (uintmax_t)curpos, p->pack_name);
1678                free(base);
1679                return NULL;
1680        }
1681        result = patch_delta(base, base_size,
1682                             delta_data, delta_size,
1683                             sizep);
1684        if (!result)
1685                die("failed to apply delta");
1686        free(delta_data);
1687        add_delta_base_cache(p, base_offset, base, base_size, *type);
1688        return result;
1689}
1690
1691void *unpack_entry(struct packed_git *p, off_t obj_offset,
1692                   enum object_type *type, unsigned long *sizep)
1693{
1694        struct pack_window *w_curs = NULL;
1695        off_t curpos = obj_offset;
1696        void *data;
1697
1698        *type = unpack_object_header(p, &w_curs, &curpos, sizep);
1699        switch (*type) {
1700        case OBJ_OFS_DELTA:
1701        case OBJ_REF_DELTA:
1702                data = unpack_delta_entry(p, &w_curs, curpos, *sizep,
1703                                          obj_offset, type, sizep);
1704                break;
1705        case OBJ_COMMIT:
1706        case OBJ_TREE:
1707        case OBJ_BLOB:
1708        case OBJ_TAG:
1709                data = unpack_compressed_entry(p, &w_curs, curpos, *sizep);
1710                break;
1711        default:
1712                data = NULL;
1713                error("unknown object type %i at offset %"PRIuMAX" in %s",
1714                      *type, (uintmax_t)obj_offset, p->pack_name);
1715        }
1716        unuse_pack(&w_curs);
1717        return data;
1718}
1719
1720const unsigned char *nth_packed_object_sha1(struct packed_git *p,
1721                                            uint32_t n)
1722{
1723        const unsigned char *index = p->index_data;
1724        if (!index) {
1725                if (open_pack_index(p))
1726                        return NULL;
1727                index = p->index_data;
1728        }
1729        if (n >= p->num_objects)
1730                return NULL;
1731        index += 4 * 256;
1732        if (p->index_version == 1) {
1733                return index + 24 * n + 4;
1734        } else {
1735                index += 8;
1736                return index + 20 * n;
1737        }
1738}
1739
1740off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1741{
1742        const unsigned char *index = p->index_data;
1743        index += 4 * 256;
1744        if (p->index_version == 1) {
1745                return ntohl(*((uint32_t *)(index + 24 * n)));
1746        } else {
1747                uint32_t off;
1748                index += 8 + p->num_objects * (20 + 4);
1749                off = ntohl(*((uint32_t *)(index + 4 * n)));
1750                if (!(off & 0x80000000))
1751                        return off;
1752                index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1753                return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
1754                                   ntohl(*((uint32_t *)(index + 4)));
1755        }
1756}
1757
1758off_t find_pack_entry_one(const unsigned char *sha1,
1759                                  struct packed_git *p)
1760{
1761        const uint32_t *level1_ofs = p->index_data;
1762        const unsigned char *index = p->index_data;
1763        unsigned hi, lo, stride;
1764        static int use_lookup = -1;
1765        static int debug_lookup = -1;
1766
1767        if (debug_lookup < 0)
1768                debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
1769
1770        if (!index) {
1771                if (open_pack_index(p))
1772                        return 0;
1773                level1_ofs = p->index_data;
1774                index = p->index_data;
1775        }
1776        if (p->index_version > 1) {
1777                level1_ofs += 2;
1778                index += 8;
1779        }
1780        index += 4 * 256;
1781        hi = ntohl(level1_ofs[*sha1]);
1782        lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1783        if (p->index_version > 1) {
1784                stride = 20;
1785        } else {
1786                stride = 24;
1787                index += 4;
1788        }
1789
1790        if (debug_lookup)
1791                printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
1792                       sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
1793
1794        if (use_lookup < 0)
1795                use_lookup = !!getenv("GIT_USE_LOOKUP");
1796        if (use_lookup) {
1797                int pos = sha1_entry_pos(index, stride, 0,
1798                                         lo, hi, p->num_objects, sha1);
1799                if (pos < 0)
1800                        return 0;
1801                return nth_packed_object_offset(p, pos);
1802        }
1803
1804        do {
1805                unsigned mi = (lo + hi) / 2;
1806                int cmp = hashcmp(index + mi * stride, sha1);
1807
1808                if (debug_lookup)
1809                        printf("lo %u hi %u rg %u mi %u\n",
1810                               lo, hi, hi - lo, mi);
1811                if (!cmp)
1812                        return nth_packed_object_offset(p, mi);
1813                if (cmp > 0)
1814                        hi = mi;
1815                else
1816                        lo = mi+1;
1817        } while (lo < hi);
1818        return 0;
1819}
1820
1821int matches_pack_name(struct packed_git *p, const char *name)
1822{
1823        const char *last_c, *c;
1824
1825        if (!strcmp(p->pack_name, name))
1826                return 1;
1827
1828        for (c = p->pack_name, last_c = c; *c;)
1829                if (*c == '/')
1830                        last_c = ++c;
1831                else
1832                        ++c;
1833        if (!strcmp(last_c, name))
1834                return 1;
1835
1836        return 0;
1837}
1838
1839static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e, const char **ignore_packed)
1840{
1841        static struct packed_git *last_found = (void *)1;
1842        struct packed_git *p;
1843        off_t offset;
1844
1845        prepare_packed_git();
1846        if (!packed_git)
1847                return 0;
1848        p = (last_found == (void *)1) ? packed_git : last_found;
1849
1850        do {
1851                if (ignore_packed) {
1852                        const char **ig;
1853                        for (ig = ignore_packed; *ig; ig++)
1854                                if (matches_pack_name(p, *ig))
1855                                        break;
1856                        if (*ig)
1857                                goto next;
1858                }
1859
1860                if (p->num_bad_objects) {
1861                        unsigned i;
1862                        for (i = 0; i < p->num_bad_objects; i++)
1863                                if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1864                                        goto next;
1865                }
1866
1867                offset = find_pack_entry_one(sha1, p);
1868                if (offset) {
1869                        /*
1870                         * We are about to tell the caller where they can
1871                         * locate the requested object.  We better make
1872                         * sure the packfile is still here and can be
1873                         * accessed before supplying that answer, as
1874                         * it may have been deleted since the index
1875                         * was loaded!
1876                         */
1877                        if (p->pack_fd == -1 && open_packed_git(p)) {
1878                                error("packfile %s cannot be accessed", p->pack_name);
1879                                goto next;
1880                        }
1881                        e->offset = offset;
1882                        e->p = p;
1883                        hashcpy(e->sha1, sha1);
1884                        last_found = p;
1885                        return 1;
1886                }
1887
1888                next:
1889                if (p == last_found)
1890                        p = packed_git;
1891                else
1892                        p = p->next;
1893                if (p == last_found)
1894                        p = p->next;
1895        } while (p);
1896        return 0;
1897}
1898
1899struct packed_git *find_sha1_pack(const unsigned char *sha1,
1900                                  struct packed_git *packs)
1901{
1902        struct packed_git *p;
1903
1904        for (p = packs; p; p = p->next) {
1905                if (find_pack_entry_one(sha1, p))
1906                        return p;
1907        }
1908        return NULL;
1909
1910}
1911
1912static int sha1_loose_object_info(const unsigned char *sha1, unsigned long *sizep)
1913{
1914        int status;
1915        unsigned long mapsize, size;
1916        void *map;
1917        z_stream stream;
1918        char hdr[32];
1919
1920        map = map_sha1_file(sha1, &mapsize);
1921        if (!map)
1922                return error("unable to find %s", sha1_to_hex(sha1));
1923        if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1924                status = error("unable to unpack %s header",
1925                               sha1_to_hex(sha1));
1926        else if ((status = parse_sha1_header(hdr, &size)) < 0)
1927                status = error("unable to parse %s header", sha1_to_hex(sha1));
1928        else if (sizep)
1929                *sizep = size;
1930        inflateEnd(&stream);
1931        munmap(map, mapsize);
1932        return status;
1933}
1934
1935int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
1936{
1937        struct pack_entry e;
1938        int status;
1939
1940        if (!find_pack_entry(sha1, &e, NULL)) {
1941                /* Most likely it's a loose object. */
1942                status = sha1_loose_object_info(sha1, sizep);
1943                if (status >= 0)
1944                        return status;
1945
1946                /* Not a loose object; someone else may have just packed it. */
1947                reprepare_packed_git();
1948                if (!find_pack_entry(sha1, &e, NULL))
1949                        return status;
1950        }
1951        return packed_object_info(e.p, e.offset, sizep);
1952}
1953
1954static void *read_packed_sha1(const unsigned char *sha1,
1955                              enum object_type *type, unsigned long *size)
1956{
1957        struct pack_entry e;
1958        void *data;
1959
1960        if (!find_pack_entry(sha1, &e, NULL))
1961                return NULL;
1962        data = cache_or_unpack_entry(e.p, e.offset, size, type, 1);
1963        if (!data) {
1964                /*
1965                 * We're probably in deep shit, but let's try to fetch
1966                 * the required object anyway from another pack or loose.
1967                 * This should happen only in the presence of a corrupted
1968                 * pack, and is better than failing outright.
1969                 */
1970                error("failed to read object %s at offset %"PRIuMAX" from %s",
1971                      sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
1972                mark_bad_packed_object(e.p, sha1);
1973                data = read_object(sha1, type, size);
1974        }
1975        return data;
1976}
1977
1978/*
1979 * This is meant to hold a *small* number of objects that you would
1980 * want read_sha1_file() to be able to return, but yet you do not want
1981 * to write them into the object store (e.g. a browse-only
1982 * application).
1983 */
1984static struct cached_object {
1985        unsigned char sha1[20];
1986        enum object_type type;
1987        void *buf;
1988        unsigned long size;
1989} *cached_objects;
1990static int cached_object_nr, cached_object_alloc;
1991
1992static struct cached_object empty_tree = {
1993        /* empty tree sha1: 4b825dc642cb6eb9a060e54bf8d69288fbee4904 */
1994        "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60"
1995        "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04",
1996        OBJ_TREE,
1997        "",
1998        0
1999};
2000
2001static struct cached_object *find_cached_object(const unsigned char *sha1)
2002{
2003        int i;
2004        struct cached_object *co = cached_objects;
2005
2006        for (i = 0; i < cached_object_nr; i++, co++) {
2007                if (!hashcmp(co->sha1, sha1))
2008                        return co;
2009        }
2010        if (!hashcmp(sha1, empty_tree.sha1))
2011                return &empty_tree;
2012        return NULL;
2013}
2014
2015int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2016                      unsigned char *sha1)
2017{
2018        struct cached_object *co;
2019
2020        hash_sha1_file(buf, len, typename(type), sha1);
2021        if (has_sha1_file(sha1) || find_cached_object(sha1))
2022                return 0;
2023        if (cached_object_alloc <= cached_object_nr) {
2024                cached_object_alloc = alloc_nr(cached_object_alloc);
2025                cached_objects = xrealloc(cached_objects,
2026                                          sizeof(*cached_objects) *
2027                                          cached_object_alloc);
2028        }
2029        co = &cached_objects[cached_object_nr++];
2030        co->size = len;
2031        co->type = type;
2032        co->buf = xmalloc(len);
2033        memcpy(co->buf, buf, len);
2034        hashcpy(co->sha1, sha1);
2035        return 0;
2036}
2037
2038void *read_object(const unsigned char *sha1, enum object_type *type,
2039                  unsigned long *size)
2040{
2041        unsigned long mapsize;
2042        void *map, *buf;
2043        struct cached_object *co;
2044
2045        co = find_cached_object(sha1);
2046        if (co) {
2047                *type = co->type;
2048                *size = co->size;
2049                return xmemdupz(co->buf, co->size);
2050        }
2051
2052        buf = read_packed_sha1(sha1, type, size);
2053        if (buf)
2054                return buf;
2055        map = map_sha1_file(sha1, &mapsize);
2056        if (map) {
2057                buf = unpack_sha1_file(map, mapsize, type, size, sha1);
2058                munmap(map, mapsize);
2059                return buf;
2060        }
2061        reprepare_packed_git();
2062        return read_packed_sha1(sha1, type, size);
2063}
2064
2065void *read_sha1_file(const unsigned char *sha1, enum object_type *type,
2066                     unsigned long *size)
2067{
2068        void *data = read_object(sha1, type, size);
2069        /* legacy behavior is to die on corrupted objects */
2070        if (!data && (has_loose_object(sha1) || has_packed_and_bad(sha1)))
2071                die("object %s is corrupted", sha1_to_hex(sha1));
2072        return data;
2073}
2074
2075void *read_object_with_reference(const unsigned char *sha1,
2076                                 const char *required_type_name,
2077                                 unsigned long *size,
2078                                 unsigned char *actual_sha1_return)
2079{
2080        enum object_type type, required_type;
2081        void *buffer;
2082        unsigned long isize;
2083        unsigned char actual_sha1[20];
2084
2085        required_type = type_from_string(required_type_name);
2086        hashcpy(actual_sha1, sha1);
2087        while (1) {
2088                int ref_length = -1;
2089                const char *ref_type = NULL;
2090
2091                buffer = read_sha1_file(actual_sha1, &type, &isize);
2092                if (!buffer)
2093                        return NULL;
2094                if (type == required_type) {
2095                        *size = isize;
2096                        if (actual_sha1_return)
2097                                hashcpy(actual_sha1_return, actual_sha1);
2098                        return buffer;
2099                }
2100                /* Handle references */
2101                else if (type == OBJ_COMMIT)
2102                        ref_type = "tree ";
2103                else if (type == OBJ_TAG)
2104                        ref_type = "object ";
2105                else {
2106                        free(buffer);
2107                        return NULL;
2108                }
2109                ref_length = strlen(ref_type);
2110
2111                if (ref_length + 40 > isize ||
2112                    memcmp(buffer, ref_type, ref_length) ||
2113                    get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2114                        free(buffer);
2115                        return NULL;
2116                }
2117                free(buffer);
2118                /* Now we have the ID of the referred-to object in
2119                 * actual_sha1.  Check again. */
2120        }
2121}
2122
2123static void write_sha1_file_prepare(const void *buf, unsigned long len,
2124                                    const char *type, unsigned char *sha1,
2125                                    char *hdr, int *hdrlen)
2126{
2127        SHA_CTX c;
2128
2129        /* Generate the header */
2130        *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
2131
2132        /* Sha1.. */
2133        SHA1_Init(&c);
2134        SHA1_Update(&c, hdr, *hdrlen);
2135        SHA1_Update(&c, buf, len);
2136        SHA1_Final(sha1, &c);
2137}
2138
2139/*
2140 * Move the just written object into its final resting place
2141 */
2142int move_temp_to_file(const char *tmpfile, const char *filename)
2143{
2144        int ret = 0;
2145        if (link(tmpfile, filename))
2146                ret = errno;
2147
2148        /*
2149         * Coda hack - coda doesn't like cross-directory links,
2150         * so we fall back to a rename, which will mean that it
2151         * won't be able to check collisions, but that's not a
2152         * big deal.
2153         *
2154         * The same holds for FAT formatted media.
2155         *
2156         * When this succeeds, we just return 0. We have nothing
2157         * left to unlink.
2158         */
2159        if (ret && ret != EEXIST) {
2160                if (!rename(tmpfile, filename))
2161                        return 0;
2162                ret = errno;
2163        }
2164        unlink(tmpfile);
2165        if (ret) {
2166                if (ret != EEXIST) {
2167                        return error("unable to write sha1 filename %s: %s\n", filename, strerror(ret));
2168                }
2169                /* FIXME!!! Collision check here ? */
2170        }
2171
2172        return 0;
2173}
2174
2175static int write_buffer(int fd, const void *buf, size_t len)
2176{
2177        if (write_in_full(fd, buf, len) < 0)
2178                return error("file write error (%s)", strerror(errno));
2179        return 0;
2180}
2181
2182int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2183                   unsigned char *sha1)
2184{
2185        char hdr[32];
2186        int hdrlen;
2187        write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2188        return 0;
2189}
2190
2191/* Finalize a file on disk, and close it. */
2192static void close_sha1_file(int fd)
2193{
2194        if (fsync_object_files)
2195                fsync_or_die(fd, "sha1 file");
2196        fchmod(fd, 0444);
2197        if (close(fd) != 0)
2198                die("unable to write sha1 file");
2199}
2200
2201/* Size of directory component, including the ending '/' */
2202static inline int directory_size(const char *filename)
2203{
2204        const char *s = strrchr(filename, '/');
2205        if (!s)
2206                return 0;
2207        return s - filename + 1;
2208}
2209
2210/*
2211 * This creates a temporary file in the same directory as the final
2212 * 'filename'
2213 *
2214 * We want to avoid cross-directory filename renames, because those
2215 * can have problems on various filesystems (FAT, NFS, Coda).
2216 */
2217static int create_tmpfile(char *buffer, size_t bufsiz, const char *filename)
2218{
2219        int fd, dirlen = directory_size(filename);
2220
2221        if (dirlen + 20 > bufsiz) {
2222                errno = ENAMETOOLONG;
2223                return -1;
2224        }
2225        memcpy(buffer, filename, dirlen);
2226        strcpy(buffer + dirlen, "tmp_obj_XXXXXX");
2227        fd = mkstemp(buffer);
2228        if (fd < 0 && dirlen) {
2229                /* Make sure the directory exists */
2230                memcpy(buffer, filename, dirlen);
2231                buffer[dirlen-1] = 0;
2232                if (mkdir(buffer, 0777) || adjust_shared_perm(buffer))
2233                        return -1;
2234
2235                /* Try again */
2236                strcpy(buffer + dirlen - 1, "/tmp_obj_XXXXXX");
2237                fd = mkstemp(buffer);
2238        }
2239        return fd;
2240}
2241
2242static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
2243                              void *buf, unsigned long len, time_t mtime)
2244{
2245        int fd, size, ret;
2246        unsigned char *compressed;
2247        z_stream stream;
2248        char *filename;
2249        static char tmpfile[PATH_MAX];
2250
2251        filename = sha1_file_name(sha1);
2252        fd = create_tmpfile(tmpfile, sizeof(tmpfile), filename);
2253        if (fd < 0) {
2254                if (errno == EPERM)
2255                        return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2256                else
2257                        return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
2258        }
2259
2260        /* Set it up */
2261        memset(&stream, 0, sizeof(stream));
2262        deflateInit(&stream, zlib_compression_level);
2263        size = 8 + deflateBound(&stream, len+hdrlen);
2264        compressed = xmalloc(size);
2265
2266        /* Compress it */
2267        stream.next_out = compressed;
2268        stream.avail_out = size;
2269
2270        /* First header.. */
2271        stream.next_in = (unsigned char *)hdr;
2272        stream.avail_in = hdrlen;
2273        while (deflate(&stream, 0) == Z_OK)
2274                /* nothing */;
2275
2276        /* Then the data itself.. */
2277        stream.next_in = buf;
2278        stream.avail_in = len;
2279        ret = deflate(&stream, Z_FINISH);
2280        if (ret != Z_STREAM_END)
2281                die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2282
2283        ret = deflateEnd(&stream);
2284        if (ret != Z_OK)
2285                die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2286
2287        size = stream.total_out;
2288
2289        if (write_buffer(fd, compressed, size) < 0)
2290                die("unable to write sha1 file");
2291        close_sha1_file(fd);
2292        free(compressed);
2293
2294        if (mtime) {
2295                struct utimbuf utb;
2296                utb.actime = mtime;
2297                utb.modtime = mtime;
2298                if (utime(tmpfile, &utb) < 0)
2299                        warning("failed utime() on %s: %s",
2300                                tmpfile, strerror(errno));
2301        }
2302
2303        return move_temp_to_file(tmpfile, filename);
2304}
2305
2306int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
2307{
2308        unsigned char sha1[20];
2309        char hdr[32];
2310        int hdrlen;
2311
2312        /* Normally if we have it in the pack then we do not bother writing
2313         * it out into .git/objects/??/?{38} file.
2314         */
2315        write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2316        if (returnsha1)
2317                hashcpy(returnsha1, sha1);
2318        if (has_sha1_file(sha1))
2319                return 0;
2320        return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
2321}
2322
2323int force_object_loose(const unsigned char *sha1, time_t mtime)
2324{
2325        void *buf;
2326        unsigned long len;
2327        enum object_type type;
2328        char hdr[32];
2329        int hdrlen;
2330        int ret;
2331
2332        if (has_loose_object(sha1))
2333                return 0;
2334        buf = read_packed_sha1(sha1, &type, &len);
2335        if (!buf)
2336                return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2337        hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
2338        ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
2339        free(buf);
2340
2341        return ret;
2342}
2343
2344int has_pack_index(const unsigned char *sha1)
2345{
2346        struct stat st;
2347        if (stat(sha1_pack_index_name(sha1), &st))
2348                return 0;
2349        return 1;
2350}
2351
2352int has_pack_file(const unsigned char *sha1)
2353{
2354        struct stat st;
2355        if (stat(sha1_pack_name(sha1), &st))
2356                return 0;
2357        return 1;
2358}
2359
2360int has_sha1_pack(const unsigned char *sha1, const char **ignore_packed)
2361{
2362        struct pack_entry e;
2363        return find_pack_entry(sha1, &e, ignore_packed);
2364}
2365
2366int has_sha1_file(const unsigned char *sha1)
2367{
2368        struct pack_entry e;
2369
2370        if (find_pack_entry(sha1, &e, NULL))
2371                return 1;
2372        return has_loose_object(sha1);
2373}
2374
2375int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
2376{
2377        struct strbuf buf;
2378        int ret;
2379
2380        strbuf_init(&buf, 0);
2381        if (strbuf_read(&buf, fd, 4096) < 0) {
2382                strbuf_release(&buf);
2383                return -1;
2384        }
2385
2386        if (!type)
2387                type = blob_type;
2388        if (write_object)
2389                ret = write_sha1_file(buf.buf, buf.len, type, sha1);
2390        else
2391                ret = hash_sha1_file(buf.buf, buf.len, type, sha1);
2392        strbuf_release(&buf);
2393
2394        return ret;
2395}
2396
2397int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object,
2398             enum object_type type, const char *path)
2399{
2400        size_t size = xsize_t(st->st_size);
2401        void *buf = NULL;
2402        int ret, re_allocated = 0;
2403
2404        if (size)
2405                buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2406        close(fd);
2407
2408        if (!type)
2409                type = OBJ_BLOB;
2410
2411        /*
2412         * Convert blobs to git internal format
2413         */
2414        if ((type == OBJ_BLOB) && S_ISREG(st->st_mode)) {
2415                struct strbuf nbuf;
2416                strbuf_init(&nbuf, 0);
2417                if (convert_to_git(path, buf, size, &nbuf,
2418                                   write_object ? safe_crlf : 0)) {
2419                        munmap(buf, size);
2420                        buf = strbuf_detach(&nbuf, &size);
2421                        re_allocated = 1;
2422                }
2423        }
2424
2425        if (write_object)
2426                ret = write_sha1_file(buf, size, typename(type), sha1);
2427        else
2428                ret = hash_sha1_file(buf, size, typename(type), sha1);
2429        if (re_allocated) {
2430                free(buf);
2431                return ret;
2432        }
2433        if (size)
2434                munmap(buf, size);
2435        return ret;
2436}
2437
2438int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
2439{
2440        int fd;
2441        char *target;
2442        size_t len;
2443
2444        switch (st->st_mode & S_IFMT) {
2445        case S_IFREG:
2446                fd = open(path, O_RDONLY);
2447                if (fd < 0)
2448                        return error("open(\"%s\"): %s", path,
2449                                     strerror(errno));
2450                if (index_fd(sha1, fd, st, write_object, OBJ_BLOB, path) < 0)
2451                        return error("%s: failed to insert into database",
2452                                     path);
2453                break;
2454        case S_IFLNK:
2455                len = xsize_t(st->st_size);
2456                target = xmalloc(len + 1);
2457                if (readlink(path, target, len + 1) != st->st_size) {
2458                        char *errstr = strerror(errno);
2459                        free(target);
2460                        return error("readlink(\"%s\"): %s", path,
2461                                     errstr);
2462                }
2463                if (!write_object)
2464                        hash_sha1_file(target, len, blob_type, sha1);
2465                else if (write_sha1_file(target, len, blob_type, sha1))
2466                        return error("%s: failed to insert into database",
2467                                     path);
2468                free(target);
2469                break;
2470        case S_IFDIR:
2471                return resolve_gitlink_ref(path, "HEAD", sha1);
2472        default:
2473                return error("%s: unsupported file type", path);
2474        }
2475        return 0;
2476}
2477
2478int read_pack_header(int fd, struct pack_header *header)
2479{
2480        if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
2481                /* "eof before pack header was fully read" */
2482                return PH_ERROR_EOF;
2483
2484        if (header->hdr_signature != htonl(PACK_SIGNATURE))
2485                /* "protocol error (pack signature mismatch detected)" */
2486                return PH_ERROR_PACK_SIGNATURE;
2487        if (!pack_version_ok(header->hdr_version))
2488                /* "protocol error (pack version unsupported)" */
2489                return PH_ERROR_PROTOCOL;
2490        return 0;
2491}