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