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