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