sha1_file.con commit Merge branch 'jc/fmt-patch' into next (b9d301b)
   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 "cache.h"
  10#include "delta.h"
  11#include "pack.h"
  12#include "blob.h"
  13#include "commit.h"
  14#include "tag.h"
  15#include "tree.h"
  16
  17#ifndef O_NOATIME
  18#if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
  19#define O_NOATIME 01000000
  20#else
  21#define O_NOATIME 0
  22#endif
  23#endif
  24
  25const unsigned char null_sha1[20] = { 0, };
  26
  27static unsigned int sha1_file_open_flag = O_NOATIME;
  28
  29static unsigned hexval(char c)
  30{
  31        if (c >= '0' && c <= '9')
  32                return c - '0';
  33        if (c >= 'a' && c <= 'f')
  34                return c - 'a' + 10;
  35        if (c >= 'A' && c <= 'F')
  36                return c - 'A' + 10;
  37        return ~0;
  38}
  39
  40int get_sha1_hex(const char *hex, unsigned char *sha1)
  41{
  42        int i;
  43        for (i = 0; i < 20; i++) {
  44                unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
  45                if (val & ~0xff)
  46                        return -1;
  47                *sha1++ = val;
  48                hex += 2;
  49        }
  50        return 0;
  51}
  52
  53int adjust_shared_perm(const char *path)
  54{
  55        struct stat st;
  56        int mode;
  57
  58        if (!shared_repository)
  59                return 0;
  60        if (lstat(path, &st) < 0)
  61                return -1;
  62        mode = st.st_mode;
  63        if (mode & S_IRUSR)
  64                mode |= S_IRGRP;
  65        if (mode & S_IWUSR)
  66                mode |= S_IWGRP;
  67        if (mode & S_IXUSR)
  68                mode |= S_IXGRP;
  69        if (S_ISDIR(mode))
  70                mode |= S_ISGID;
  71        if (chmod(path, mode) < 0)
  72                return -2;
  73        return 0;
  74}
  75
  76int safe_create_leading_directories(char *path)
  77{
  78        char *pos = path;
  79        struct stat st;
  80
  81        if (*pos == '/')
  82                pos++;
  83
  84        while (pos) {
  85                pos = strchr(pos, '/');
  86                if (!pos)
  87                        break;
  88                *pos = 0;
  89                if (!stat(path, &st)) {
  90                        /* path exists */
  91                        if (!S_ISDIR(st.st_mode)) {
  92                                *pos = '/';
  93                                return -3;
  94                        }
  95                }
  96                else if (mkdir(path, 0777)) {
  97                        *pos = '/';
  98                        return -1;
  99                }
 100                else if (adjust_shared_perm(path)) {
 101                        *pos = '/';
 102                        return -2;
 103                }
 104                *pos++ = '/';
 105        }
 106        return 0;
 107}
 108
 109char * sha1_to_hex(const unsigned char *sha1)
 110{
 111        static int bufno;
 112        static char hexbuffer[4][50];
 113        static const char hex[] = "0123456789abcdef";
 114        char *buffer = hexbuffer[3 & ++bufno], *buf = buffer;
 115        int i;
 116
 117        for (i = 0; i < 20; i++) {
 118                unsigned int val = *sha1++;
 119                *buf++ = hex[val >> 4];
 120                *buf++ = hex[val & 0xf];
 121        }
 122        *buf = '\0';
 123
 124        return buffer;
 125}
 126
 127static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
 128{
 129        int i;
 130        for (i = 0; i < 20; i++) {
 131                static char hex[] = "0123456789abcdef";
 132                unsigned int val = sha1[i];
 133                char *pos = pathbuf + i*2 + (i > 0);
 134                *pos++ = hex[val >> 4];
 135                *pos = hex[val & 0xf];
 136        }
 137}
 138
 139/*
 140 * NOTE! This returns a statically allocated buffer, so you have to be
 141 * careful about using it. Do a "strdup()" if you need to save the
 142 * filename.
 143 *
 144 * Also note that this returns the location for creating.  Reading
 145 * SHA1 file can happen from any alternate directory listed in the
 146 * DB_ENVIRONMENT environment variable if it is not found in
 147 * the primary object database.
 148 */
 149char *sha1_file_name(const unsigned char *sha1)
 150{
 151        static char *name, *base;
 152
 153        if (!base) {
 154                const char *sha1_file_directory = get_object_directory();
 155                int len = strlen(sha1_file_directory);
 156                base = xmalloc(len + 60);
 157                memcpy(base, sha1_file_directory, len);
 158                memset(base+len, 0, 60);
 159                base[len] = '/';
 160                base[len+3] = '/';
 161                name = base + len + 1;
 162        }
 163        fill_sha1_path(name, sha1);
 164        return base;
 165}
 166
 167char *sha1_pack_name(const unsigned char *sha1)
 168{
 169        static const char hex[] = "0123456789abcdef";
 170        static char *name, *base, *buf;
 171        int i;
 172
 173        if (!base) {
 174                const char *sha1_file_directory = get_object_directory();
 175                int len = strlen(sha1_file_directory);
 176                base = xmalloc(len + 60);
 177                sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
 178                name = base + len + 11;
 179        }
 180
 181        buf = name;
 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        
 189        return base;
 190}
 191
 192char *sha1_pack_index_name(const unsigned char *sha1)
 193{
 194        static const char hex[] = "0123456789abcdef";
 195        static char *name, *base, *buf;
 196        int i;
 197
 198        if (!base) {
 199                const char *sha1_file_directory = get_object_directory();
 200                int len = strlen(sha1_file_directory);
 201                base = xmalloc(len + 60);
 202                sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
 203                name = base + len + 11;
 204        }
 205
 206        buf = name;
 207
 208        for (i = 0; i < 20; i++) {
 209                unsigned int val = *sha1++;
 210                *buf++ = hex[val >> 4];
 211                *buf++ = hex[val & 0xf];
 212        }
 213        
 214        return base;
 215}
 216
 217struct alternate_object_database *alt_odb_list;
 218static struct alternate_object_database **alt_odb_tail;
 219
 220static void read_info_alternates(const char * alternates, int depth);
 221
 222/*
 223 * Prepare alternate object database registry.
 224 *
 225 * The variable alt_odb_list points at the list of struct
 226 * alternate_object_database.  The elements on this list come from
 227 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
 228 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
 229 * whose contents is similar to that environment variable but can be
 230 * LF separated.  Its base points at a statically allocated buffer that
 231 * contains "/the/directory/corresponding/to/.git/objects/...", while
 232 * its name points just after the slash at the end of ".git/objects/"
 233 * in the example above, and has enough space to hold 40-byte hex
 234 * SHA1, an extra slash for the first level indirection, and the
 235 * terminating NUL.
 236 */
 237static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
 238{
 239        struct stat st;
 240        const char *objdir = get_object_directory();
 241        struct alternate_object_database *ent;
 242        struct alternate_object_database *alt;
 243        /* 43 = 40-byte + 2 '/' + terminating NUL */
 244        int pfxlen = len;
 245        int entlen = pfxlen + 43;
 246        int base_len = -1;
 247
 248        if (*entry != '/' && relative_base) {
 249                /* Relative alt-odb */
 250                if (base_len < 0)
 251                        base_len = strlen(relative_base) + 1;
 252                entlen += base_len;
 253                pfxlen += base_len;
 254        }
 255        ent = xmalloc(sizeof(*ent) + entlen);
 256
 257        if (*entry != '/' && relative_base) {
 258                memcpy(ent->base, relative_base, base_len - 1);
 259                ent->base[base_len - 1] = '/';
 260                memcpy(ent->base + base_len, entry, len);
 261        }
 262        else
 263                memcpy(ent->base, entry, pfxlen);
 264
 265        ent->name = ent->base + pfxlen + 1;
 266        ent->base[pfxlen + 3] = '/';
 267        ent->base[pfxlen] = ent->base[entlen-1] = 0;
 268
 269        /* Detect cases where alternate disappeared */
 270        if (stat(ent->base, &st) || !S_ISDIR(st.st_mode)) {
 271                error("object directory %s does not exist; "
 272                      "check .git/objects/info/alternates.",
 273                      ent->base);
 274                free(ent);
 275                return -1;
 276        }
 277
 278        /* Prevent the common mistake of listing the same
 279         * thing twice, or object directory itself.
 280         */
 281        for (alt = alt_odb_list; alt; alt = alt->next) {
 282                if (!memcmp(ent->base, alt->base, pfxlen)) {
 283                        free(ent);
 284                        return -1;
 285                }
 286        }
 287        if (!memcmp(ent->base, objdir, pfxlen)) {
 288                free(ent);
 289                return -1;
 290        }
 291
 292        /* add the alternate entry */
 293        *alt_odb_tail = ent;
 294        alt_odb_tail = &(ent->next);
 295        ent->next = NULL;
 296
 297        /* recursively add alternates */
 298        read_info_alternates(ent->base, depth + 1);
 299
 300        ent->base[pfxlen] = '/';
 301
 302        return 0;
 303}
 304
 305static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
 306                                 const char *relative_base, int depth)
 307{
 308        const char *cp, *last;
 309
 310        if (depth > 5) {
 311                error("%s: ignoring alternate object stores, nesting too deep.",
 312                                relative_base);
 313                return;
 314        }
 315
 316        last = alt;
 317        while (last < ep) {
 318                cp = last;
 319                if (cp < ep && *cp == '#') {
 320                        while (cp < ep && *cp != sep)
 321                                cp++;
 322                        last = cp + 1;
 323                        continue;
 324                }
 325                while (cp < ep && *cp != sep)
 326                        cp++;
 327                if (last != cp) {
 328                        if ((*last != '/') && depth) {
 329                                error("%s: ignoring relative alternate object store %s",
 330                                                relative_base, last);
 331                        } else {
 332                                link_alt_odb_entry(last, cp - last,
 333                                                relative_base, depth);
 334                        }
 335                }
 336                while (cp < ep && *cp == sep)
 337                        cp++;
 338                last = cp;
 339        }
 340}
 341
 342static void read_info_alternates(const char * relative_base, int depth)
 343{
 344        char *map;
 345        struct stat st;
 346        char path[PATH_MAX];
 347        int fd;
 348
 349        sprintf(path, "%s/info/alternates", relative_base);
 350        fd = open(path, O_RDONLY);
 351        if (fd < 0)
 352                return;
 353        if (fstat(fd, &st) || (st.st_size == 0)) {
 354                close(fd);
 355                return;
 356        }
 357        map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
 358        close(fd);
 359        if (map == MAP_FAILED)
 360                return;
 361
 362        link_alt_odb_entries(map, map + st.st_size, '\n', relative_base, depth);
 363
 364        munmap(map, st.st_size);
 365}
 366
 367void prepare_alt_odb(void)
 368{
 369        char *alt;
 370
 371        alt = getenv(ALTERNATE_DB_ENVIRONMENT);
 372        if (!alt) alt = "";
 373
 374        if (alt_odb_tail)
 375                return;
 376        alt_odb_tail = &alt_odb_list;
 377        link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL, 0);
 378
 379        read_info_alternates(get_object_directory(), 0);
 380}
 381
 382static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
 383{
 384        char *name = sha1_file_name(sha1);
 385        struct alternate_object_database *alt;
 386
 387        if (!stat(name, st))
 388                return name;
 389        prepare_alt_odb();
 390        for (alt = alt_odb_list; alt; alt = alt->next) {
 391                name = alt->name;
 392                fill_sha1_path(name, sha1);
 393                if (!stat(alt->base, st))
 394                        return alt->base;
 395        }
 396        return NULL;
 397}
 398
 399#define PACK_MAX_SZ (1<<26)
 400static int pack_used_ctr;
 401static unsigned long pack_mapped;
 402struct packed_git *packed_git;
 403
 404static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
 405                                void **idx_map_)
 406{
 407        void *idx_map;
 408        unsigned int *index;
 409        unsigned long idx_size;
 410        int nr, i;
 411        int fd = open(path, O_RDONLY);
 412        struct stat st;
 413        if (fd < 0)
 414                return -1;
 415        if (fstat(fd, &st)) {
 416                close(fd);
 417                return -1;
 418        }
 419        idx_size = st.st_size;
 420        idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
 421        close(fd);
 422        if (idx_map == MAP_FAILED)
 423                return -1;
 424
 425        index = idx_map;
 426        *idx_map_ = idx_map;
 427        *idx_size_ = idx_size;
 428
 429        /* check index map */
 430        if (idx_size < 4*256 + 20 + 20)
 431                return error("index file too small");
 432        nr = 0;
 433        for (i = 0; i < 256; i++) {
 434                unsigned int n = ntohl(index[i]);
 435                if (n < nr)
 436                        return error("non-monotonic index");
 437                nr = n;
 438        }
 439
 440        /*
 441         * Total size:
 442         *  - 256 index entries 4 bytes each
 443         *  - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
 444         *  - 20-byte SHA1 of the packfile
 445         *  - 20-byte SHA1 file checksum
 446         */
 447        if (idx_size != 4*256 + nr * 24 + 20 + 20)
 448                return error("wrong index file size");
 449
 450        return 0;
 451}
 452
 453static int unuse_one_packed_git(void)
 454{
 455        struct packed_git *p, *lru = NULL;
 456
 457        for (p = packed_git; p; p = p->next) {
 458                if (p->pack_use_cnt || !p->pack_base)
 459                        continue;
 460                if (!lru || p->pack_last_used < lru->pack_last_used)
 461                        lru = p;
 462        }
 463        if (!lru)
 464                return 0;
 465        munmap(lru->pack_base, lru->pack_size);
 466        lru->pack_base = NULL;
 467        return 1;
 468}
 469
 470void unuse_packed_git(struct packed_git *p)
 471{
 472        p->pack_use_cnt--;
 473}
 474
 475int use_packed_git(struct packed_git *p)
 476{
 477        if (!p->pack_size) {
 478                struct stat st;
 479                // We created the struct before we had the pack
 480                stat(p->pack_name, &st);
 481                if (!S_ISREG(st.st_mode))
 482                        die("packfile %s not a regular file", p->pack_name);
 483                p->pack_size = st.st_size;
 484        }
 485        if (!p->pack_base) {
 486                int fd;
 487                struct stat st;
 488                void *map;
 489
 490                pack_mapped += p->pack_size;
 491                while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
 492                        ; /* nothing */
 493                fd = open(p->pack_name, O_RDONLY);
 494                if (fd < 0)
 495                        die("packfile %s cannot be opened", p->pack_name);
 496                if (fstat(fd, &st)) {
 497                        close(fd);
 498                        die("packfile %s cannot be opened", p->pack_name);
 499                }
 500                if (st.st_size != p->pack_size)
 501                        die("packfile %s size mismatch.", p->pack_name);
 502                map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
 503                close(fd);
 504                if (map == MAP_FAILED)
 505                        die("packfile %s cannot be mapped.", p->pack_name);
 506                p->pack_base = map;
 507
 508                /* Check if the pack file matches with the index file.
 509                 * this is cheap.
 510                 */
 511                if (memcmp((char*)(p->index_base) + p->index_size - 40,
 512                           p->pack_base + p->pack_size - 20, 20)) {
 513                              
 514                        die("packfile %s does not match index.", p->pack_name);
 515                }
 516        }
 517        p->pack_last_used = pack_used_ctr++;
 518        p->pack_use_cnt++;
 519        return 0;
 520}
 521
 522struct packed_git *add_packed_git(char *path, int path_len, int local)
 523{
 524        struct stat st;
 525        struct packed_git *p;
 526        unsigned long idx_size;
 527        void *idx_map;
 528        unsigned char sha1[20];
 529
 530        if (check_packed_git_idx(path, &idx_size, &idx_map))
 531                return NULL;
 532
 533        /* do we have a corresponding .pack file? */
 534        strcpy(path + path_len - 4, ".pack");
 535        if (stat(path, &st) || !S_ISREG(st.st_mode)) {
 536                munmap(idx_map, idx_size);
 537                return NULL;
 538        }
 539        /* ok, it looks sane as far as we can check without
 540         * actually mapping the pack file.
 541         */
 542        p = xmalloc(sizeof(*p) + path_len + 2);
 543        strcpy(p->pack_name, path);
 544        p->index_size = idx_size;
 545        p->pack_size = st.st_size;
 546        p->index_base = idx_map;
 547        p->next = NULL;
 548        p->pack_base = NULL;
 549        p->pack_last_used = 0;
 550        p->pack_use_cnt = 0;
 551        p->pack_local = local;
 552        if ((path_len > 44) && !get_sha1_hex(path + path_len - 44, sha1))
 553                memcpy(p->sha1, sha1, 20);
 554        return p;
 555}
 556
 557struct packed_git *parse_pack_index(unsigned char *sha1)
 558{
 559        char *path = sha1_pack_index_name(sha1);
 560        return parse_pack_index_file(sha1, path);
 561}
 562
 563struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
 564{
 565        struct packed_git *p;
 566        unsigned long idx_size;
 567        void *idx_map;
 568        char *path;
 569
 570        if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
 571                return NULL;
 572
 573        path = sha1_pack_name(sha1);
 574
 575        p = xmalloc(sizeof(*p) + strlen(path) + 2);
 576        strcpy(p->pack_name, path);
 577        p->index_size = idx_size;
 578        p->pack_size = 0;
 579        p->index_base = idx_map;
 580        p->next = NULL;
 581        p->pack_base = NULL;
 582        p->pack_last_used = 0;
 583        p->pack_use_cnt = 0;
 584        memcpy(p->sha1, sha1, 20);
 585        return p;
 586}
 587
 588void install_packed_git(struct packed_git *pack)
 589{
 590        pack->next = packed_git;
 591        packed_git = pack;
 592}
 593
 594static void prepare_packed_git_one(char *objdir, int local)
 595{
 596        char path[PATH_MAX];
 597        int len;
 598        DIR *dir;
 599        struct dirent *de;
 600
 601        sprintf(path, "%s/pack", objdir);
 602        len = strlen(path);
 603        dir = opendir(path);
 604        if (!dir) {
 605                if (errno != ENOENT)
 606                        error("unable to open object pack directory: %s: %s",
 607                              path, strerror(errno));
 608                return;
 609        }
 610        path[len++] = '/';
 611        while ((de = readdir(dir)) != NULL) {
 612                int namelen = strlen(de->d_name);
 613                struct packed_git *p;
 614
 615                if (strcmp(de->d_name + namelen - 4, ".idx"))
 616                        continue;
 617
 618                /* we have .idx.  Is it a file we can map? */
 619                strcpy(path + len, de->d_name);
 620                for (p = packed_git; p; p = p->next) {
 621                        if (!memcmp(path, p->pack_name, len + namelen - 4))
 622                                break;
 623                }
 624                if (p)
 625                        continue;
 626                p = add_packed_git(path, len + namelen, local);
 627                if (!p)
 628                        continue;
 629                p->next = packed_git;
 630                packed_git = p;
 631        }
 632        closedir(dir);
 633}
 634
 635static int prepare_packed_git_run_once = 0;
 636void prepare_packed_git(void)
 637{
 638        struct alternate_object_database *alt;
 639
 640        if (prepare_packed_git_run_once)
 641                return;
 642        prepare_packed_git_one(get_object_directory(), 1);
 643        prepare_alt_odb();
 644        for (alt = alt_odb_list; alt; alt = alt->next) {
 645                alt->name[-1] = 0;
 646                prepare_packed_git_one(alt->base, 0);
 647                alt->name[-1] = '/';
 648        }
 649        prepare_packed_git_run_once = 1;
 650}
 651
 652static void reprepare_packed_git(void)
 653{
 654        prepare_packed_git_run_once = 0;
 655        prepare_packed_git();
 656}
 657
 658int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
 659{
 660        char header[100];
 661        unsigned char real_sha1[20];
 662        SHA_CTX c;
 663
 664        SHA1_Init(&c);
 665        SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
 666        SHA1_Update(&c, map, size);
 667        SHA1_Final(real_sha1, &c);
 668        return memcmp(sha1, real_sha1, 20) ? -1 : 0;
 669}
 670
 671static void *map_sha1_file_internal(const unsigned char *sha1,
 672                                    unsigned long *size)
 673{
 674        struct stat st;
 675        void *map;
 676        int fd;
 677        char *filename = find_sha1_file(sha1, &st);
 678
 679        if (!filename) {
 680                return NULL;
 681        }
 682
 683        fd = open(filename, O_RDONLY | sha1_file_open_flag);
 684        if (fd < 0) {
 685                /* See if it works without O_NOATIME */
 686                switch (sha1_file_open_flag) {
 687                default:
 688                        fd = open(filename, O_RDONLY);
 689                        if (fd >= 0)
 690                                break;
 691                /* Fallthrough */
 692                case 0:
 693                        return NULL;
 694                }
 695
 696                /* If it failed once, it will probably fail again.
 697                 * Stop using O_NOATIME
 698                 */
 699                sha1_file_open_flag = 0;
 700        }
 701        map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
 702        close(fd);
 703        if (map == MAP_FAILED)
 704                return NULL;
 705        *size = st.st_size;
 706        return map;
 707}
 708
 709int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
 710{
 711        /* Get the data stream */
 712        memset(stream, 0, sizeof(*stream));
 713        stream->next_in = map;
 714        stream->avail_in = mapsize;
 715        stream->next_out = buffer;
 716        stream->avail_out = size;
 717
 718        inflateInit(stream);
 719        return inflate(stream, 0);
 720}
 721
 722static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
 723{
 724        int bytes = strlen(buffer) + 1;
 725        unsigned char *buf = xmalloc(1+size);
 726
 727        memcpy(buf, buffer + bytes, stream->total_out - bytes);
 728        bytes = stream->total_out - bytes;
 729        if (bytes < size) {
 730                stream->next_out = buf + bytes;
 731                stream->avail_out = size - bytes;
 732                while (inflate(stream, Z_FINISH) == Z_OK)
 733                        /* nothing */;
 734        }
 735        buf[size] = 0;
 736        inflateEnd(stream);
 737        return buf;
 738}
 739
 740/*
 741 * We used to just use "sscanf()", but that's actually way
 742 * too permissive for what we want to check. So do an anal
 743 * object header parse by hand.
 744 */
 745int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
 746{
 747        int i;
 748        unsigned long size;
 749
 750        /*
 751         * The type can be at most ten bytes (including the 
 752         * terminating '\0' that we add), and is followed by
 753         * a space. 
 754         */
 755        i = 10;
 756        for (;;) {
 757                char c = *hdr++;
 758                if (c == ' ')
 759                        break;
 760                if (!--i)
 761                        return -1;
 762                *type++ = c;
 763        }
 764        *type = 0;
 765
 766        /*
 767         * The length must follow immediately, and be in canonical
 768         * decimal format (ie "010" is not valid).
 769         */
 770        size = *hdr++ - '0';
 771        if (size > 9)
 772                return -1;
 773        if (size) {
 774                for (;;) {
 775                        unsigned long c = *hdr - '0';
 776                        if (c > 9)
 777                                break;
 778                        hdr++;
 779                        size = size * 10 + c;
 780                }
 781        }
 782        *sizep = size;
 783
 784        /*
 785         * The length must be followed by a zero byte
 786         */
 787        return *hdr ? -1 : 0;
 788}
 789
 790void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
 791{
 792        int ret;
 793        z_stream stream;
 794        char hdr[8192];
 795
 796        ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
 797        if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
 798                return NULL;
 799
 800        return unpack_sha1_rest(&stream, hdr, *size);
 801}
 802
 803/* forward declaration for a mutually recursive function */
 804static int packed_object_info(struct pack_entry *entry,
 805                              char *type, unsigned long *sizep);
 806
 807static int packed_delta_info(unsigned char *base_sha1,
 808                             unsigned long delta_size,
 809                             unsigned long left,
 810                             char *type,
 811                             unsigned long *sizep,
 812                             struct packed_git *p)
 813{
 814        struct pack_entry base_ent;
 815
 816        if (left < 20)
 817                die("truncated pack file");
 818
 819        /* The base entry _must_ be in the same pack */
 820        if (!find_pack_entry_one(base_sha1, &base_ent, p))
 821                die("failed to find delta-pack base object %s",
 822                    sha1_to_hex(base_sha1));
 823
 824        /* We choose to only get the type of the base object and
 825         * ignore potentially corrupt pack file that expects the delta
 826         * based on a base with a wrong size.  This saves tons of
 827         * inflate() calls.
 828         */
 829
 830        if (packed_object_info(&base_ent, type, NULL))
 831                die("cannot get info for delta-pack base");
 832
 833        if (sizep) {
 834                const unsigned char *data;
 835                unsigned char delta_head[64];
 836                unsigned long result_size;
 837                z_stream stream;
 838                int st;
 839
 840                memset(&stream, 0, sizeof(stream));
 841
 842                data = stream.next_in = base_sha1 + 20;
 843                stream.avail_in = left - 20;
 844                stream.next_out = delta_head;
 845                stream.avail_out = sizeof(delta_head);
 846
 847                inflateInit(&stream);
 848                st = inflate(&stream, Z_FINISH);
 849                inflateEnd(&stream);
 850                if ((st != Z_STREAM_END) &&
 851                    stream.total_out != sizeof(delta_head))
 852                        die("delta data unpack-initial failed");
 853
 854                /* Examine the initial part of the delta to figure out
 855                 * the result size.
 856                 */
 857                data = delta_head;
 858
 859                /* ignore base size */
 860                get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
 861
 862                /* Read the result size */
 863                result_size = get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
 864                *sizep = result_size;
 865        }
 866        return 0;
 867}
 868
 869static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
 870        enum object_type *type, unsigned long *sizep)
 871{
 872        unsigned shift;
 873        unsigned char *pack, c;
 874        unsigned long size;
 875
 876        if (offset >= p->pack_size)
 877                die("object offset outside of pack file");
 878
 879        pack =  p->pack_base + offset;
 880        c = *pack++;
 881        offset++;
 882        *type = (c >> 4) & 7;
 883        size = c & 15;
 884        shift = 4;
 885        while (c & 0x80) {
 886                if (offset >= p->pack_size)
 887                        die("object offset outside of pack file");
 888                c = *pack++;
 889                offset++;
 890                size += (c & 0x7f) << shift;
 891                shift += 7;
 892        }
 893        *sizep = size;
 894        return offset;
 895}
 896
 897int check_reuse_pack_delta(struct packed_git *p, unsigned long offset,
 898                           unsigned char *base, unsigned long *sizep,
 899                           enum object_type *kindp)
 900{
 901        unsigned long ptr;
 902        int status = -1;
 903
 904        use_packed_git(p);
 905        ptr = offset;
 906        ptr = unpack_object_header(p, ptr, kindp, sizep);
 907        if (*kindp != OBJ_DELTA)
 908                goto done;
 909        memcpy(base, p->pack_base + ptr, 20);
 910        status = 0;
 911 done:
 912        unuse_packed_git(p);
 913        return status;
 914}
 915
 916void packed_object_info_detail(struct pack_entry *e,
 917                               char *type,
 918                               unsigned long *size,
 919                               unsigned long *store_size,
 920                               unsigned int *delta_chain_length,
 921                               unsigned char *base_sha1)
 922{
 923        struct packed_git *p = e->p;
 924        unsigned long offset;
 925        unsigned char *pack;
 926        enum object_type kind;
 927
 928        offset = unpack_object_header(p, e->offset, &kind, size);
 929        pack = p->pack_base + offset;
 930        if (kind != OBJ_DELTA)
 931                *delta_chain_length = 0;
 932        else {
 933                unsigned int chain_length = 0;
 934                if (p->pack_size <= offset + 20)
 935                        die("pack file %s records an incomplete delta base",
 936                            p->pack_name);
 937                memcpy(base_sha1, pack, 20);
 938                do {
 939                        struct pack_entry base_ent;
 940                        unsigned long junk;
 941
 942                        find_pack_entry_one(pack, &base_ent, p);
 943                        offset = unpack_object_header(p, base_ent.offset,
 944                                                      &kind, &junk);
 945                        pack = p->pack_base + offset;
 946                        chain_length++;
 947                } while (kind == OBJ_DELTA);
 948                *delta_chain_length = chain_length;
 949        }
 950        switch (kind) {
 951        case OBJ_COMMIT:
 952                strcpy(type, commit_type);
 953                break;
 954        case OBJ_TREE:
 955                strcpy(type, tree_type);
 956                break;
 957        case OBJ_BLOB:
 958                strcpy(type, blob_type);
 959                break;
 960        case OBJ_TAG:
 961                strcpy(type, tag_type);
 962                break;
 963        default:
 964                die("corrupted pack file %s containing object of kind %d",
 965                    p->pack_name, kind);
 966        }
 967        *store_size = 0; /* notyet */
 968}
 969
 970static int packed_object_info(struct pack_entry *entry,
 971                              char *type, unsigned long *sizep)
 972{
 973        struct packed_git *p = entry->p;
 974        unsigned long offset, size, left;
 975        unsigned char *pack;
 976        enum object_type kind;
 977        int retval;
 978
 979        if (use_packed_git(p))
 980                die("cannot map packed file");
 981
 982        offset = unpack_object_header(p, entry->offset, &kind, &size);
 983        pack = p->pack_base + offset;
 984        left = p->pack_size - offset;
 985
 986        switch (kind) {
 987        case OBJ_DELTA:
 988                retval = packed_delta_info(pack, size, left, type, sizep, p);
 989                unuse_packed_git(p);
 990                return retval;
 991        case OBJ_COMMIT:
 992                strcpy(type, commit_type);
 993                break;
 994        case OBJ_TREE:
 995                strcpy(type, tree_type);
 996                break;
 997        case OBJ_BLOB:
 998                strcpy(type, blob_type);
 999                break;
1000        case OBJ_TAG:
1001                strcpy(type, tag_type);
1002                break;
1003        default:
1004                die("corrupted pack file %s containing object of kind %d",
1005                    p->pack_name, kind);
1006        }
1007        if (sizep)
1008                *sizep = size;
1009        unuse_packed_git(p);
1010        return 0;
1011}
1012
1013/* forward declaration for a mutually recursive function */
1014static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
1015
1016static void *unpack_delta_entry(unsigned char *base_sha1,
1017                                unsigned long delta_size,
1018                                unsigned long left,
1019                                char *type,
1020                                unsigned long *sizep,
1021                                struct packed_git *p)
1022{
1023        struct pack_entry base_ent;
1024        void *data, *delta_data, *result, *base;
1025        unsigned long data_size, result_size, base_size;
1026        z_stream stream;
1027        int st;
1028
1029        if (left < 20)
1030                die("truncated pack file");
1031
1032        /* The base entry _must_ be in the same pack */
1033        if (!find_pack_entry_one(base_sha1, &base_ent, p))
1034                die("failed to find delta-pack base object %s",
1035                    sha1_to_hex(base_sha1));
1036        base = unpack_entry_gently(&base_ent, type, &base_size);
1037        if (!base)
1038                die("failed to read delta-pack base object %s",
1039                    sha1_to_hex(base_sha1));
1040
1041        data = base_sha1 + 20;
1042        data_size = left - 20;
1043        delta_data = xmalloc(delta_size);
1044
1045        memset(&stream, 0, sizeof(stream));
1046
1047        stream.next_in = data;
1048        stream.avail_in = data_size;
1049        stream.next_out = delta_data;
1050        stream.avail_out = delta_size;
1051
1052        inflateInit(&stream);
1053        st = inflate(&stream, Z_FINISH);
1054        inflateEnd(&stream);
1055        if ((st != Z_STREAM_END) || stream.total_out != delta_size)
1056                die("delta data unpack failed");
1057
1058        result = patch_delta(base, base_size,
1059                             delta_data, delta_size,
1060                             &result_size);
1061        if (!result)
1062                die("failed to apply delta");
1063        free(delta_data);
1064        free(base);
1065        *sizep = result_size;
1066        return result;
1067}
1068
1069static void *unpack_non_delta_entry(unsigned char *data,
1070                                    unsigned long size,
1071                                    unsigned long left)
1072{
1073        int st;
1074        z_stream stream;
1075        unsigned char *buffer;
1076
1077        buffer = xmalloc(size + 1);
1078        buffer[size] = 0;
1079        memset(&stream, 0, sizeof(stream));
1080        stream.next_in = data;
1081        stream.avail_in = left;
1082        stream.next_out = buffer;
1083        stream.avail_out = size;
1084
1085        inflateInit(&stream);
1086        st = inflate(&stream, Z_FINISH);
1087        inflateEnd(&stream);
1088        if ((st != Z_STREAM_END) || stream.total_out != size) {
1089                free(buffer);
1090                return NULL;
1091        }
1092
1093        return buffer;
1094}
1095
1096static void *unpack_entry(struct pack_entry *entry,
1097                          char *type, unsigned long *sizep)
1098{
1099        struct packed_git *p = entry->p;
1100        void *retval;
1101
1102        if (use_packed_git(p))
1103                die("cannot map packed file");
1104        retval = unpack_entry_gently(entry, type, sizep);
1105        unuse_packed_git(p);
1106        if (!retval)
1107                die("corrupted pack file %s", p->pack_name);
1108        return retval;
1109}
1110
1111/* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
1112void *unpack_entry_gently(struct pack_entry *entry,
1113                          char *type, unsigned long *sizep)
1114{
1115        struct packed_git *p = entry->p;
1116        unsigned long offset, size, left;
1117        unsigned char *pack;
1118        enum object_type kind;
1119        void *retval;
1120
1121        offset = unpack_object_header(p, entry->offset, &kind, &size);
1122        pack = p->pack_base + offset;
1123        left = p->pack_size - offset;
1124        switch (kind) {
1125        case OBJ_DELTA:
1126                retval = unpack_delta_entry(pack, size, left, type, sizep, p);
1127                return retval;
1128        case OBJ_COMMIT:
1129                strcpy(type, commit_type);
1130                break;
1131        case OBJ_TREE:
1132                strcpy(type, tree_type);
1133                break;
1134        case OBJ_BLOB:
1135                strcpy(type, blob_type);
1136                break;
1137        case OBJ_TAG:
1138                strcpy(type, tag_type);
1139                break;
1140        default:
1141                return NULL;
1142        }
1143        *sizep = size;
1144        retval = unpack_non_delta_entry(pack, size, left);
1145        return retval;
1146}
1147
1148int num_packed_objects(const struct packed_git *p)
1149{
1150        /* See check_packed_git_idx() */
1151        return (p->index_size - 20 - 20 - 4*256) / 24;
1152}
1153
1154int nth_packed_object_sha1(const struct packed_git *p, int n,
1155                           unsigned char* sha1)
1156{
1157        void *index = p->index_base + 256;
1158        if (n < 0 || num_packed_objects(p) <= n)
1159                return -1;
1160        memcpy(sha1, (index + 24 * n + 4), 20);
1161        return 0;
1162}
1163
1164int find_pack_entry_one(const unsigned char *sha1,
1165                        struct pack_entry *e, struct packed_git *p)
1166{
1167        unsigned int *level1_ofs = p->index_base;
1168        int hi = ntohl(level1_ofs[*sha1]);
1169        int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1170        void *index = p->index_base + 256;
1171
1172        do {
1173                int mi = (lo + hi) / 2;
1174                int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
1175                if (!cmp) {
1176                        e->offset = ntohl(*((unsigned int *)(index + 24 * mi)));
1177                        memcpy(e->sha1, sha1, 20);
1178                        e->p = p;
1179                        return 1;
1180                }
1181                if (cmp > 0)
1182                        hi = mi;
1183                else
1184                        lo = mi+1;
1185        } while (lo < hi);
1186        return 0;
1187}
1188
1189static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1190{
1191        struct packed_git *p;
1192        prepare_packed_git();
1193
1194        for (p = packed_git; p; p = p->next) {
1195                if (find_pack_entry_one(sha1, e, p))
1196                        return 1;
1197        }
1198        return 0;
1199}
1200
1201struct packed_git *find_sha1_pack(const unsigned char *sha1, 
1202                                  struct packed_git *packs)
1203{
1204        struct packed_git *p;
1205        struct pack_entry e;
1206
1207        for (p = packs; p; p = p->next) {
1208                if (find_pack_entry_one(sha1, &e, p))
1209                        return p;
1210        }
1211        return NULL;
1212        
1213}
1214
1215int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1216{
1217        int status;
1218        unsigned long mapsize, size;
1219        void *map;
1220        z_stream stream;
1221        char hdr[128];
1222
1223        map = map_sha1_file_internal(sha1, &mapsize);
1224        if (!map) {
1225                struct pack_entry e;
1226
1227                if (find_pack_entry(sha1, &e))
1228                        return packed_object_info(&e, type, sizep);
1229                reprepare_packed_git();
1230                if (find_pack_entry(sha1, &e))
1231                        return packed_object_info(&e, type, sizep);
1232                return error("unable to find %s", sha1_to_hex(sha1));
1233        }
1234        if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1235                status = error("unable to unpack %s header",
1236                               sha1_to_hex(sha1));
1237        if (parse_sha1_header(hdr, type, &size) < 0)
1238                status = error("unable to parse %s header", sha1_to_hex(sha1));
1239        else {
1240                status = 0;
1241                if (sizep)
1242                        *sizep = size;
1243        }
1244        inflateEnd(&stream);
1245        munmap(map, mapsize);
1246        return status;
1247}
1248
1249static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1250{
1251        struct pack_entry e;
1252
1253        if (!find_pack_entry(sha1, &e)) {
1254                error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1255                return NULL;
1256        }
1257        return unpack_entry(&e, type, size);
1258}
1259
1260void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1261{
1262        unsigned long mapsize;
1263        void *map, *buf;
1264        struct pack_entry e;
1265
1266        if (find_pack_entry(sha1, &e))
1267                return read_packed_sha1(sha1, type, size);
1268        map = map_sha1_file_internal(sha1, &mapsize);
1269        if (map) {
1270                buf = unpack_sha1_file(map, mapsize, type, size);
1271                munmap(map, mapsize);
1272                return buf;
1273        }
1274        reprepare_packed_git();
1275        if (find_pack_entry(sha1, &e))
1276                return read_packed_sha1(sha1, type, size);
1277        return NULL;
1278}
1279
1280void *read_object_with_reference(const unsigned char *sha1,
1281                                 const char *required_type,
1282                                 unsigned long *size,
1283                                 unsigned char *actual_sha1_return)
1284{
1285        char type[20];
1286        void *buffer;
1287        unsigned long isize;
1288        unsigned char actual_sha1[20];
1289
1290        memcpy(actual_sha1, sha1, 20);
1291        while (1) {
1292                int ref_length = -1;
1293                const char *ref_type = NULL;
1294
1295                buffer = read_sha1_file(actual_sha1, type, &isize);
1296                if (!buffer)
1297                        return NULL;
1298                if (!strcmp(type, required_type)) {
1299                        *size = isize;
1300                        if (actual_sha1_return)
1301                                memcpy(actual_sha1_return, actual_sha1, 20);
1302                        return buffer;
1303                }
1304                /* Handle references */
1305                else if (!strcmp(type, commit_type))
1306                        ref_type = "tree ";
1307                else if (!strcmp(type, tag_type))
1308                        ref_type = "object ";
1309                else {
1310                        free(buffer);
1311                        return NULL;
1312                }
1313                ref_length = strlen(ref_type);
1314
1315                if (memcmp(buffer, ref_type, ref_length) ||
1316                    get_sha1_hex(buffer + ref_length, actual_sha1)) {
1317                        free(buffer);
1318                        return NULL;
1319                }
1320                free(buffer);
1321                /* Now we have the ID of the referred-to object in
1322                 * actual_sha1.  Check again. */
1323        }
1324}
1325
1326char *write_sha1_file_prepare(void *buf,
1327                              unsigned long len,
1328                              const char *type,
1329                              unsigned char *sha1,
1330                              unsigned char *hdr,
1331                              int *hdrlen)
1332{
1333        SHA_CTX c;
1334
1335        /* Generate the header */
1336        *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1337
1338        /* Sha1.. */
1339        SHA1_Init(&c);
1340        SHA1_Update(&c, hdr, *hdrlen);
1341        SHA1_Update(&c, buf, len);
1342        SHA1_Final(sha1, &c);
1343
1344        return sha1_file_name(sha1);
1345}
1346
1347/*
1348 * Link the tempfile to the final place, possibly creating the
1349 * last directory level as you do so.
1350 *
1351 * Returns the errno on failure, 0 on success.
1352 */
1353static int link_temp_to_file(const char *tmpfile, char *filename)
1354{
1355        int ret;
1356
1357        if (!link(tmpfile, filename))
1358                return 0;
1359
1360        /*
1361         * Try to mkdir the last path component if that failed
1362         * with an ENOENT.
1363         *
1364         * Re-try the "link()" regardless of whether the mkdir
1365         * succeeds, since a race might mean that somebody
1366         * else succeeded.
1367         */
1368        ret = errno;
1369        if (ret == ENOENT) {
1370                char *dir = strrchr(filename, '/');
1371                if (dir) {
1372                        *dir = 0;
1373                        mkdir(filename, 0777);
1374                        if (adjust_shared_perm(filename))
1375                                return -2;
1376                        *dir = '/';
1377                        if (!link(tmpfile, filename))
1378                                return 0;
1379                        ret = errno;
1380                }
1381        }
1382        return ret;
1383}
1384
1385/*
1386 * Move the just written object into its final resting place
1387 */
1388int move_temp_to_file(const char *tmpfile, char *filename)
1389{
1390        int ret = link_temp_to_file(tmpfile, filename);
1391
1392        /*
1393         * Coda hack - coda doesn't like cross-directory links,
1394         * so we fall back to a rename, which will mean that it
1395         * won't be able to check collisions, but that's not a
1396         * big deal.
1397         *
1398         * The same holds for FAT formatted media.
1399         *
1400         * When this succeeds, we just return 0. We have nothing
1401         * left to unlink.
1402         */
1403        if (ret && ret != EEXIST) {
1404                if (!rename(tmpfile, filename))
1405                        return 0;
1406                ret = errno;
1407        }
1408        unlink(tmpfile);
1409        if (ret) {
1410                if (ret != EEXIST) {
1411                        fprintf(stderr, "unable to write sha1 filename %s: %s\n", filename, strerror(ret));
1412                        return -1;
1413                }
1414                /* FIXME!!! Collision check here ? */
1415        }
1416
1417        return 0;
1418}
1419
1420static int write_buffer(int fd, const void *buf, size_t len)
1421{
1422        while (len) {
1423                ssize_t size;
1424
1425                size = write(fd, buf, len);
1426                if (!size)
1427                        return error("file write: disk full");
1428                if (size < 0) {
1429                        if (errno == EINTR || errno == EAGAIN)
1430                                continue;
1431                        return error("file write error (%s)", strerror(errno));
1432                }
1433                len -= size;
1434                buf += size;
1435        }
1436        return 0;
1437}
1438
1439int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1440{
1441        int size;
1442        unsigned char *compressed;
1443        z_stream stream;
1444        unsigned char sha1[20];
1445        char *filename;
1446        static char tmpfile[PATH_MAX];
1447        unsigned char hdr[50];
1448        int fd, hdrlen;
1449
1450        /* Normally if we have it in the pack then we do not bother writing
1451         * it out into .git/objects/??/?{38} file.
1452         */
1453        filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1454        if (returnsha1)
1455                memcpy(returnsha1, sha1, 20);
1456        if (has_sha1_file(sha1))
1457                return 0;
1458        fd = open(filename, O_RDONLY);
1459        if (fd >= 0) {
1460                /*
1461                 * FIXME!!! We might do collision checking here, but we'd
1462                 * need to uncompress the old file and check it. Later.
1463                 */
1464                close(fd);
1465                return 0;
1466        }
1467
1468        if (errno != ENOENT) {
1469                fprintf(stderr, "sha1 file %s: %s\n", filename, strerror(errno));
1470                return -1;
1471        }
1472
1473        snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1474
1475        fd = mkstemp(tmpfile);
1476        if (fd < 0) {
1477                fprintf(stderr, "unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
1478                return -1;
1479        }
1480
1481        /* Set it up */
1482        memset(&stream, 0, sizeof(stream));
1483        deflateInit(&stream, Z_BEST_COMPRESSION);
1484        size = deflateBound(&stream, len+hdrlen);
1485        compressed = xmalloc(size);
1486
1487        /* Compress it */
1488        stream.next_out = compressed;
1489        stream.avail_out = size;
1490
1491        /* First header.. */
1492        stream.next_in = hdr;
1493        stream.avail_in = hdrlen;
1494        while (deflate(&stream, 0) == Z_OK)
1495                /* nothing */;
1496
1497        /* Then the data itself.. */
1498        stream.next_in = buf;
1499        stream.avail_in = len;
1500        while (deflate(&stream, Z_FINISH) == Z_OK)
1501                /* nothing */;
1502        deflateEnd(&stream);
1503        size = stream.total_out;
1504
1505        if (write_buffer(fd, compressed, size) < 0)
1506                die("unable to write sha1 file");
1507        fchmod(fd, 0444);
1508        close(fd);
1509        free(compressed);
1510
1511        return move_temp_to_file(tmpfile, filename);
1512}
1513
1514/*
1515 * We need to unpack and recompress the object for writing
1516 * it out to a different file.
1517 */
1518static void *repack_object(const unsigned char *sha1, unsigned long *objsize)
1519{
1520        size_t size;
1521        z_stream stream;
1522        unsigned char *unpacked;
1523        unsigned long len;
1524        char type[20];
1525        char hdr[50];
1526        int hdrlen;
1527        void *buf;
1528
1529        // need to unpack and recompress it by itself
1530        unpacked = read_packed_sha1(sha1, type, &len);
1531
1532        hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1533
1534        /* Set it up */
1535        memset(&stream, 0, sizeof(stream));
1536        deflateInit(&stream, Z_BEST_COMPRESSION);
1537        size = deflateBound(&stream, len + hdrlen);
1538        buf = xmalloc(size);
1539
1540        /* Compress it */
1541        stream.next_out = buf;
1542        stream.avail_out = size;
1543
1544        /* First header.. */
1545        stream.next_in = (void *)hdr;
1546        stream.avail_in = hdrlen;
1547        while (deflate(&stream, 0) == Z_OK)
1548                /* nothing */;
1549
1550        /* Then the data itself.. */
1551        stream.next_in = unpacked;
1552        stream.avail_in = len;
1553        while (deflate(&stream, Z_FINISH) == Z_OK)
1554                /* nothing */;
1555        deflateEnd(&stream);
1556        free(unpacked);
1557
1558        *objsize = stream.total_out;
1559        return buf;
1560}
1561
1562int write_sha1_to_fd(int fd, const unsigned char *sha1)
1563{
1564        int retval;
1565        unsigned long objsize;
1566        void *buf = map_sha1_file_internal(sha1, &objsize);
1567
1568        if (buf) {
1569                retval = write_buffer(fd, buf, objsize);
1570                munmap(buf, objsize);
1571                return retval;
1572        }
1573
1574        buf = repack_object(sha1, &objsize);
1575        retval = write_buffer(fd, buf, objsize);
1576        free(buf);
1577        return retval;
1578}
1579
1580int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1581                       size_t bufsize, size_t *bufposn)
1582{
1583        char tmpfile[PATH_MAX];
1584        int local;
1585        z_stream stream;
1586        unsigned char real_sha1[20];
1587        unsigned char discard[4096];
1588        int ret;
1589        SHA_CTX c;
1590
1591        snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1592
1593        local = mkstemp(tmpfile);
1594        if (local < 0)
1595                return error("Couldn't open %s for %s",
1596                             tmpfile, sha1_to_hex(sha1));
1597
1598        memset(&stream, 0, sizeof(stream));
1599
1600        inflateInit(&stream);
1601
1602        SHA1_Init(&c);
1603
1604        do {
1605                ssize_t size;
1606                if (*bufposn) {
1607                        stream.avail_in = *bufposn;
1608                        stream.next_in = (unsigned char *) buffer;
1609                        do {
1610                                stream.next_out = discard;
1611                                stream.avail_out = sizeof(discard);
1612                                ret = inflate(&stream, Z_SYNC_FLUSH);
1613                                SHA1_Update(&c, discard, sizeof(discard) -
1614                                            stream.avail_out);
1615                        } while (stream.avail_in && ret == Z_OK);
1616                        if (write_buffer(local, buffer, *bufposn - stream.avail_in) < 0)
1617                                die("unable to write sha1 file");
1618                        memmove(buffer, buffer + *bufposn - stream.avail_in,
1619                                stream.avail_in);
1620                        *bufposn = stream.avail_in;
1621                        if (ret != Z_OK)
1622                                break;
1623                }
1624                size = read(fd, buffer + *bufposn, bufsize - *bufposn);
1625                if (size <= 0) {
1626                        close(local);
1627                        unlink(tmpfile);
1628                        if (!size)
1629                                return error("Connection closed?");
1630                        perror("Reading from connection");
1631                        return -1;
1632                }
1633                *bufposn += size;
1634        } while (1);
1635        inflateEnd(&stream);
1636
1637        close(local);
1638        SHA1_Final(real_sha1, &c);
1639        if (ret != Z_STREAM_END) {
1640                unlink(tmpfile);
1641                return error("File %s corrupted", sha1_to_hex(sha1));
1642        }
1643        if (memcmp(sha1, real_sha1, 20)) {
1644                unlink(tmpfile);
1645                return error("File %s has bad hash", sha1_to_hex(sha1));
1646        }
1647
1648        return move_temp_to_file(tmpfile, sha1_file_name(sha1));
1649}
1650
1651int has_pack_index(const unsigned char *sha1)
1652{
1653        struct stat st;
1654        if (stat(sha1_pack_index_name(sha1), &st))
1655                return 0;
1656        return 1;
1657}
1658
1659int has_pack_file(const unsigned char *sha1)
1660{
1661        struct stat st;
1662        if (stat(sha1_pack_name(sha1), &st))
1663                return 0;
1664        return 1;
1665}
1666
1667int has_sha1_pack(const unsigned char *sha1)
1668{
1669        struct pack_entry e;
1670        return find_pack_entry(sha1, &e);
1671}
1672
1673int has_sha1_file(const unsigned char *sha1)
1674{
1675        struct stat st;
1676        struct pack_entry e;
1677
1678        if (find_pack_entry(sha1, &e))
1679                return 1;
1680        return find_sha1_file(sha1, &st) ? 1 : 0;
1681}
1682
1683/*
1684 * reads from fd as long as possible into a supplied buffer of size bytes.
1685 * If neccessary the buffer's size is increased using realloc()
1686 *
1687 * returns 0 if anything went fine and -1 otherwise
1688 *
1689 * NOTE: both buf and size may change, but even when -1 is returned
1690 * you still have to free() it yourself.
1691 */
1692int read_pipe(int fd, char** return_buf, unsigned long* return_size)
1693{
1694        char* buf = *return_buf;
1695        unsigned long size = *return_size;
1696        int iret;
1697        unsigned long off = 0;
1698
1699        do {
1700                iret = xread(fd, buf + off, size - off);
1701                if (iret > 0) {
1702                        off += iret;
1703                        if (off == size) {
1704                                size *= 2;
1705                                buf = realloc(buf, size);
1706                        }
1707                }
1708        } while (iret > 0);
1709
1710        *return_buf = buf;
1711        *return_size = off;
1712
1713        if (iret < 0)
1714                return -1;
1715        return 0;
1716}
1717
1718int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
1719{
1720        unsigned long size = 4096;
1721        char *buf = malloc(size);
1722        int ret;
1723        unsigned char hdr[50];
1724        int hdrlen;
1725
1726        if (read_pipe(fd, &buf, &size)) {
1727                free(buf);
1728                return -1;
1729        }
1730
1731        if (!type)
1732                type = blob_type;
1733        if (write_object)
1734                ret = write_sha1_file(buf, size, type, sha1);
1735        else {
1736                write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1737                ret = 0;
1738        }
1739        free(buf);
1740        return ret;
1741}
1742
1743int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1744{
1745        unsigned long size = st->st_size;
1746        void *buf;
1747        int ret;
1748        unsigned char hdr[50];
1749        int hdrlen;
1750
1751        buf = "";
1752        if (size)
1753                buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1754        close(fd);
1755        if (buf == MAP_FAILED)
1756                return -1;
1757
1758        if (!type)
1759                type = blob_type;
1760        if (write_object)
1761                ret = write_sha1_file(buf, size, type, sha1);
1762        else {
1763                write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1764                ret = 0;
1765        }
1766        if (size)
1767                munmap(buf, size);
1768        return ret;
1769}
1770
1771int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1772{
1773        int fd;
1774        char *target;
1775
1776        switch (st->st_mode & S_IFMT) {
1777        case S_IFREG:
1778                fd = open(path, O_RDONLY);
1779                if (fd < 0)
1780                        return error("open(\"%s\"): %s", path,
1781                                     strerror(errno));
1782                if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1783                        return error("%s: failed to insert into database",
1784                                     path);
1785                break;
1786        case S_IFLNK:
1787                target = xmalloc(st->st_size+1);
1788                if (readlink(path, target, st->st_size+1) != st->st_size) {
1789                        char *errstr = strerror(errno);
1790                        free(target);
1791                        return error("readlink(\"%s\"): %s", path,
1792                                     errstr);
1793                }
1794                if (!write_object) {
1795                        unsigned char hdr[50];
1796                        int hdrlen;
1797                        write_sha1_file_prepare(target, st->st_size, blob_type,
1798                                                sha1, hdr, &hdrlen);
1799                } else if (write_sha1_file(target, st->st_size, blob_type, sha1))
1800                        return error("%s: failed to insert into database",
1801                                     path);
1802                free(target);
1803                break;
1804        default:
1805                return error("%s: unsupported file type", path);
1806        }
1807        return 0;
1808}