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