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