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