sha1_file.con commit [PATCH] Bugfix: initialize pack_base to NULL. (d85a4fe)
   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 <sys/types.h>
  10#include <dirent.h>
  11#include "cache.h"
  12#include "delta.h"
  13#include "pack.h"
  14
  15#ifndef O_NOATIME
  16#if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
  17#define O_NOATIME 01000000
  18#else
  19#define O_NOATIME 0
  20#endif
  21#endif
  22
  23static unsigned int sha1_file_open_flag = O_NOATIME;
  24
  25static unsigned hexval(char c)
  26{
  27        if (c >= '0' && c <= '9')
  28                return c - '0';
  29        if (c >= 'a' && c <= 'f')
  30                return c - 'a' + 10;
  31        if (c >= 'A' && c <= 'F')
  32                return c - 'A' + 10;
  33        return ~0;
  34}
  35
  36int get_sha1_hex(const char *hex, unsigned char *sha1)
  37{
  38        int i;
  39        for (i = 0; i < 20; i++) {
  40                unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
  41                if (val & ~0xff)
  42                        return -1;
  43                *sha1++ = val;
  44                hex += 2;
  45        }
  46        return 0;
  47}
  48
  49static int get_sha1_file(const char *path, unsigned char *result)
  50{
  51        char buffer[60];
  52        int fd = open(path, O_RDONLY);
  53        int len;
  54
  55        if (fd < 0)
  56                return -1;
  57        len = read(fd, buffer, sizeof(buffer));
  58        close(fd);
  59        if (len < 40)
  60                return -1;
  61        return get_sha1_hex(buffer, result);
  62}
  63
  64static char *git_dir, *git_object_dir, *git_index_file, *git_refs_dir;
  65static void setup_git_env(void)
  66{
  67        git_dir = gitenv(GIT_DIR_ENVIRONMENT);
  68        if (!git_dir)
  69                git_dir = DEFAULT_GIT_DIR_ENVIRONMENT;
  70        git_object_dir = gitenv(DB_ENVIRONMENT);
  71        if (!git_object_dir) {
  72                git_object_dir = xmalloc(strlen(git_dir) + 9);
  73                sprintf(git_object_dir, "%s/objects", git_dir);
  74        }
  75        git_refs_dir = xmalloc(strlen(git_dir) + 6);
  76        sprintf(git_refs_dir, "%s/refs", git_dir);
  77        git_index_file = gitenv(INDEX_ENVIRONMENT);
  78        if (!git_index_file) {
  79                git_index_file = xmalloc(strlen(git_dir) + 7);
  80                sprintf(git_index_file, "%s/index", git_dir);
  81        }
  82}
  83
  84char *get_object_directory(void)
  85{
  86        if (!git_object_dir)
  87                setup_git_env();
  88        return git_object_dir;
  89}
  90
  91char *get_refs_directory(void)
  92{
  93        if (!git_refs_dir)
  94                setup_git_env();
  95        return git_refs_dir;
  96}
  97
  98char *get_index_file(void)
  99{
 100        if (!git_index_file)
 101                setup_git_env();
 102        return git_index_file;
 103}
 104
 105int get_sha1(const char *str, unsigned char *sha1)
 106{
 107        static char pathname[PATH_MAX];
 108        static const char *prefix[] = {
 109                "",
 110                "refs",
 111                "refs/tags",
 112                "refs/heads",
 113                "refs/snap",
 114                NULL
 115        };
 116        const char **p;
 117
 118        if (!get_sha1_hex(str, sha1))
 119                return 0;
 120
 121        if (!git_dir)
 122                setup_git_env();
 123        for (p = prefix; *p; p++) {
 124                snprintf(pathname, sizeof(pathname), "%s/%s/%s",
 125                         git_dir, *p, str);
 126                if (!get_sha1_file(pathname, sha1))
 127                        return 0;
 128        }
 129
 130        return -1;
 131}
 132
 133char * sha1_to_hex(const unsigned char *sha1)
 134{
 135        static char buffer[50];
 136        static const char hex[] = "0123456789abcdef";
 137        char *buf = buffer;
 138        int i;
 139
 140        for (i = 0; i < 20; i++) {
 141                unsigned int val = *sha1++;
 142                *buf++ = hex[val >> 4];
 143                *buf++ = hex[val & 0xf];
 144        }
 145        return buffer;
 146}
 147
 148static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
 149{
 150        int i;
 151        for (i = 0; i < 20; i++) {
 152                static char hex[] = "0123456789abcdef";
 153                unsigned int val = sha1[i];
 154                char *pos = pathbuf + i*2 + (i > 0);
 155                *pos++ = hex[val >> 4];
 156                *pos = hex[val & 0xf];
 157        }
 158}
 159
 160/*
 161 * NOTE! This returns a statically allocated buffer, so you have to be
 162 * careful about using it. Do a "strdup()" if you need to save the
 163 * filename.
 164 *
 165 * Also note that this returns the location for creating.  Reading
 166 * SHA1 file can happen from any alternate directory listed in the
 167 * DB_ENVIRONMENT environment variable if it is not found in
 168 * the primary object database.
 169 */
 170char *sha1_file_name(const unsigned char *sha1)
 171{
 172        static char *name, *base;
 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                memcpy(base, sha1_file_directory, len);
 179                memset(base+len, 0, 60);
 180                base[len] = '/';
 181                base[len+3] = '/';
 182                name = base + len + 1;
 183        }
 184        fill_sha1_path(name, sha1);
 185        return base;
 186}
 187
 188static struct alternate_object_database {
 189        char *base;
 190        char *name;
 191} *alt_odb;
 192
 193/*
 194 * Prepare alternate object database registry.
 195 * alt_odb points at an array of struct alternate_object_database.
 196 * This array is terminated with an element that has both its base
 197 * and name set to NULL.  alt_odb[n] comes from n'th non-empty
 198 * element from colon separated ALTERNATE_DB_ENVIRONMENT environment
 199 * variable, and its base points at a statically allocated buffer
 200 * that contains "/the/directory/corresponding/to/.git/objects/...",
 201 * while its name points just after the slash at the end of
 202 * ".git/objects/" in the example above, and has enough space to hold
 203 * 40-byte hex SHA1, an extra slash for the first level indirection,
 204 * and the terminating NUL.
 205 * This function allocates the alt_odb array and all the strings
 206 * pointed by base fields of the array elements with one xmalloc();
 207 * the string pool immediately follows the array.
 208 */
 209static void prepare_alt_odb(void)
 210{
 211        int pass, totlen, i;
 212        const char *cp, *last;
 213        char *op = NULL;
 214        const char *alt = gitenv(ALTERNATE_DB_ENVIRONMENT) ? : "";
 215
 216        /* The first pass counts how large an area to allocate to
 217         * hold the entire alt_odb structure, including array of
 218         * structs and path buffers for them.  The second pass fills
 219         * the structure and prepares the path buffers for use by
 220         * fill_sha1_path().
 221         */
 222        for (totlen = pass = 0; pass < 2; pass++) {
 223                last = alt;
 224                i = 0;
 225                do {
 226                        cp = strchr(last, ':') ? : last + strlen(last);
 227                        if (last != cp) {
 228                                /* 43 = 40-byte + 2 '/' + terminating NUL */
 229                                int pfxlen = cp - last;
 230                                int entlen = pfxlen + 43;
 231                                if (pass == 0)
 232                                        totlen += entlen;
 233                                else {
 234                                        alt_odb[i].base = op;
 235                                        alt_odb[i].name = op + pfxlen + 1;
 236                                        memcpy(op, last, pfxlen);
 237                                        op[pfxlen] = op[pfxlen + 3] = '/';
 238                                        op[entlen-1] = 0;
 239                                        op += entlen;
 240                                }
 241                                i++;
 242                        }
 243                        while (*cp && *cp == ':')
 244                                cp++;
 245                        last = cp;
 246                } while (*cp);
 247                if (pass)
 248                        break;
 249                alt_odb = xmalloc(sizeof(*alt_odb) * (i + 1) + totlen);
 250                alt_odb[i].base = alt_odb[i].name = NULL;
 251                op = (char*)(&alt_odb[i+1]);
 252        }
 253}
 254
 255static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
 256{
 257        int i;
 258        char *name = sha1_file_name(sha1);
 259
 260        if (!stat(name, st))
 261                return name;
 262        if (!alt_odb)
 263                prepare_alt_odb();
 264        for (i = 0; (name = alt_odb[i].name) != NULL; i++) {
 265                fill_sha1_path(name, sha1);
 266                if (!stat(alt_odb[i].base, st))
 267                        return alt_odb[i].base;
 268        }
 269        return NULL;
 270}
 271
 272#define PACK_MAX_SZ (1<<26)
 273static int pack_used_ctr;
 274static unsigned long pack_mapped;
 275static struct packed_git {
 276        struct packed_git *next;
 277        unsigned long index_size;
 278        unsigned long pack_size;
 279        unsigned int *index_base;
 280        void *pack_base;
 281        unsigned int pack_last_used;
 282        char pack_name[0]; /* something like ".git/objects/pack/xxxxx.pack" */
 283} *packed_git;
 284
 285struct pack_entry {
 286        unsigned int offset;
 287        unsigned char sha1[20];
 288        struct packed_git *p;
 289};
 290
 291static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
 292                                void **idx_map_)
 293{
 294        void *idx_map;
 295        unsigned int *index;
 296        unsigned long idx_size;
 297        int nr, i;
 298        int fd = open(path, O_RDONLY);
 299        struct stat st;
 300        if (fd < 0)
 301                return -1;
 302        if (fstat(fd, &st)) {
 303                close(fd);
 304                return -1;
 305        }
 306        idx_size = st.st_size;
 307        idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
 308        close(fd);
 309        if (idx_map == MAP_FAILED)
 310                return -1;
 311
 312        index = idx_map;
 313
 314        /* check index map */
 315        if (idx_size < 4*256 + 20)
 316                return error("index file too small");
 317        nr = 0;
 318        for (i = 0; i < 256; i++) {
 319                unsigned int n = ntohl(index[i]);
 320                if (n < nr)
 321                        return error("non-monotonic index");
 322                nr = n;
 323        }
 324
 325        /*
 326         * Total size:
 327         *  - 256 index entries 4 bytes each
 328         *  - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
 329         *  - 20-byte SHA1 of the packfile
 330         *  - 20-byte SHA1 file checksum
 331         */
 332        if (idx_size != 4*256 + nr * 24 + 20 + 20)
 333                return error("wrong index file size");
 334
 335        *idx_map_ = idx_map;
 336        *idx_size_ = idx_size;
 337        return 0;
 338}
 339
 340static void unuse_one_packed_git(void)
 341{
 342        /* NOTYET */
 343}
 344
 345static int use_packed_git(struct packed_git *p)
 346{
 347        if (!p->pack_base) {
 348                int fd;
 349                struct stat st;
 350                void *map;
 351
 352                pack_mapped += p->pack_size;
 353                while (PACK_MAX_SZ < pack_mapped)
 354                        unuse_one_packed_git();
 355                fd = open(p->pack_name, O_RDONLY);
 356                if (fd < 0)
 357                        return -1;
 358                if (fstat(fd, &st)) {
 359                        close(fd);
 360                        return -1;
 361                }
 362                if (st.st_size != p->pack_size)
 363                        return -1;
 364                map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
 365                close(fd);
 366                if (map == MAP_FAILED)
 367                        return -1;
 368                p->pack_base = map;
 369        }
 370        p->pack_last_used = pack_used_ctr++;
 371        return 0;
 372}
 373
 374static struct packed_git *add_packed_git(char *path, int path_len)
 375{
 376        struct stat st;
 377        struct packed_git *p;
 378        unsigned long idx_size;
 379        void *idx_map;
 380
 381        if (check_packed_git_idx(path, &idx_size, &idx_map))
 382                return NULL;
 383
 384        /* do we have a corresponding .pack file? */
 385        strcpy(path + path_len - 4, ".pack");
 386        if (stat(path, &st) || !S_ISREG(st.st_mode)) {
 387                munmap(idx_map, idx_size);
 388                return NULL;
 389        }
 390        /* ok, it looks sane as far as we can check without
 391         * actually mapping the pack file.
 392         */
 393        p = xmalloc(sizeof(*p) + path_len + 2);
 394        strcpy(p->pack_name, path);
 395        p->index_size = idx_size;
 396        p->pack_size = st.st_size;
 397        p->index_base = idx_map;
 398        p->next = NULL;
 399        p->pack_base = NULL;
 400        p->pack_last_used = 0;
 401        return p;
 402}
 403
 404static void prepare_packed_git_one(char *objdir)
 405{
 406        char path[PATH_MAX];
 407        int len;
 408        DIR *dir;
 409        struct dirent *de;
 410
 411        sprintf(path, "%s/pack", objdir);
 412        len = strlen(path);
 413        dir = opendir(path);
 414        if (!dir)
 415                return;
 416        path[len++] = '/';
 417        while ((de = readdir(dir)) != NULL) {
 418                int namelen = strlen(de->d_name);
 419                struct packed_git *p;
 420
 421                if (strcmp(de->d_name + namelen - 4, ".idx"))
 422                        continue;
 423
 424                /* we have .idx.  Is it a file we can map? */
 425                strcpy(path + len, de->d_name);
 426                p = add_packed_git(path, len + namelen);
 427                if (!p)
 428                        continue;
 429                p->next = packed_git;
 430                packed_git = p;
 431        }
 432}
 433
 434static void prepare_packed_git(void)
 435{
 436        int i;
 437        static int run_once = 0;
 438
 439        if (run_once++)
 440                return;
 441
 442        prepare_packed_git_one(get_object_directory());
 443        if (!alt_odb)
 444                prepare_alt_odb();
 445        for (i = 0; alt_odb[i].base != NULL; i++) {
 446                alt_odb[i].name[0] = 0;
 447                prepare_packed_git_one(alt_odb[i].base);
 448        }
 449}
 450
 451int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
 452{
 453        char header[100];
 454        unsigned char real_sha1[20];
 455        SHA_CTX c;
 456
 457        SHA1_Init(&c);
 458        SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
 459        SHA1_Update(&c, map, size);
 460        SHA1_Final(real_sha1, &c);
 461        return memcmp(sha1, real_sha1, 20) ? -1 : 0;
 462}
 463
 464static void *map_sha1_file_internal(const unsigned char *sha1,
 465                                    unsigned long *size,
 466                                    int say_error)
 467{
 468        struct stat st;
 469        void *map;
 470        int fd;
 471        char *filename = find_sha1_file(sha1, &st);
 472
 473        if (!filename) {
 474                if (say_error)
 475                        error("cannot map sha1 file %s", sha1_to_hex(sha1));
 476                return NULL;
 477        }
 478
 479        fd = open(filename, O_RDONLY | sha1_file_open_flag);
 480        if (fd < 0) {
 481                /* See if it works without O_NOATIME */
 482                switch (sha1_file_open_flag) {
 483                default:
 484                        fd = open(filename, O_RDONLY);
 485                        if (fd >= 0)
 486                                break;
 487                /* Fallthrough */
 488                case 0:
 489                        if (say_error)
 490                                perror(filename);
 491                        return NULL;
 492                }
 493
 494                /* If it failed once, it will probably fail again.
 495                 * Stop using O_NOATIME
 496                 */
 497                sha1_file_open_flag = 0;
 498        }
 499        map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
 500        close(fd);
 501        if (-1 == (int)(long)map)
 502                return NULL;
 503        *size = st.st_size;
 504        return map;
 505}
 506
 507void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
 508{
 509        return map_sha1_file_internal(sha1, size, 1);
 510}
 511
 512int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
 513{
 514        /* Get the data stream */
 515        memset(stream, 0, sizeof(*stream));
 516        stream->next_in = map;
 517        stream->avail_in = mapsize;
 518        stream->next_out = buffer;
 519        stream->avail_out = size;
 520
 521        inflateInit(stream);
 522        return inflate(stream, 0);
 523}
 524
 525void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
 526{
 527        int bytes = strlen(buffer) + 1;
 528        unsigned char *buf = xmalloc(1+size);
 529
 530        memcpy(buf, buffer + bytes, stream->total_out - bytes);
 531        bytes = stream->total_out - bytes;
 532        if (bytes < size) {
 533                stream->next_out = buf + bytes;
 534                stream->avail_out = size - bytes;
 535                while (inflate(stream, Z_FINISH) == Z_OK)
 536                        /* nothing */;
 537        }
 538        buf[size] = 0;
 539        inflateEnd(stream);
 540        return buf;
 541}
 542
 543/*
 544 * We used to just use "sscanf()", but that's actually way
 545 * too permissive for what we want to check. So do an anal
 546 * object header parse by hand.
 547 */
 548int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
 549{
 550        int i;
 551        unsigned long size;
 552
 553        /*
 554         * The type can be at most ten bytes (including the 
 555         * terminating '\0' that we add), and is followed by
 556         * a space. 
 557         */
 558        i = 10;
 559        for (;;) {
 560                char c = *hdr++;
 561                if (c == ' ')
 562                        break;
 563                if (!--i)
 564                        return -1;
 565                *type++ = c;
 566        }
 567        *type = 0;
 568
 569        /*
 570         * The length must follow immediately, and be in canonical
 571         * decimal format (ie "010" is not valid).
 572         */
 573        size = *hdr++ - '0';
 574        if (size > 9)
 575                return -1;
 576        if (size) {
 577                for (;;) {
 578                        unsigned long c = *hdr - '0';
 579                        if (c > 9)
 580                                break;
 581                        hdr++;
 582                        size = size * 10 + c;
 583                }
 584        }
 585        *sizep = size;
 586
 587        /*
 588         * The length must be followed by a zero byte
 589         */
 590        return *hdr ? -1 : 0;
 591}
 592
 593void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
 594{
 595        int ret;
 596        z_stream stream;
 597        char hdr[8192];
 598
 599        ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
 600        if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
 601                return NULL;
 602
 603        return unpack_sha1_rest(&stream, hdr, *size);
 604}
 605
 606static int packed_delta_info(unsigned char *base_sha1,
 607                             unsigned long delta_size,
 608                             unsigned long left,
 609                             char *type,
 610                             unsigned long *sizep)
 611{
 612        unsigned char *data;
 613        unsigned char delta_head[64];
 614        int i;
 615        unsigned char cmd;
 616        unsigned long data_size, result_size, base_size, verify_base_size;
 617        z_stream stream;
 618        int st;
 619
 620        if (left < 20)
 621                die("truncated pack file");
 622        if (sha1_object_info(base_sha1, type, &base_size))
 623                die("cannot get info for delta-pack base");
 624
 625        data = base_sha1 + 20;
 626        data_size = left - 20;
 627
 628        memset(&stream, 0, sizeof(stream));
 629
 630        stream.next_in = data;
 631        stream.avail_in = data_size;
 632        stream.next_out = delta_head;
 633        stream.avail_out = sizeof(delta_head);
 634
 635        inflateInit(&stream);
 636        st = inflate(&stream, Z_FINISH);
 637        inflateEnd(&stream);
 638        if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head))
 639                die("delta data unpack-initial failed");
 640
 641        /* Examine the initial part of the delta to figure out
 642         * the result size.  Verify the base size while we are at it.
 643         */
 644        data = delta_head;
 645        verify_base_size = i = 0;
 646        cmd = *data++;
 647        while (cmd) {
 648                if (cmd & 1)
 649                        verify_base_size |= *data++ << i;
 650                i += 8;
 651                cmd >>= 1;
 652        }
 653
 654        /* Read the result size */
 655        result_size = i = 0;
 656        cmd = *data++;
 657        while (cmd) {
 658                if (cmd & 1)
 659                        result_size |= *data++ << i;
 660                i += 8;
 661                cmd >>= 1;
 662        }
 663        if (verify_base_size != base_size)
 664                die("delta base size mismatch");
 665
 666        *sizep = result_size;
 667        return 0;
 668}
 669
 670static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
 671        enum object_type *type, unsigned long *sizep)
 672{
 673        unsigned char *pack, c;
 674        unsigned long size;
 675
 676        if (offset >= p->pack_size)
 677                die("object offset outside of pack file");
 678
 679        pack =  p->pack_base + offset;
 680        c = *pack++;
 681        offset++;
 682        *type = (c >> 4) & 7;
 683        size = c & 15;
 684        while (c & 0x80) {
 685                if (offset >= p->pack_size)
 686                        die("object offset outside of pack file");
 687                c = *pack++;
 688                offset++;
 689                size = (size << 7) | (c & 0x7f);
 690        }
 691        *sizep = size;
 692        return offset;
 693}
 694
 695static int packed_object_info(struct pack_entry *entry,
 696                              char *type, unsigned long *sizep)
 697{
 698        struct packed_git *p = entry->p;
 699        unsigned long offset, size, left;
 700        unsigned char *pack;
 701        enum object_type kind;
 702
 703        if (use_packed_git(p))
 704                die("cannot map packed file");
 705
 706        offset = unpack_object_header(p, entry->offset, &kind, &size);
 707        pack = p->pack_base + offset;
 708        left = p->pack_size - offset;
 709
 710        switch (kind) {
 711        case OBJ_DELTA:
 712                return packed_delta_info(pack, size, left, type, sizep);
 713                break;
 714        case OBJ_COMMIT:
 715                strcpy(type, "commit");
 716                break;
 717        case OBJ_TREE:
 718                strcpy(type, "tree");
 719                break;
 720        case OBJ_BLOB:
 721                strcpy(type, "blob");
 722                break;
 723        case OBJ_TAG:
 724                strcpy(type, "tag");
 725                break;
 726        default:
 727                die("corrupted pack file");
 728        }
 729        *sizep = size;
 730        return 0;
 731}
 732
 733/* forward declaration for a mutually recursive function */
 734static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
 735
 736static void *unpack_delta_entry(unsigned char *base_sha1,
 737                                unsigned long delta_size,
 738                                unsigned long left,
 739                                char *type,
 740                                unsigned long *sizep)
 741{
 742        void *data, *delta_data, *result, *base;
 743        unsigned long data_size, result_size, base_size;
 744        z_stream stream;
 745        int st;
 746
 747        if (left < 20)
 748                die("truncated pack file");
 749        data = base_sha1 + 20;
 750        data_size = left - 20;
 751        delta_data = xmalloc(delta_size);
 752
 753        memset(&stream, 0, sizeof(stream));
 754
 755        stream.next_in = data;
 756        stream.avail_in = data_size;
 757        stream.next_out = delta_data;
 758        stream.avail_out = delta_size;
 759
 760        inflateInit(&stream);
 761        st = inflate(&stream, Z_FINISH);
 762        inflateEnd(&stream);
 763        if ((st != Z_STREAM_END) || stream.total_out != delta_size)
 764                die("delta data unpack failed");
 765
 766        /* This may recursively unpack the base, which is what we want */
 767        base = read_sha1_file(base_sha1, type, &base_size);
 768        if (!base)
 769                die("failed to read delta-pack base object %s",
 770                    sha1_to_hex(base_sha1));
 771        result = patch_delta(base, base_size,
 772                             delta_data, delta_size,
 773                             &result_size);
 774        if (!result)
 775                die("failed to apply delta");
 776        free(delta_data);
 777        free(base);
 778        *sizep = result_size;
 779        return result;
 780}
 781
 782static void *unpack_non_delta_entry(unsigned char *data,
 783                                    unsigned long size,
 784                                    unsigned long left)
 785{
 786        int st;
 787        z_stream stream;
 788        char *buffer;
 789
 790        buffer = xmalloc(size + 1);
 791        buffer[size] = 0;
 792        memset(&stream, 0, sizeof(stream));
 793        stream.next_in = data;
 794        stream.avail_in = left;
 795        stream.next_out = buffer;
 796        stream.avail_out = size;
 797
 798        inflateInit(&stream);
 799        st = inflate(&stream, Z_FINISH);
 800        inflateEnd(&stream);
 801        if ((st != Z_STREAM_END) || stream.total_out != size) {
 802                free(buffer);
 803                return NULL;
 804        }
 805
 806        return buffer;
 807}
 808
 809static void *unpack_entry(struct pack_entry *entry,
 810                          char *type, unsigned long *sizep)
 811{
 812        struct packed_git *p = entry->p;
 813        unsigned long offset, size, left;
 814        unsigned char *pack;
 815        enum object_type kind;
 816
 817        if (use_packed_git(p))
 818                die("cannot map packed file");
 819
 820        offset = unpack_object_header(p, entry->offset, &kind, &size);
 821        pack = p->pack_base + offset;
 822        left = p->pack_size - offset;
 823        switch (kind) {
 824        case OBJ_DELTA:
 825                return unpack_delta_entry(pack, size, left, type, sizep);
 826        case OBJ_COMMIT:
 827                strcpy(type, "commit");
 828                break;
 829        case OBJ_TREE:
 830                strcpy(type, "tree");
 831                break;
 832        case OBJ_BLOB:
 833                strcpy(type, "blob");
 834                break;
 835        case OBJ_TAG:
 836                strcpy(type, "tag");
 837                break;
 838        default:
 839                die("corrupted pack file");
 840        }
 841        *sizep = size;
 842        return unpack_non_delta_entry(pack, size, left);
 843}
 844
 845static int find_pack_entry_1(const unsigned char *sha1,
 846                             struct pack_entry *e, struct packed_git *p)
 847{
 848        int *level1_ofs = p->index_base;
 849        int hi = ntohl(level1_ofs[*sha1]);
 850        int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
 851        void *index = p->index_base + 256;
 852
 853        do {
 854                int mi = (lo + hi) / 2;
 855                int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
 856                if (!cmp) {
 857                        e->offset = ntohl(*((int*)(index + 24 * mi)));
 858                        memcpy(e->sha1, sha1, 20);
 859                        e->p = p;
 860                        return 1;
 861                }
 862                if (cmp > 0)
 863                        hi = mi;
 864                else
 865                        lo = mi+1;
 866        } while (lo < hi);
 867        return 0;
 868}
 869
 870static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
 871{
 872        struct packed_git *p;
 873        prepare_packed_git();
 874
 875        for (p = packed_git; p; p = p->next) {
 876                if (find_pack_entry_1(sha1, e, p))
 877                        return 1;
 878        }
 879        return 0;
 880}
 881
 882int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
 883{
 884        int status;
 885        unsigned long mapsize, size;
 886        void *map;
 887        z_stream stream;
 888        char hdr[128];
 889
 890        map = map_sha1_file_internal(sha1, &mapsize, 0);
 891        if (!map) {
 892                struct pack_entry e;
 893
 894                if (!find_pack_entry(sha1, &e))
 895                        return error("unable to find %s", sha1_to_hex(sha1));
 896                if (!packed_object_info(&e, type, sizep))
 897                        return 0;
 898                /* sheesh */
 899                map = unpack_entry(&e, type, sizep);
 900                free(map);
 901                return (map == NULL) ? 0 : -1;
 902        }
 903        if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
 904                status = error("unable to unpack %s header",
 905                               sha1_to_hex(sha1));
 906        if (parse_sha1_header(hdr, type, &size) < 0)
 907                status = error("unable to parse %s header", sha1_to_hex(sha1));
 908        else {
 909                status = 0;
 910                *sizep = size;
 911        }
 912        inflateEnd(&stream);
 913        munmap(map, mapsize);
 914        return status;
 915}
 916
 917static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
 918{
 919        struct pack_entry e;
 920
 921        if (!find_pack_entry(sha1, &e)) {
 922                error("cannot read sha1_file for %s", sha1_to_hex(sha1));
 923                return NULL;
 924        }
 925        return unpack_entry(&e, type, size);
 926}
 927
 928void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
 929{
 930        unsigned long mapsize;
 931        void *map, *buf;
 932
 933        map = map_sha1_file_internal(sha1, &mapsize, 0);
 934        if (map) {
 935                buf = unpack_sha1_file(map, mapsize, type, size);
 936                munmap(map, mapsize);
 937                return buf;
 938        }
 939        return read_packed_sha1(sha1, type, size);
 940}
 941
 942void *read_object_with_reference(const unsigned char *sha1,
 943                                 const char *required_type,
 944                                 unsigned long *size,
 945                                 unsigned char *actual_sha1_return)
 946{
 947        char type[20];
 948        void *buffer;
 949        unsigned long isize;
 950        unsigned char actual_sha1[20];
 951
 952        memcpy(actual_sha1, sha1, 20);
 953        while (1) {
 954                int ref_length = -1;
 955                const char *ref_type = NULL;
 956
 957                buffer = read_sha1_file(actual_sha1, type, &isize);
 958                if (!buffer)
 959                        return NULL;
 960                if (!strcmp(type, required_type)) {
 961                        *size = isize;
 962                        if (actual_sha1_return)
 963                                memcpy(actual_sha1_return, actual_sha1, 20);
 964                        return buffer;
 965                }
 966                /* Handle references */
 967                else if (!strcmp(type, "commit"))
 968                        ref_type = "tree ";
 969                else if (!strcmp(type, "tag"))
 970                        ref_type = "object ";
 971                else {
 972                        free(buffer);
 973                        return NULL;
 974                }
 975                ref_length = strlen(ref_type);
 976
 977                if (memcmp(buffer, ref_type, ref_length) ||
 978                    get_sha1_hex(buffer + ref_length, actual_sha1)) {
 979                        free(buffer);
 980                        return NULL;
 981                }
 982                /* Now we have the ID of the referred-to object in
 983                 * actual_sha1.  Check again. */
 984        }
 985}
 986
 987static char *write_sha1_file_prepare(void *buf,
 988                                     unsigned long len,
 989                                     const char *type,
 990                                     unsigned char *sha1,
 991                                     unsigned char *hdr,
 992                                     int *hdrlen)
 993{
 994        SHA_CTX c;
 995
 996        /* Generate the header */
 997        *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
 998
 999        /* Sha1.. */
1000        SHA1_Init(&c);
1001        SHA1_Update(&c, hdr, *hdrlen);
1002        SHA1_Update(&c, buf, len);
1003        SHA1_Final(sha1, &c);
1004
1005        return sha1_file_name(sha1);
1006}
1007
1008int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1009{
1010        int size;
1011        unsigned char *compressed;
1012        z_stream stream;
1013        unsigned char sha1[20];
1014        char *filename;
1015        static char tmpfile[PATH_MAX];
1016        unsigned char hdr[50];
1017        int fd, hdrlen, ret;
1018
1019        /* Normally if we have it in the pack then we do not bother writing
1020         * it out into .git/objects/??/?{38} file.
1021         */
1022        filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1023        if (returnsha1)
1024                memcpy(returnsha1, sha1, 20);
1025        if (has_sha1_file(sha1))
1026                return 0;
1027        fd = open(filename, O_RDONLY);
1028        if (fd >= 0) {
1029                /*
1030                 * FIXME!!! We might do collision checking here, but we'd
1031                 * need to uncompress the old file and check it. Later.
1032                 */
1033                close(fd);
1034                return 0;
1035        }
1036
1037        if (errno != ENOENT) {
1038                fprintf(stderr, "sha1 file %s: %s", filename, strerror(errno));
1039                return -1;
1040        }
1041
1042        snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1043
1044        fd = mkstemp(tmpfile);
1045        if (fd < 0) {
1046                fprintf(stderr, "unable to create temporary sha1 filename %s: %s", tmpfile, strerror(errno));
1047                return -1;
1048        }
1049
1050        /* Set it up */
1051        memset(&stream, 0, sizeof(stream));
1052        deflateInit(&stream, Z_BEST_COMPRESSION);
1053        size = deflateBound(&stream, len+hdrlen);
1054        compressed = xmalloc(size);
1055
1056        /* Compress it */
1057        stream.next_out = compressed;
1058        stream.avail_out = size;
1059
1060        /* First header.. */
1061        stream.next_in = hdr;
1062        stream.avail_in = hdrlen;
1063        while (deflate(&stream, 0) == Z_OK)
1064                /* nothing */;
1065
1066        /* Then the data itself.. */
1067        stream.next_in = buf;
1068        stream.avail_in = len;
1069        while (deflate(&stream, Z_FINISH) == Z_OK)
1070                /* nothing */;
1071        deflateEnd(&stream);
1072        size = stream.total_out;
1073
1074        if (write(fd, compressed, size) != size)
1075                die("unable to write file");
1076        fchmod(fd, 0444);
1077        close(fd);
1078        free(compressed);
1079
1080        ret = link(tmpfile, filename);
1081        if (ret < 0) {
1082                ret = errno;
1083
1084                /*
1085                 * Coda hack - coda doesn't like cross-directory links,
1086                 * so we fall back to a rename, which will mean that it
1087                 * won't be able to check collisions, but that's not a
1088                 * big deal.
1089                 *
1090                 * When this succeeds, we just return 0. We have nothing
1091                 * left to unlink.
1092                 */
1093                if (ret == EXDEV && !rename(tmpfile, filename))
1094                        return 0;
1095        }
1096        unlink(tmpfile);
1097        if (ret) {
1098                if (ret != EEXIST) {
1099                        fprintf(stderr, "unable to write sha1 filename %s: %s", filename, strerror(ret));
1100                        return -1;
1101                }
1102                /* FIXME!!! Collision check here ? */
1103        }
1104
1105        return 0;
1106}
1107
1108int write_sha1_from_fd(const unsigned char *sha1, int fd)
1109{
1110        char *filename = sha1_file_name(sha1);
1111
1112        int local;
1113        z_stream stream;
1114        unsigned char real_sha1[20];
1115        unsigned char buf[4096];
1116        unsigned char discard[4096];
1117        int ret;
1118        SHA_CTX c;
1119
1120        local = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0666);
1121
1122        if (local < 0)
1123                return error("Couldn't open %s\n", filename);
1124
1125        memset(&stream, 0, sizeof(stream));
1126
1127        inflateInit(&stream);
1128
1129        SHA1_Init(&c);
1130
1131        do {
1132                ssize_t size;
1133                size = read(fd, buf, 4096);
1134                if (size <= 0) {
1135                        close(local);
1136                        unlink(filename);
1137                        if (!size)
1138                                return error("Connection closed?");
1139                        perror("Reading from connection");
1140                        return -1;
1141                }
1142                write(local, buf, size);
1143                stream.avail_in = size;
1144                stream.next_in = buf;
1145                do {
1146                        stream.next_out = discard;
1147                        stream.avail_out = sizeof(discard);
1148                        ret = inflate(&stream, Z_SYNC_FLUSH);
1149                        SHA1_Update(&c, discard, sizeof(discard) -
1150                                    stream.avail_out);
1151                } while (stream.avail_in && ret == Z_OK);
1152                
1153        } while (ret == Z_OK);
1154        inflateEnd(&stream);
1155
1156        close(local);
1157        SHA1_Final(real_sha1, &c);
1158        if (ret != Z_STREAM_END) {
1159                unlink(filename);
1160                return error("File %s corrupted", sha1_to_hex(sha1));
1161        }
1162        if (memcmp(sha1, real_sha1, 20)) {
1163                unlink(filename);
1164                return error("File %s has bad hash\n", sha1_to_hex(sha1));
1165        }
1166        
1167        return 0;
1168}
1169
1170int has_sha1_file(const unsigned char *sha1)
1171{
1172        struct stat st;
1173        struct pack_entry e;
1174
1175        if (find_sha1_file(sha1, &st))
1176                return 1;
1177        return find_pack_entry(sha1, &e);
1178}
1179
1180int index_fd(unsigned char *sha1, int fd, struct stat *st)
1181{
1182        unsigned long size = st->st_size;
1183        void *buf;
1184        int ret;
1185
1186        buf = "";
1187        if (size)
1188                buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1189        close(fd);
1190        if ((int)(long)buf == -1)
1191                return -1;
1192
1193        ret = write_sha1_file(buf, size, "blob", sha1);
1194        if (size)
1195                munmap(buf, size);
1196        return ret;
1197}