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