5f34c69d3a80167a8337b9c6a5382e78f857428f
   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
  17#ifndef O_NOATIME
  18#if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
  19#define O_NOATIME 01000000
  20#else
  21#define O_NOATIME 0
  22#endif
  23#endif
  24
  25const unsigned char null_sha1[20];
  26
  27static unsigned int sha1_file_open_flag = O_NOATIME;
  28
  29static unsigned hexval(char c)
  30{
  31        if (c >= '0' && c <= '9')
  32                return c - '0';
  33        if (c >= 'a' && c <= 'f')
  34                return c - 'a' + 10;
  35        if (c >= 'A' && c <= 'F')
  36                return c - 'A' + 10;
  37        return ~0;
  38}
  39
  40int get_sha1_hex(const char *hex, unsigned char *sha1)
  41{
  42        int i;
  43        for (i = 0; i < 20; i++) {
  44                unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
  45                if (val & ~0xff)
  46                        return -1;
  47                *sha1++ = val;
  48                hex += 2;
  49        }
  50        return 0;
  51}
  52
  53int safe_create_leading_directories(char *path)
  54{
  55        char *pos = path;
  56        struct stat st;
  57
  58        if (*pos == '/')
  59                pos++;
  60
  61        while (pos) {
  62                pos = strchr(pos, '/');
  63                if (!pos)
  64                        break;
  65                *pos = 0;
  66                if (!stat(path, &st)) {
  67                        /* path exists */
  68                        if (!S_ISDIR(st.st_mode)) {
  69                                *pos = '/';
  70                                return -3;
  71                        }
  72                }
  73                else if (mkdir(path, 0777)) {
  74                        *pos = '/';
  75                        return -1;
  76                }
  77                else if (adjust_shared_perm(path)) {
  78                        *pos = '/';
  79                        return -2;
  80                }
  81                *pos++ = '/';
  82        }
  83        return 0;
  84}
  85
  86char * sha1_to_hex(const unsigned char *sha1)
  87{
  88        static int bufno;
  89        static char hexbuffer[4][50];
  90        static const char hex[] = "0123456789abcdef";
  91        char *buffer = hexbuffer[3 & ++bufno], *buf = buffer;
  92        int i;
  93
  94        for (i = 0; i < 20; i++) {
  95                unsigned int val = *sha1++;
  96                *buf++ = hex[val >> 4];
  97                *buf++ = hex[val & 0xf];
  98        }
  99        *buf = '\0';
 100
 101        return buffer;
 102}
 103
 104static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
 105{
 106        int i;
 107        for (i = 0; i < 20; i++) {
 108                static char hex[] = "0123456789abcdef";
 109                unsigned int val = sha1[i];
 110                char *pos = pathbuf + i*2 + (i > 0);
 111                *pos++ = hex[val >> 4];
 112                *pos = hex[val & 0xf];
 113        }
 114}
 115
 116/*
 117 * NOTE! This returns a statically allocated buffer, so you have to be
 118 * careful about using it. Do a "strdup()" if you need to save the
 119 * filename.
 120 *
 121 * Also note that this returns the location for creating.  Reading
 122 * SHA1 file can happen from any alternate directory listed in the
 123 * DB_ENVIRONMENT environment variable if it is not found in
 124 * the primary object database.
 125 */
 126char *sha1_file_name(const unsigned char *sha1)
 127{
 128        static char *name, *base;
 129
 130        if (!base) {
 131                const char *sha1_file_directory = get_object_directory();
 132                int len = strlen(sha1_file_directory);
 133                base = xmalloc(len + 60);
 134                memcpy(base, sha1_file_directory, len);
 135                memset(base+len, 0, 60);
 136                base[len] = '/';
 137                base[len+3] = '/';
 138                name = base + len + 1;
 139        }
 140        fill_sha1_path(name, sha1);
 141        return base;
 142}
 143
 144char *sha1_pack_name(const unsigned char *sha1)
 145{
 146        static const char hex[] = "0123456789abcdef";
 147        static char *name, *base, *buf;
 148        int i;
 149
 150        if (!base) {
 151                const char *sha1_file_directory = get_object_directory();
 152                int len = strlen(sha1_file_directory);
 153                base = xmalloc(len + 60);
 154                sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
 155                name = base + len + 11;
 156        }
 157
 158        buf = name;
 159
 160        for (i = 0; i < 20; i++) {
 161                unsigned int val = *sha1++;
 162                *buf++ = hex[val >> 4];
 163                *buf++ = hex[val & 0xf];
 164        }
 165        
 166        return base;
 167}
 168
 169char *sha1_pack_index_name(const unsigned char *sha1)
 170{
 171        static const char hex[] = "0123456789abcdef";
 172        static char *name, *base, *buf;
 173        int i;
 174
 175        if (!base) {
 176                const char *sha1_file_directory = get_object_directory();
 177                int len = strlen(sha1_file_directory);
 178                base = xmalloc(len + 60);
 179                sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
 180                name = base + len + 11;
 181        }
 182
 183        buf = name;
 184
 185        for (i = 0; i < 20; i++) {
 186                unsigned int val = *sha1++;
 187                *buf++ = hex[val >> 4];
 188                *buf++ = hex[val & 0xf];
 189        }
 190        
 191        return base;
 192}
 193
 194struct alternate_object_database *alt_odb_list;
 195static struct alternate_object_database **alt_odb_tail;
 196
 197static void read_info_alternates(const char * alternates, int depth);
 198
 199/*
 200 * Prepare alternate object database registry.
 201 *
 202 * The variable alt_odb_list points at the list of struct
 203 * alternate_object_database.  The elements on this list come from
 204 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
 205 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
 206 * whose contents is similar to that environment variable but can be
 207 * LF separated.  Its base points at a statically allocated buffer that
 208 * contains "/the/directory/corresponding/to/.git/objects/...", while
 209 * its name points just after the slash at the end of ".git/objects/"
 210 * in the example above, and has enough space to hold 40-byte hex
 211 * SHA1, an extra slash for the first level indirection, and the
 212 * terminating NUL.
 213 */
 214static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
 215{
 216        struct stat st;
 217        const char *objdir = get_object_directory();
 218        struct alternate_object_database *ent;
 219        struct alternate_object_database *alt;
 220        /* 43 = 40-byte + 2 '/' + terminating NUL */
 221        int pfxlen = len;
 222        int entlen = pfxlen + 43;
 223        int base_len = -1;
 224
 225        if (*entry != '/' && relative_base) {
 226                /* Relative alt-odb */
 227                if (base_len < 0)
 228                        base_len = strlen(relative_base) + 1;
 229                entlen += base_len;
 230                pfxlen += base_len;
 231        }
 232        ent = xmalloc(sizeof(*ent) + entlen);
 233
 234        if (*entry != '/' && relative_base) {
 235                memcpy(ent->base, relative_base, base_len - 1);
 236                ent->base[base_len - 1] = '/';
 237                memcpy(ent->base + base_len, entry, len);
 238        }
 239        else
 240                memcpy(ent->base, entry, pfxlen);
 241
 242        ent->name = ent->base + pfxlen + 1;
 243        ent->base[pfxlen + 3] = '/';
 244        ent->base[pfxlen] = ent->base[entlen-1] = 0;
 245
 246        /* Detect cases where alternate disappeared */
 247        if (stat(ent->base, &st) || !S_ISDIR(st.st_mode)) {
 248                error("object directory %s does not exist; "
 249                      "check .git/objects/info/alternates.",
 250                      ent->base);
 251                free(ent);
 252                return -1;
 253        }
 254
 255        /* Prevent the common mistake of listing the same
 256         * thing twice, or object directory itself.
 257         */
 258        for (alt = alt_odb_list; alt; alt = alt->next) {
 259                if (!memcmp(ent->base, alt->base, pfxlen)) {
 260                        free(ent);
 261                        return -1;
 262                }
 263        }
 264        if (!memcmp(ent->base, objdir, pfxlen)) {
 265                free(ent);
 266                return -1;
 267        }
 268
 269        /* add the alternate entry */
 270        *alt_odb_tail = ent;
 271        alt_odb_tail = &(ent->next);
 272        ent->next = NULL;
 273
 274        /* recursively add alternates */
 275        read_info_alternates(ent->base, depth + 1);
 276
 277        ent->base[pfxlen] = '/';
 278
 279        return 0;
 280}
 281
 282static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
 283                                 const char *relative_base, int depth)
 284{
 285        const char *cp, *last;
 286
 287        if (depth > 5) {
 288                error("%s: ignoring alternate object stores, nesting too deep.",
 289                                relative_base);
 290                return;
 291        }
 292
 293        last = alt;
 294        while (last < ep) {
 295                cp = last;
 296                if (cp < ep && *cp == '#') {
 297                        while (cp < ep && *cp != sep)
 298                                cp++;
 299                        last = cp + 1;
 300                        continue;
 301                }
 302                while (cp < ep && *cp != sep)
 303                        cp++;
 304                if (last != cp) {
 305                        if ((*last != '/') && depth) {
 306                                error("%s: ignoring relative alternate object store %s",
 307                                                relative_base, last);
 308                        } else {
 309                                link_alt_odb_entry(last, cp - last,
 310                                                relative_base, depth);
 311                        }
 312                }
 313                while (cp < ep && *cp == sep)
 314                        cp++;
 315                last = cp;
 316        }
 317}
 318
 319static void read_info_alternates(const char * relative_base, int depth)
 320{
 321        char *map;
 322        struct stat st;
 323        char path[PATH_MAX];
 324        int fd;
 325
 326        sprintf(path, "%s/info/alternates", relative_base);
 327        fd = open(path, O_RDONLY);
 328        if (fd < 0)
 329                return;
 330        if (fstat(fd, &st) || (st.st_size == 0)) {
 331                close(fd);
 332                return;
 333        }
 334        map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
 335        close(fd);
 336        if (map == MAP_FAILED)
 337                return;
 338
 339        link_alt_odb_entries(map, map + st.st_size, '\n', relative_base, depth);
 340
 341        munmap(map, st.st_size);
 342}
 343
 344void prepare_alt_odb(void)
 345{
 346        const char *alt;
 347
 348        alt = getenv(ALTERNATE_DB_ENVIRONMENT);
 349        if (!alt) alt = "";
 350
 351        if (alt_odb_tail)
 352                return;
 353        alt_odb_tail = &alt_odb_list;
 354        link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL, 0);
 355
 356        read_info_alternates(get_object_directory(), 0);
 357}
 358
 359static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
 360{
 361        char *name = sha1_file_name(sha1);
 362        struct alternate_object_database *alt;
 363
 364        if (!stat(name, st))
 365                return name;
 366        prepare_alt_odb();
 367        for (alt = alt_odb_list; alt; alt = alt->next) {
 368                name = alt->name;
 369                fill_sha1_path(name, sha1);
 370                if (!stat(alt->base, st))
 371                        return alt->base;
 372        }
 373        return NULL;
 374}
 375
 376#define PACK_MAX_SZ (1<<26)
 377static int pack_used_ctr;
 378static unsigned long pack_mapped;
 379struct packed_git *packed_git;
 380
 381static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
 382                                void **idx_map_)
 383{
 384        void *idx_map;
 385        unsigned int *index;
 386        unsigned long idx_size;
 387        int nr, i;
 388        int fd = open(path, O_RDONLY);
 389        struct stat st;
 390        if (fd < 0)
 391                return -1;
 392        if (fstat(fd, &st)) {
 393                close(fd);
 394                return -1;
 395        }
 396        idx_size = st.st_size;
 397        idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
 398        close(fd);
 399        if (idx_map == MAP_FAILED)
 400                return -1;
 401
 402        index = idx_map;
 403        *idx_map_ = idx_map;
 404        *idx_size_ = idx_size;
 405
 406        /* check index map */
 407        if (idx_size < 4*256 + 20 + 20)
 408                return error("index file too small");
 409        nr = 0;
 410        for (i = 0; i < 256; i++) {
 411                unsigned int n = ntohl(index[i]);
 412                if (n < nr)
 413                        return error("non-monotonic index");
 414                nr = n;
 415        }
 416
 417        /*
 418         * Total size:
 419         *  - 256 index entries 4 bytes each
 420         *  - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
 421         *  - 20-byte SHA1 of the packfile
 422         *  - 20-byte SHA1 file checksum
 423         */
 424        if (idx_size != 4*256 + nr * 24 + 20 + 20)
 425                return error("wrong index file size");
 426
 427        return 0;
 428}
 429
 430static int unuse_one_packed_git(void)
 431{
 432        struct packed_git *p, *lru = NULL;
 433
 434        for (p = packed_git; p; p = p->next) {
 435                if (p->pack_use_cnt || !p->pack_base)
 436                        continue;
 437                if (!lru || p->pack_last_used < lru->pack_last_used)
 438                        lru = p;
 439        }
 440        if (!lru)
 441                return 0;
 442        munmap(lru->pack_base, lru->pack_size);
 443        lru->pack_base = NULL;
 444        return 1;
 445}
 446
 447void unuse_packed_git(struct packed_git *p)
 448{
 449        p->pack_use_cnt--;
 450}
 451
 452int use_packed_git(struct packed_git *p)
 453{
 454        if (!p->pack_size) {
 455                struct stat st;
 456                /* We created the struct before we had the pack */
 457                stat(p->pack_name, &st);
 458                if (!S_ISREG(st.st_mode))
 459                        die("packfile %s not a regular file", p->pack_name);
 460                p->pack_size = st.st_size;
 461        }
 462        if (!p->pack_base) {
 463                int fd;
 464                struct stat st;
 465                void *map;
 466                struct pack_header *hdr;
 467
 468                pack_mapped += p->pack_size;
 469                while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
 470                        ; /* nothing */
 471                fd = open(p->pack_name, O_RDONLY);
 472                if (fd < 0)
 473                        die("packfile %s cannot be opened", p->pack_name);
 474                if (fstat(fd, &st)) {
 475                        close(fd);
 476                        die("packfile %s cannot be opened", p->pack_name);
 477                }
 478                if (st.st_size != p->pack_size)
 479                        die("packfile %s size mismatch.", p->pack_name);
 480                map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
 481                close(fd);
 482                if (map == MAP_FAILED)
 483                        die("packfile %s cannot be mapped.", p->pack_name);
 484                p->pack_base = map;
 485
 486                /* Check if we understand this pack file.  If we don't we're
 487                 * likely too old to handle it.
 488                 */
 489                hdr = map;
 490                if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
 491                        die("packfile %s isn't actually a pack.", p->pack_name);
 492                if (!pack_version_ok(hdr->hdr_version))
 493                        die("packfile %s is version %i and not supported"
 494                                " (try upgrading GIT to a newer version)",
 495                                p->pack_name, ntohl(hdr->hdr_version));
 496
 497                /* Check if the pack file matches with the index file.
 498                 * this is cheap.
 499                 */
 500                if (hashcmp((unsigned char *)(p->index_base) +
 501                            p->index_size - 40,
 502                            (unsigned char *)p->pack_base +
 503                            p->pack_size - 20)) {
 504                        die("packfile %s does not match index.", p->pack_name);
 505                }
 506        }
 507        p->pack_last_used = pack_used_ctr++;
 508        p->pack_use_cnt++;
 509        return 0;
 510}
 511
 512struct packed_git *add_packed_git(char *path, int path_len, int local)
 513{
 514        struct stat st;
 515        struct packed_git *p;
 516        unsigned long idx_size;
 517        void *idx_map;
 518        unsigned char sha1[20];
 519
 520        if (check_packed_git_idx(path, &idx_size, &idx_map))
 521                return NULL;
 522
 523        /* do we have a corresponding .pack file? */
 524        strcpy(path + path_len - 4, ".pack");
 525        if (stat(path, &st) || !S_ISREG(st.st_mode)) {
 526                munmap(idx_map, idx_size);
 527                return NULL;
 528        }
 529        /* ok, it looks sane as far as we can check without
 530         * actually mapping the pack file.
 531         */
 532        p = xmalloc(sizeof(*p) + path_len + 2);
 533        strcpy(p->pack_name, path);
 534        p->index_size = idx_size;
 535        p->pack_size = st.st_size;
 536        p->index_base = idx_map;
 537        p->next = NULL;
 538        p->pack_base = NULL;
 539        p->pack_last_used = 0;
 540        p->pack_use_cnt = 0;
 541        p->pack_local = local;
 542        if ((path_len > 44) && !get_sha1_hex(path + path_len - 44, sha1))
 543                memcpy(p->sha1, sha1, 20);
 544        return p;
 545}
 546
 547struct packed_git *parse_pack_index(unsigned char *sha1)
 548{
 549        char *path = sha1_pack_index_name(sha1);
 550        return parse_pack_index_file(sha1, path);
 551}
 552
 553struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
 554{
 555        struct packed_git *p;
 556        unsigned long idx_size;
 557        void *idx_map;
 558        char *path;
 559
 560        if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
 561                return NULL;
 562
 563        path = sha1_pack_name(sha1);
 564
 565        p = xmalloc(sizeof(*p) + strlen(path) + 2);
 566        strcpy(p->pack_name, path);
 567        p->index_size = idx_size;
 568        p->pack_size = 0;
 569        p->index_base = idx_map;
 570        p->next = NULL;
 571        p->pack_base = NULL;
 572        p->pack_last_used = 0;
 573        p->pack_use_cnt = 0;
 574        memcpy(p->sha1, sha1, 20);
 575        return p;
 576}
 577
 578void install_packed_git(struct packed_git *pack)
 579{
 580        pack->next = packed_git;
 581        packed_git = pack;
 582}
 583
 584static void prepare_packed_git_one(char *objdir, int local)
 585{
 586        char path[PATH_MAX];
 587        int len;
 588        DIR *dir;
 589        struct dirent *de;
 590
 591        sprintf(path, "%s/pack", objdir);
 592        len = strlen(path);
 593        dir = opendir(path);
 594        if (!dir) {
 595                if (errno != ENOENT)
 596                        error("unable to open object pack directory: %s: %s",
 597                              path, strerror(errno));
 598                return;
 599        }
 600        path[len++] = '/';
 601        while ((de = readdir(dir)) != NULL) {
 602                int namelen = strlen(de->d_name);
 603                struct packed_git *p;
 604
 605                if (!has_extension(de->d_name, ".idx"))
 606                        continue;
 607
 608                /* we have .idx.  Is it a file we can map? */
 609                strcpy(path + len, de->d_name);
 610                for (p = packed_git; p; p = p->next) {
 611                        if (!memcmp(path, p->pack_name, len + namelen - 4))
 612                                break;
 613                }
 614                if (p)
 615                        continue;
 616                p = add_packed_git(path, len + namelen, local);
 617                if (!p)
 618                        continue;
 619                p->next = packed_git;
 620                packed_git = p;
 621        }
 622        closedir(dir);
 623}
 624
 625static int prepare_packed_git_run_once = 0;
 626void prepare_packed_git(void)
 627{
 628        struct alternate_object_database *alt;
 629
 630        if (prepare_packed_git_run_once)
 631                return;
 632        prepare_packed_git_one(get_object_directory(), 1);
 633        prepare_alt_odb();
 634        for (alt = alt_odb_list; alt; alt = alt->next) {
 635                alt->name[-1] = 0;
 636                prepare_packed_git_one(alt->base, 0);
 637                alt->name[-1] = '/';
 638        }
 639        prepare_packed_git_run_once = 1;
 640}
 641
 642static void reprepare_packed_git(void)
 643{
 644        prepare_packed_git_run_once = 0;
 645        prepare_packed_git();
 646}
 647
 648int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
 649{
 650        char header[100];
 651        unsigned char real_sha1[20];
 652        SHA_CTX c;
 653
 654        SHA1_Init(&c);
 655        SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
 656        SHA1_Update(&c, map, size);
 657        SHA1_Final(real_sha1, &c);
 658        return hashcmp(sha1, real_sha1) ? -1 : 0;
 659}
 660
 661void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
 662{
 663        struct stat st;
 664        void *map;
 665        int fd;
 666        char *filename = find_sha1_file(sha1, &st);
 667
 668        if (!filename) {
 669                return NULL;
 670        }
 671
 672        fd = open(filename, O_RDONLY | sha1_file_open_flag);
 673        if (fd < 0) {
 674                /* See if it works without O_NOATIME */
 675                switch (sha1_file_open_flag) {
 676                default:
 677                        fd = open(filename, O_RDONLY);
 678                        if (fd >= 0)
 679                                break;
 680                /* Fallthrough */
 681                case 0:
 682                        return NULL;
 683                }
 684
 685                /* If it failed once, it will probably fail again.
 686                 * Stop using O_NOATIME
 687                 */
 688                sha1_file_open_flag = 0;
 689        }
 690        map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
 691        close(fd);
 692        if (map == MAP_FAILED)
 693                return NULL;
 694        *size = st.st_size;
 695        return map;
 696}
 697
 698int legacy_loose_object(unsigned char *map)
 699{
 700        unsigned int word;
 701
 702        /*
 703         * Is it a zlib-compressed buffer? If so, the first byte
 704         * must be 0x78 (15-bit window size, deflated), and the
 705         * first 16-bit word is evenly divisible by 31
 706         */
 707        word = (map[0] << 8) + map[1];
 708        if (map[0] == 0x78 && !(word % 31))
 709                return 1;
 710        else
 711                return 0;
 712}
 713
 714static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
 715{
 716        unsigned char c;
 717        unsigned int bits;
 718        unsigned long size;
 719        static const char *typename[8] = {
 720                NULL,   /* OBJ_EXT */
 721                "commit", "tree", "blob", "tag",
 722                NULL, NULL, NULL
 723        };
 724        const char *type;
 725
 726        /* Get the data stream */
 727        memset(stream, 0, sizeof(*stream));
 728        stream->next_in = map;
 729        stream->avail_in = mapsize;
 730        stream->next_out = buffer;
 731        stream->avail_out = bufsiz;
 732
 733        if (legacy_loose_object(map)) {
 734                inflateInit(stream);
 735                return inflate(stream, 0);
 736        }
 737
 738        c = *map++;
 739        mapsize--;
 740        type = typename[(c >> 4) & 7];
 741        if (!type)
 742                return -1;
 743
 744        bits = 4;
 745        size = c & 0xf;
 746        while ((c & 0x80)) {
 747                if (bits >= 8*sizeof(long))
 748                        return -1;
 749                c = *map++;
 750                size += (c & 0x7f) << bits;
 751                bits += 7;
 752                mapsize--;
 753        }
 754
 755        /* Set up the stream for the rest.. */
 756        stream->next_in = map;
 757        stream->avail_in = mapsize;
 758        inflateInit(stream);
 759
 760        /* And generate the fake traditional header */
 761        stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu", type, size);
 762        return 0;
 763}
 764
 765static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
 766{
 767        int bytes = strlen(buffer) + 1;
 768        unsigned char *buf = xmalloc(1+size);
 769        unsigned long n;
 770
 771        n = stream->total_out - bytes;
 772        if (n > size)
 773                n = size;
 774        memcpy(buf, (char *) buffer + bytes, n);
 775        bytes = n;
 776        if (bytes < size) {
 777                stream->next_out = buf + bytes;
 778                stream->avail_out = size - bytes;
 779                while (inflate(stream, Z_FINISH) == Z_OK)
 780                        /* nothing */;
 781        }
 782        buf[size] = 0;
 783        inflateEnd(stream);
 784        return buf;
 785}
 786
 787/*
 788 * We used to just use "sscanf()", but that's actually way
 789 * too permissive for what we want to check. So do an anal
 790 * object header parse by hand.
 791 */
 792static int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
 793{
 794        int i;
 795        unsigned long size;
 796
 797        /*
 798         * The type can be at most ten bytes (including the 
 799         * terminating '\0' that we add), and is followed by
 800         * a space. 
 801         */
 802        i = 10;
 803        for (;;) {
 804                char c = *hdr++;
 805                if (c == ' ')
 806                        break;
 807                if (!--i)
 808                        return -1;
 809                *type++ = c;
 810        }
 811        *type = 0;
 812
 813        /*
 814         * The length must follow immediately, and be in canonical
 815         * decimal format (ie "010" is not valid).
 816         */
 817        size = *hdr++ - '0';
 818        if (size > 9)
 819                return -1;
 820        if (size) {
 821                for (;;) {
 822                        unsigned long c = *hdr - '0';
 823                        if (c > 9)
 824                                break;
 825                        hdr++;
 826                        size = size * 10 + c;
 827                }
 828        }
 829        *sizep = size;
 830
 831        /*
 832         * The length must be followed by a zero byte
 833         */
 834        return *hdr ? -1 : 0;
 835}
 836
 837void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
 838{
 839        int ret;
 840        z_stream stream;
 841        char hdr[8192];
 842
 843        ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
 844        if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
 845                return NULL;
 846
 847        return unpack_sha1_rest(&stream, hdr, *size);
 848}
 849
 850/* forward declaration for a mutually recursive function */
 851static int packed_object_info(struct pack_entry *entry,
 852                              char *type, unsigned long *sizep);
 853
 854static int packed_delta_info(unsigned char *base_sha1,
 855                             unsigned long delta_size,
 856                             unsigned long left,
 857                             char *type,
 858                             unsigned long *sizep,
 859                             struct packed_git *p)
 860{
 861        struct pack_entry base_ent;
 862
 863        if (left < 20)
 864                die("truncated pack file");
 865
 866        /* The base entry _must_ be in the same pack */
 867        if (!find_pack_entry_one(base_sha1, &base_ent, p))
 868                die("failed to find delta-pack base object %s",
 869                    sha1_to_hex(base_sha1));
 870
 871        /* We choose to only get the type of the base object and
 872         * ignore potentially corrupt pack file that expects the delta
 873         * based on a base with a wrong size.  This saves tons of
 874         * inflate() calls.
 875         */
 876
 877        if (packed_object_info(&base_ent, type, NULL))
 878                die("cannot get info for delta-pack base");
 879
 880        if (sizep) {
 881                const unsigned char *data;
 882                unsigned char delta_head[64];
 883                unsigned long result_size;
 884                z_stream stream;
 885                int st;
 886
 887                memset(&stream, 0, sizeof(stream));
 888
 889                data = stream.next_in = base_sha1 + 20;
 890                stream.avail_in = left - 20;
 891                stream.next_out = delta_head;
 892                stream.avail_out = sizeof(delta_head);
 893
 894                inflateInit(&stream);
 895                st = inflate(&stream, Z_FINISH);
 896                inflateEnd(&stream);
 897                if ((st != Z_STREAM_END) &&
 898                    stream.total_out != sizeof(delta_head))
 899                        die("delta data unpack-initial failed");
 900
 901                /* Examine the initial part of the delta to figure out
 902                 * the result size.
 903                 */
 904                data = delta_head;
 905
 906                /* ignore base size */
 907                get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
 908
 909                /* Read the result size */
 910                result_size = get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
 911                *sizep = result_size;
 912        }
 913        return 0;
 914}
 915
 916static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
 917        enum object_type *type, unsigned long *sizep)
 918{
 919        unsigned shift;
 920        unsigned char *pack, c;
 921        unsigned long size;
 922
 923        if (offset >= p->pack_size)
 924                die("object offset outside of pack file");
 925
 926        pack =  (unsigned char *) p->pack_base + offset;
 927        c = *pack++;
 928        offset++;
 929        *type = (c >> 4) & 7;
 930        size = c & 15;
 931        shift = 4;
 932        while (c & 0x80) {
 933                if (offset >= p->pack_size)
 934                        die("object offset outside of pack file");
 935                c = *pack++;
 936                offset++;
 937                size += (c & 0x7f) << shift;
 938                shift += 7;
 939        }
 940        *sizep = size;
 941        return offset;
 942}
 943
 944int check_reuse_pack_delta(struct packed_git *p, unsigned long offset,
 945                           unsigned char *base, unsigned long *sizep,
 946                           enum object_type *kindp)
 947{
 948        unsigned long ptr;
 949        int status = -1;
 950
 951        use_packed_git(p);
 952        ptr = offset;
 953        ptr = unpack_object_header(p, ptr, kindp, sizep);
 954        if (*kindp != OBJ_DELTA)
 955                goto done;
 956        memcpy(base, (unsigned char *) p->pack_base + ptr, 20);
 957        status = 0;
 958 done:
 959        unuse_packed_git(p);
 960        return status;
 961}
 962
 963void packed_object_info_detail(struct pack_entry *e,
 964                               char *type,
 965                               unsigned long *size,
 966                               unsigned long *store_size,
 967                               unsigned int *delta_chain_length,
 968                               unsigned char *base_sha1)
 969{
 970        struct packed_git *p = e->p;
 971        unsigned long offset;
 972        unsigned char *pack;
 973        enum object_type kind;
 974
 975        offset = unpack_object_header(p, e->offset, &kind, size);
 976        pack = (unsigned char *) p->pack_base + offset;
 977        if (kind != OBJ_DELTA)
 978                *delta_chain_length = 0;
 979        else {
 980                unsigned int chain_length = 0;
 981                if (p->pack_size <= offset + 20)
 982                        die("pack file %s records an incomplete delta base",
 983                            p->pack_name);
 984                memcpy(base_sha1, pack, 20);
 985                do {
 986                        struct pack_entry base_ent;
 987                        unsigned long junk;
 988
 989                        find_pack_entry_one(pack, &base_ent, p);
 990                        offset = unpack_object_header(p, base_ent.offset,
 991                                                      &kind, &junk);
 992                        pack = (unsigned char *) p->pack_base + offset;
 993                        chain_length++;
 994                } while (kind == OBJ_DELTA);
 995                *delta_chain_length = chain_length;
 996        }
 997        switch (kind) {
 998        case OBJ_COMMIT:
 999                strcpy(type, commit_type);
1000                break;
1001        case OBJ_TREE:
1002                strcpy(type, tree_type);
1003                break;
1004        case OBJ_BLOB:
1005                strcpy(type, blob_type);
1006                break;
1007        case OBJ_TAG:
1008                strcpy(type, tag_type);
1009                break;
1010        default:
1011                die("corrupted pack file %s containing object of kind %d",
1012                    p->pack_name, kind);
1013        }
1014        *store_size = 0; /* notyet */
1015}
1016
1017static int packed_object_info(struct pack_entry *entry,
1018                              char *type, unsigned long *sizep)
1019{
1020        struct packed_git *p = entry->p;
1021        unsigned long offset, size, left;
1022        unsigned char *pack;
1023        enum object_type kind;
1024        int retval;
1025
1026        if (use_packed_git(p))
1027                die("cannot map packed file");
1028
1029        offset = unpack_object_header(p, entry->offset, &kind, &size);
1030        pack = (unsigned char *) p->pack_base + offset;
1031        left = p->pack_size - offset;
1032
1033        switch (kind) {
1034        case OBJ_DELTA:
1035                retval = packed_delta_info(pack, size, left, type, sizep, p);
1036                unuse_packed_git(p);
1037                return retval;
1038        case OBJ_COMMIT:
1039                strcpy(type, commit_type);
1040                break;
1041        case OBJ_TREE:
1042                strcpy(type, tree_type);
1043                break;
1044        case OBJ_BLOB:
1045                strcpy(type, blob_type);
1046                break;
1047        case OBJ_TAG:
1048                strcpy(type, tag_type);
1049                break;
1050        default:
1051                die("corrupted pack file %s containing object of kind %d",
1052                    p->pack_name, kind);
1053        }
1054        if (sizep)
1055                *sizep = size;
1056        unuse_packed_git(p);
1057        return 0;
1058}
1059
1060/* forward declaration for a mutually recursive function */
1061static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
1062
1063static void *unpack_delta_entry(unsigned char *base_sha1,
1064                                unsigned long delta_size,
1065                                unsigned long left,
1066                                char *type,
1067                                unsigned long *sizep,
1068                                struct packed_git *p)
1069{
1070        struct pack_entry base_ent;
1071        void *data, *delta_data, *result, *base;
1072        unsigned long data_size, result_size, base_size;
1073        z_stream stream;
1074        int st;
1075
1076        if (left < 20)
1077                die("truncated pack file");
1078
1079        /* The base entry _must_ be in the same pack */
1080        if (!find_pack_entry_one(base_sha1, &base_ent, p))
1081                die("failed to find delta-pack base object %s",
1082                    sha1_to_hex(base_sha1));
1083        base = unpack_entry_gently(&base_ent, type, &base_size);
1084        if (!base)
1085                die("failed to read delta-pack base object %s",
1086                    sha1_to_hex(base_sha1));
1087
1088        data = base_sha1 + 20;
1089        data_size = left - 20;
1090        delta_data = xmalloc(delta_size);
1091
1092        memset(&stream, 0, sizeof(stream));
1093
1094        stream.next_in = data;
1095        stream.avail_in = data_size;
1096        stream.next_out = delta_data;
1097        stream.avail_out = delta_size;
1098
1099        inflateInit(&stream);
1100        st = inflate(&stream, Z_FINISH);
1101        inflateEnd(&stream);
1102        if ((st != Z_STREAM_END) || stream.total_out != delta_size)
1103                die("delta data unpack failed");
1104
1105        result = patch_delta(base, base_size,
1106                             delta_data, delta_size,
1107                             &result_size);
1108        if (!result)
1109                die("failed to apply delta");
1110        free(delta_data);
1111        free(base);
1112        *sizep = result_size;
1113        return result;
1114}
1115
1116static void *unpack_non_delta_entry(unsigned char *data,
1117                                    unsigned long size,
1118                                    unsigned long left)
1119{
1120        int st;
1121        z_stream stream;
1122        unsigned char *buffer;
1123
1124        buffer = xmalloc(size + 1);
1125        buffer[size] = 0;
1126        memset(&stream, 0, sizeof(stream));
1127        stream.next_in = data;
1128        stream.avail_in = left;
1129        stream.next_out = buffer;
1130        stream.avail_out = size;
1131
1132        inflateInit(&stream);
1133        st = inflate(&stream, Z_FINISH);
1134        inflateEnd(&stream);
1135        if ((st != Z_STREAM_END) || stream.total_out != size) {
1136                free(buffer);
1137                return NULL;
1138        }
1139
1140        return buffer;
1141}
1142
1143static void *unpack_entry(struct pack_entry *entry,
1144                          char *type, unsigned long *sizep)
1145{
1146        struct packed_git *p = entry->p;
1147        void *retval;
1148
1149        if (use_packed_git(p))
1150                die("cannot map packed file");
1151        retval = unpack_entry_gently(entry, type, sizep);
1152        unuse_packed_git(p);
1153        if (!retval)
1154                die("corrupted pack file %s", p->pack_name);
1155        return retval;
1156}
1157
1158/* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
1159void *unpack_entry_gently(struct pack_entry *entry,
1160                          char *type, unsigned long *sizep)
1161{
1162        struct packed_git *p = entry->p;
1163        unsigned long offset, size, left;
1164        unsigned char *pack;
1165        enum object_type kind;
1166        void *retval;
1167
1168        offset = unpack_object_header(p, entry->offset, &kind, &size);
1169        pack = (unsigned char *) p->pack_base + offset;
1170        left = p->pack_size - offset;
1171        switch (kind) {
1172        case OBJ_DELTA:
1173                retval = unpack_delta_entry(pack, size, left, type, sizep, p);
1174                return retval;
1175        case OBJ_COMMIT:
1176                strcpy(type, commit_type);
1177                break;
1178        case OBJ_TREE:
1179                strcpy(type, tree_type);
1180                break;
1181        case OBJ_BLOB:
1182                strcpy(type, blob_type);
1183                break;
1184        case OBJ_TAG:
1185                strcpy(type, tag_type);
1186                break;
1187        default:
1188                return NULL;
1189        }
1190        *sizep = size;
1191        retval = unpack_non_delta_entry(pack, size, left);
1192        return retval;
1193}
1194
1195int num_packed_objects(const struct packed_git *p)
1196{
1197        /* See check_packed_git_idx() */
1198        return (p->index_size - 20 - 20 - 4*256) / 24;
1199}
1200
1201int nth_packed_object_sha1(const struct packed_git *p, int n,
1202                           unsigned char* sha1)
1203{
1204        void *index = p->index_base + 256;
1205        if (n < 0 || num_packed_objects(p) <= n)
1206                return -1;
1207        memcpy(sha1, (char *) index + (24 * n) + 4, 20);
1208        return 0;
1209}
1210
1211int find_pack_entry_one(const unsigned char *sha1,
1212                        struct pack_entry *e, struct packed_git *p)
1213{
1214        unsigned int *level1_ofs = p->index_base;
1215        int hi = ntohl(level1_ofs[*sha1]);
1216        int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1217        void *index = p->index_base + 256;
1218
1219        do {
1220                int mi = (lo + hi) / 2;
1221                int cmp = hashcmp((unsigned char *)index + (24 * mi) + 4, sha1);
1222                if (!cmp) {
1223                        e->offset = ntohl(*((unsigned int *) ((char *) index + (24 * mi))));
1224                        memcpy(e->sha1, sha1, 20);
1225                        e->p = p;
1226                        return 1;
1227                }
1228                if (cmp > 0)
1229                        hi = mi;
1230                else
1231                        lo = mi+1;
1232        } while (lo < hi);
1233        return 0;
1234}
1235
1236static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1237{
1238        struct packed_git *p;
1239        prepare_packed_git();
1240
1241        for (p = packed_git; p; p = p->next) {
1242                if (find_pack_entry_one(sha1, e, p))
1243                        return 1;
1244        }
1245        return 0;
1246}
1247
1248struct packed_git *find_sha1_pack(const unsigned char *sha1, 
1249                                  struct packed_git *packs)
1250{
1251        struct packed_git *p;
1252        struct pack_entry e;
1253
1254        for (p = packs; p; p = p->next) {
1255                if (find_pack_entry_one(sha1, &e, p))
1256                        return p;
1257        }
1258        return NULL;
1259        
1260}
1261
1262int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1263{
1264        int status;
1265        unsigned long mapsize, size;
1266        void *map;
1267        z_stream stream;
1268        char hdr[128];
1269
1270        map = map_sha1_file(sha1, &mapsize);
1271        if (!map) {
1272                struct pack_entry e;
1273
1274                if (find_pack_entry(sha1, &e))
1275                        return packed_object_info(&e, type, sizep);
1276                reprepare_packed_git();
1277                if (find_pack_entry(sha1, &e))
1278                        return packed_object_info(&e, type, sizep);
1279                return error("unable to find %s", sha1_to_hex(sha1));
1280        }
1281        if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1282                status = error("unable to unpack %s header",
1283                               sha1_to_hex(sha1));
1284        if (parse_sha1_header(hdr, type, &size) < 0)
1285                status = error("unable to parse %s header", sha1_to_hex(sha1));
1286        else {
1287                status = 0;
1288                if (sizep)
1289                        *sizep = size;
1290        }
1291        inflateEnd(&stream);
1292        munmap(map, mapsize);
1293        return status;
1294}
1295
1296static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1297{
1298        struct pack_entry e;
1299
1300        if (!find_pack_entry(sha1, &e)) {
1301                error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1302                return NULL;
1303        }
1304        return unpack_entry(&e, type, size);
1305}
1306
1307void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1308{
1309        unsigned long mapsize;
1310        void *map, *buf;
1311        struct pack_entry e;
1312
1313        if (find_pack_entry(sha1, &e))
1314                return read_packed_sha1(sha1, type, size);
1315        map = map_sha1_file(sha1, &mapsize);
1316        if (map) {
1317                buf = unpack_sha1_file(map, mapsize, type, size);
1318                munmap(map, mapsize);
1319                return buf;
1320        }
1321        reprepare_packed_git();
1322        if (find_pack_entry(sha1, &e))
1323                return read_packed_sha1(sha1, type, size);
1324        return NULL;
1325}
1326
1327void *read_object_with_reference(const unsigned char *sha1,
1328                                 const char *required_type,
1329                                 unsigned long *size,
1330                                 unsigned char *actual_sha1_return)
1331{
1332        char type[20];
1333        void *buffer;
1334        unsigned long isize;
1335        unsigned char actual_sha1[20];
1336
1337        memcpy(actual_sha1, sha1, 20);
1338        while (1) {
1339                int ref_length = -1;
1340                const char *ref_type = NULL;
1341
1342                buffer = read_sha1_file(actual_sha1, type, &isize);
1343                if (!buffer)
1344                        return NULL;
1345                if (!strcmp(type, required_type)) {
1346                        *size = isize;
1347                        if (actual_sha1_return)
1348                                memcpy(actual_sha1_return, actual_sha1, 20);
1349                        return buffer;
1350                }
1351                /* Handle references */
1352                else if (!strcmp(type, commit_type))
1353                        ref_type = "tree ";
1354                else if (!strcmp(type, tag_type))
1355                        ref_type = "object ";
1356                else {
1357                        free(buffer);
1358                        return NULL;
1359                }
1360                ref_length = strlen(ref_type);
1361
1362                if (memcmp(buffer, ref_type, ref_length) ||
1363                    get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
1364                        free(buffer);
1365                        return NULL;
1366                }
1367                free(buffer);
1368                /* Now we have the ID of the referred-to object in
1369                 * actual_sha1.  Check again. */
1370        }
1371}
1372
1373char *write_sha1_file_prepare(void *buf,
1374                              unsigned long len,
1375                              const char *type,
1376                              unsigned char *sha1,
1377                              unsigned char *hdr,
1378                              int *hdrlen)
1379{
1380        SHA_CTX c;
1381
1382        /* Generate the header */
1383        *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1384
1385        /* Sha1.. */
1386        SHA1_Init(&c);
1387        SHA1_Update(&c, hdr, *hdrlen);
1388        SHA1_Update(&c, buf, len);
1389        SHA1_Final(sha1, &c);
1390
1391        return sha1_file_name(sha1);
1392}
1393
1394/*
1395 * Link the tempfile to the final place, possibly creating the
1396 * last directory level as you do so.
1397 *
1398 * Returns the errno on failure, 0 on success.
1399 */
1400static int link_temp_to_file(const char *tmpfile, char *filename)
1401{
1402        int ret;
1403        char *dir;
1404
1405        if (!link(tmpfile, filename))
1406                return 0;
1407
1408        /*
1409         * Try to mkdir the last path component if that failed.
1410         *
1411         * Re-try the "link()" regardless of whether the mkdir
1412         * succeeds, since a race might mean that somebody
1413         * else succeeded.
1414         */
1415        ret = errno;
1416        dir = strrchr(filename, '/');
1417        if (dir) {
1418                *dir = 0;
1419                mkdir(filename, 0777);
1420                if (adjust_shared_perm(filename))
1421                        return -2;
1422                *dir = '/';
1423                if (!link(tmpfile, filename))
1424                        return 0;
1425                ret = errno;
1426        }
1427        return ret;
1428}
1429
1430/*
1431 * Move the just written object into its final resting place
1432 */
1433int move_temp_to_file(const char *tmpfile, char *filename)
1434{
1435        int ret = link_temp_to_file(tmpfile, filename);
1436
1437        /*
1438         * Coda hack - coda doesn't like cross-directory links,
1439         * so we fall back to a rename, which will mean that it
1440         * won't be able to check collisions, but that's not a
1441         * big deal.
1442         *
1443         * The same holds for FAT formatted media.
1444         *
1445         * When this succeeds, we just return 0. We have nothing
1446         * left to unlink.
1447         */
1448        if (ret && ret != EEXIST) {
1449                if (!rename(tmpfile, filename))
1450                        return 0;
1451                ret = errno;
1452        }
1453        unlink(tmpfile);
1454        if (ret) {
1455                if (ret != EEXIST) {
1456                        fprintf(stderr, "unable to write sha1 filename %s: %s\n", filename, strerror(ret));
1457                        return -1;
1458                }
1459                /* FIXME!!! Collision check here ? */
1460        }
1461
1462        return 0;
1463}
1464
1465static int write_buffer(int fd, const void *buf, size_t len)
1466{
1467        while (len) {
1468                ssize_t size;
1469
1470                size = write(fd, buf, len);
1471                if (!size)
1472                        return error("file write: disk full");
1473                if (size < 0) {
1474                        if (errno == EINTR || errno == EAGAIN)
1475                                continue;
1476                        return error("file write error (%s)", strerror(errno));
1477                }
1478                len -= size;
1479                buf = (char *) buf + size;
1480        }
1481        return 0;
1482}
1483
1484static int write_binary_header(unsigned char *hdr, enum object_type type, unsigned long len)
1485{
1486        int hdr_len;
1487        unsigned char c;
1488
1489        c = (type << 4) | (len & 15);
1490        len >>= 4;
1491        hdr_len = 1;
1492        while (len) {
1493                *hdr++ = c | 0x80;
1494                hdr_len++;
1495                c = (len & 0x7f);
1496                len >>= 7;
1497        }
1498        *hdr = c;
1499        return hdr_len;
1500}
1501
1502static void setup_object_header(z_stream *stream, const char *type, unsigned long len)
1503{
1504        int obj_type, hdr;
1505
1506        if (use_legacy_headers) {
1507                while (deflate(stream, 0) == Z_OK)
1508                        /* nothing */;
1509                return;
1510        }
1511        if (!strcmp(type, blob_type))
1512                obj_type = OBJ_BLOB;
1513        else if (!strcmp(type, tree_type))
1514                obj_type = OBJ_TREE;
1515        else if (!strcmp(type, commit_type))
1516                obj_type = OBJ_COMMIT;
1517        else if (!strcmp(type, tag_type))
1518                obj_type = OBJ_TAG;
1519        else
1520                die("trying to generate bogus object of type '%s'", type);
1521        hdr = write_binary_header(stream->next_out, obj_type, len);
1522        stream->total_out = hdr;
1523        stream->next_out += hdr;
1524        stream->avail_out -= hdr;
1525}
1526
1527int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1528{
1529        int size;
1530        unsigned char *compressed;
1531        z_stream stream;
1532        unsigned char sha1[20];
1533        char *filename;
1534        static char tmpfile[PATH_MAX];
1535        unsigned char hdr[50];
1536        int fd, hdrlen;
1537
1538        /* Normally if we have it in the pack then we do not bother writing
1539         * it out into .git/objects/??/?{38} file.
1540         */
1541        filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1542        if (returnsha1)
1543                memcpy(returnsha1, sha1, 20);
1544        if (has_sha1_file(sha1))
1545                return 0;
1546        fd = open(filename, O_RDONLY);
1547        if (fd >= 0) {
1548                /*
1549                 * FIXME!!! We might do collision checking here, but we'd
1550                 * need to uncompress the old file and check it. Later.
1551                 */
1552                close(fd);
1553                return 0;
1554        }
1555
1556        if (errno != ENOENT) {
1557                fprintf(stderr, "sha1 file %s: %s\n", filename, strerror(errno));
1558                return -1;
1559        }
1560
1561        snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1562
1563        fd = mkstemp(tmpfile);
1564        if (fd < 0) {
1565                fprintf(stderr, "unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
1566                return -1;
1567        }
1568
1569        /* Set it up */
1570        memset(&stream, 0, sizeof(stream));
1571        deflateInit(&stream, zlib_compression_level);
1572        size = 8 + deflateBound(&stream, len+hdrlen);
1573        compressed = xmalloc(size);
1574
1575        /* Compress it */
1576        stream.next_out = compressed;
1577        stream.avail_out = size;
1578
1579        /* First header.. */
1580        stream.next_in = hdr;
1581        stream.avail_in = hdrlen;
1582        setup_object_header(&stream, type, len);
1583
1584        /* Then the data itself.. */
1585        stream.next_in = buf;
1586        stream.avail_in = len;
1587        while (deflate(&stream, Z_FINISH) == Z_OK)
1588                /* nothing */;
1589        deflateEnd(&stream);
1590        size = stream.total_out;
1591
1592        if (write_buffer(fd, compressed, size) < 0)
1593                die("unable to write sha1 file");
1594        fchmod(fd, 0444);
1595        close(fd);
1596        free(compressed);
1597
1598        return move_temp_to_file(tmpfile, filename);
1599}
1600
1601/*
1602 * We need to unpack and recompress the object for writing
1603 * it out to a different file.
1604 */
1605static void *repack_object(const unsigned char *sha1, unsigned long *objsize)
1606{
1607        size_t size;
1608        z_stream stream;
1609        unsigned char *unpacked;
1610        unsigned long len;
1611        char type[20];
1612        char hdr[50];
1613        int hdrlen;
1614        void *buf;
1615
1616        /* need to unpack and recompress it by itself */
1617        unpacked = read_packed_sha1(sha1, type, &len);
1618
1619        hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1620
1621        /* Set it up */
1622        memset(&stream, 0, sizeof(stream));
1623        deflateInit(&stream, zlib_compression_level);
1624        size = deflateBound(&stream, len + hdrlen);
1625        buf = xmalloc(size);
1626
1627        /* Compress it */
1628        stream.next_out = buf;
1629        stream.avail_out = size;
1630
1631        /* First header.. */
1632        stream.next_in = (void *)hdr;
1633        stream.avail_in = hdrlen;
1634        while (deflate(&stream, 0) == Z_OK)
1635                /* nothing */;
1636
1637        /* Then the data itself.. */
1638        stream.next_in = unpacked;
1639        stream.avail_in = len;
1640        while (deflate(&stream, Z_FINISH) == Z_OK)
1641                /* nothing */;
1642        deflateEnd(&stream);
1643        free(unpacked);
1644
1645        *objsize = stream.total_out;
1646        return buf;
1647}
1648
1649int write_sha1_to_fd(int fd, const unsigned char *sha1)
1650{
1651        int retval;
1652        unsigned long objsize;
1653        void *buf = map_sha1_file(sha1, &objsize);
1654
1655        if (buf) {
1656                retval = write_buffer(fd, buf, objsize);
1657                munmap(buf, objsize);
1658                return retval;
1659        }
1660
1661        buf = repack_object(sha1, &objsize);
1662        retval = write_buffer(fd, buf, objsize);
1663        free(buf);
1664        return retval;
1665}
1666
1667int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1668                       size_t bufsize, size_t *bufposn)
1669{
1670        char tmpfile[PATH_MAX];
1671        int local;
1672        z_stream stream;
1673        unsigned char real_sha1[20];
1674        unsigned char discard[4096];
1675        int ret;
1676        SHA_CTX c;
1677
1678        snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1679
1680        local = mkstemp(tmpfile);
1681        if (local < 0)
1682                return error("Couldn't open %s for %s",
1683                             tmpfile, sha1_to_hex(sha1));
1684
1685        memset(&stream, 0, sizeof(stream));
1686
1687        inflateInit(&stream);
1688
1689        SHA1_Init(&c);
1690
1691        do {
1692                ssize_t size;
1693                if (*bufposn) {
1694                        stream.avail_in = *bufposn;
1695                        stream.next_in = (unsigned char *) buffer;
1696                        do {
1697                                stream.next_out = discard;
1698                                stream.avail_out = sizeof(discard);
1699                                ret = inflate(&stream, Z_SYNC_FLUSH);
1700                                SHA1_Update(&c, discard, sizeof(discard) -
1701                                            stream.avail_out);
1702                        } while (stream.avail_in && ret == Z_OK);
1703                        if (write_buffer(local, buffer, *bufposn - stream.avail_in) < 0)
1704                                die("unable to write sha1 file");
1705                        memmove(buffer, buffer + *bufposn - stream.avail_in,
1706                                stream.avail_in);
1707                        *bufposn = stream.avail_in;
1708                        if (ret != Z_OK)
1709                                break;
1710                }
1711                size = read(fd, buffer + *bufposn, bufsize - *bufposn);
1712                if (size <= 0) {
1713                        close(local);
1714                        unlink(tmpfile);
1715                        if (!size)
1716                                return error("Connection closed?");
1717                        perror("Reading from connection");
1718                        return -1;
1719                }
1720                *bufposn += size;
1721        } while (1);
1722        inflateEnd(&stream);
1723
1724        close(local);
1725        SHA1_Final(real_sha1, &c);
1726        if (ret != Z_STREAM_END) {
1727                unlink(tmpfile);
1728                return error("File %s corrupted", sha1_to_hex(sha1));
1729        }
1730        if (hashcmp(sha1, real_sha1)) {
1731                unlink(tmpfile);
1732                return error("File %s has bad hash", sha1_to_hex(sha1));
1733        }
1734
1735        return move_temp_to_file(tmpfile, sha1_file_name(sha1));
1736}
1737
1738int has_pack_index(const unsigned char *sha1)
1739{
1740        struct stat st;
1741        if (stat(sha1_pack_index_name(sha1), &st))
1742                return 0;
1743        return 1;
1744}
1745
1746int has_pack_file(const unsigned char *sha1)
1747{
1748        struct stat st;
1749        if (stat(sha1_pack_name(sha1), &st))
1750                return 0;
1751        return 1;
1752}
1753
1754int has_sha1_pack(const unsigned char *sha1)
1755{
1756        struct pack_entry e;
1757        return find_pack_entry(sha1, &e);
1758}
1759
1760int has_sha1_file(const unsigned char *sha1)
1761{
1762        struct stat st;
1763        struct pack_entry e;
1764
1765        if (find_pack_entry(sha1, &e))
1766                return 1;
1767        return find_sha1_file(sha1, &st) ? 1 : 0;
1768}
1769
1770/*
1771 * reads from fd as long as possible into a supplied buffer of size bytes.
1772 * If necessary the buffer's size is increased using realloc()
1773 *
1774 * returns 0 if anything went fine and -1 otherwise
1775 *
1776 * NOTE: both buf and size may change, but even when -1 is returned
1777 * you still have to free() it yourself.
1778 */
1779int read_pipe(int fd, char** return_buf, unsigned long* return_size)
1780{
1781        char* buf = *return_buf;
1782        unsigned long size = *return_size;
1783        int iret;
1784        unsigned long off = 0;
1785
1786        do {
1787                iret = xread(fd, buf + off, size - off);
1788                if (iret > 0) {
1789                        off += iret;
1790                        if (off == size) {
1791                                size *= 2;
1792                                buf = realloc(buf, size);
1793                        }
1794                }
1795        } while (iret > 0);
1796
1797        *return_buf = buf;
1798        *return_size = off;
1799
1800        if (iret < 0)
1801                return -1;
1802        return 0;
1803}
1804
1805int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
1806{
1807        unsigned long size = 4096;
1808        char *buf = malloc(size);
1809        int ret;
1810        unsigned char hdr[50];
1811        int hdrlen;
1812
1813        if (read_pipe(fd, &buf, &size)) {
1814                free(buf);
1815                return -1;
1816        }
1817
1818        if (!type)
1819                type = blob_type;
1820        if (write_object)
1821                ret = write_sha1_file(buf, size, type, sha1);
1822        else {
1823                write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1824                ret = 0;
1825        }
1826        free(buf);
1827        return ret;
1828}
1829
1830int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1831{
1832        unsigned long size = st->st_size;
1833        void *buf;
1834        int ret;
1835        unsigned char hdr[50];
1836        int hdrlen;
1837
1838        buf = "";
1839        if (size)
1840                buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1841        close(fd);
1842        if (buf == MAP_FAILED)
1843                return -1;
1844
1845        if (!type)
1846                type = blob_type;
1847        if (write_object)
1848                ret = write_sha1_file(buf, size, type, sha1);
1849        else {
1850                write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1851                ret = 0;
1852        }
1853        if (size)
1854                munmap(buf, size);
1855        return ret;
1856}
1857
1858int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1859{
1860        int fd;
1861        char *target;
1862
1863        switch (st->st_mode & S_IFMT) {
1864        case S_IFREG:
1865                fd = open(path, O_RDONLY);
1866                if (fd < 0)
1867                        return error("open(\"%s\"): %s", path,
1868                                     strerror(errno));
1869                if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1870                        return error("%s: failed to insert into database",
1871                                     path);
1872                break;
1873        case S_IFLNK:
1874                target = xmalloc(st->st_size+1);
1875                if (readlink(path, target, st->st_size+1) != st->st_size) {
1876                        char *errstr = strerror(errno);
1877                        free(target);
1878                        return error("readlink(\"%s\"): %s", path,
1879                                     errstr);
1880                }
1881                if (!write_object) {
1882                        unsigned char hdr[50];
1883                        int hdrlen;
1884                        write_sha1_file_prepare(target, st->st_size, blob_type,
1885                                                sha1, hdr, &hdrlen);
1886                } else if (write_sha1_file(target, st->st_size, blob_type, sha1))
1887                        return error("%s: failed to insert into database",
1888                                     path);
1889                free(target);
1890                break;
1891        default:
1892                return error("%s: unsupported file type", path);
1893        }
1894        return 0;
1895}