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