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