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