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