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