index-pack.con commit don't ever allow SHA1 collisions to exist by fetching a pack (8685da4)
   1#include "cache.h"
   2#include "delta.h"
   3#include "pack.h"
   4#include "csum-file.h"
   5#include "blob.h"
   6#include "commit.h"
   7#include "tag.h"
   8#include "tree.h"
   9
  10static const char index_pack_usage[] =
  11"git-index-pack [-v] [-o <index-file>] [{ ---keep | --keep=<msg> }] { <pack-file> | --stdin [--fix-thin] [<pack-file>] }";
  12
  13struct object_entry
  14{
  15        unsigned long offset;
  16        unsigned long size;
  17        unsigned int hdr_size;
  18        enum object_type type;
  19        enum object_type real_type;
  20        unsigned char sha1[20];
  21};
  22
  23union delta_base {
  24        unsigned char sha1[20];
  25        unsigned long offset;
  26};
  27
  28/*
  29 * Even if sizeof(union delta_base) == 24 on 64-bit archs, we really want
  30 * to memcmp() only the first 20 bytes.
  31 */
  32#define UNION_BASE_SZ   20
  33
  34struct delta_entry
  35{
  36        union delta_base base;
  37        int obj_no;
  38};
  39
  40static struct object_entry *objects;
  41static struct delta_entry *deltas;
  42static int nr_objects;
  43static int nr_deltas;
  44static int nr_resolved_deltas;
  45
  46static int from_stdin;
  47static int verbose;
  48
  49static volatile sig_atomic_t progress_update;
  50
  51static void progress_interval(int signum)
  52{
  53        progress_update = 1;
  54}
  55
  56static void setup_progress_signal(void)
  57{
  58        struct sigaction sa;
  59        struct itimerval v;
  60
  61        memset(&sa, 0, sizeof(sa));
  62        sa.sa_handler = progress_interval;
  63        sigemptyset(&sa.sa_mask);
  64        sa.sa_flags = SA_RESTART;
  65        sigaction(SIGALRM, &sa, NULL);
  66
  67        v.it_interval.tv_sec = 1;
  68        v.it_interval.tv_usec = 0;
  69        v.it_value = v.it_interval;
  70        setitimer(ITIMER_REAL, &v, NULL);
  71
  72}
  73
  74static unsigned display_progress(unsigned n, unsigned total, unsigned last_pc)
  75{
  76        unsigned percent = n * 100 / total;
  77        if (percent != last_pc || progress_update) {
  78                fprintf(stderr, "%4u%% (%u/%u) done\r", percent, n, total);
  79                progress_update = 0;
  80        }
  81        return percent;
  82}
  83
  84/* We always read in 4kB chunks. */
  85static unsigned char input_buffer[4096];
  86static unsigned long input_offset, input_len, consumed_bytes;
  87static SHA_CTX input_ctx;
  88static int input_fd, output_fd, pack_fd;
  89
  90/* Discard current buffer used content. */
  91static void flush(void)
  92{
  93        if (input_offset) {
  94                if (output_fd >= 0)
  95                        write_or_die(output_fd, input_buffer, input_offset);
  96                SHA1_Update(&input_ctx, input_buffer, input_offset);
  97                memmove(input_buffer, input_buffer + input_offset, input_len);
  98                input_offset = 0;
  99        }
 100}
 101
 102/*
 103 * Make sure at least "min" bytes are available in the buffer, and
 104 * return the pointer to the buffer.
 105 */
 106static void *fill(int min)
 107{
 108        if (min <= input_len)
 109                return input_buffer + input_offset;
 110        if (min > sizeof(input_buffer))
 111                die("cannot fill %d bytes", min);
 112        flush();
 113        do {
 114                int ret = xread(input_fd, input_buffer + input_len,
 115                                sizeof(input_buffer) - input_len);
 116                if (ret <= 0) {
 117                        if (!ret)
 118                                die("early EOF");
 119                        die("read error on input: %s", strerror(errno));
 120                }
 121                input_len += ret;
 122        } while (input_len < min);
 123        return input_buffer;
 124}
 125
 126static void use(int bytes)
 127{
 128        if (bytes > input_len)
 129                die("used more bytes than were available");
 130        input_len -= bytes;
 131        input_offset += bytes;
 132        consumed_bytes += bytes;
 133}
 134
 135static const char *open_pack_file(const char *pack_name)
 136{
 137        if (from_stdin) {
 138                input_fd = 0;
 139                if (!pack_name) {
 140                        static char tmpfile[PATH_MAX];
 141                        snprintf(tmpfile, sizeof(tmpfile),
 142                                 "%s/pack_XXXXXX", get_object_directory());
 143                        output_fd = mkstemp(tmpfile);
 144                        pack_name = xstrdup(tmpfile);
 145                } else
 146                        output_fd = open(pack_name, O_CREAT|O_EXCL|O_RDWR, 0600);
 147                if (output_fd < 0)
 148                        die("unable to create %s: %s\n", pack_name, strerror(errno));
 149                pack_fd = output_fd;
 150        } else {
 151                input_fd = open(pack_name, O_RDONLY);
 152                if (input_fd < 0)
 153                        die("cannot open packfile '%s': %s",
 154                            pack_name, strerror(errno));
 155                output_fd = -1;
 156                pack_fd = input_fd;
 157        }
 158        SHA1_Init(&input_ctx);
 159        return pack_name;
 160}
 161
 162static void parse_pack_header(void)
 163{
 164        struct pack_header *hdr = fill(sizeof(struct pack_header));
 165
 166        /* Header consistency check */
 167        if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
 168                die("pack signature mismatch");
 169        if (!pack_version_ok(hdr->hdr_version))
 170                die("pack version %d unsupported", ntohl(hdr->hdr_version));
 171
 172        nr_objects = ntohl(hdr->hdr_entries);
 173        use(sizeof(struct pack_header));
 174}
 175
 176static void bad_object(unsigned long offset, const char *format,
 177                       ...) NORETURN __attribute__((format (printf, 2, 3)));
 178
 179static void bad_object(unsigned long offset, const char *format, ...)
 180{
 181        va_list params;
 182        char buf[1024];
 183
 184        va_start(params, format);
 185        vsnprintf(buf, sizeof(buf), format, params);
 186        va_end(params);
 187        die("pack has bad object at offset %lu: %s", offset, buf);
 188}
 189
 190static void *unpack_entry_data(unsigned long offset, unsigned long size)
 191{
 192        z_stream stream;
 193        void *buf = xmalloc(size);
 194
 195        memset(&stream, 0, sizeof(stream));
 196        stream.next_out = buf;
 197        stream.avail_out = size;
 198        stream.next_in = fill(1);
 199        stream.avail_in = input_len;
 200        inflateInit(&stream);
 201
 202        for (;;) {
 203                int ret = inflate(&stream, 0);
 204                use(input_len - stream.avail_in);
 205                if (stream.total_out == size && ret == Z_STREAM_END)
 206                        break;
 207                if (ret != Z_OK)
 208                        bad_object(offset, "inflate returned %d", ret);
 209                stream.next_in = fill(1);
 210                stream.avail_in = input_len;
 211        }
 212        inflateEnd(&stream);
 213        return buf;
 214}
 215
 216static void *unpack_raw_entry(struct object_entry *obj, union delta_base *delta_base)
 217{
 218        unsigned char *p, c;
 219        unsigned long size, base_offset;
 220        unsigned shift;
 221
 222        obj->offset = consumed_bytes;
 223
 224        p = fill(1);
 225        c = *p;
 226        use(1);
 227        obj->type = (c >> 4) & 7;
 228        size = (c & 15);
 229        shift = 4;
 230        while (c & 0x80) {
 231                p = fill(1);
 232                c = *p;
 233                use(1);
 234                size += (c & 0x7fUL) << shift;
 235                shift += 7;
 236        }
 237        obj->size = size;
 238
 239        switch (obj->type) {
 240        case OBJ_REF_DELTA:
 241                hashcpy(delta_base->sha1, fill(20));
 242                use(20);
 243                break;
 244        case OBJ_OFS_DELTA:
 245                memset(delta_base, 0, sizeof(*delta_base));
 246                p = fill(1);
 247                c = *p;
 248                use(1);
 249                base_offset = c & 127;
 250                while (c & 128) {
 251                        base_offset += 1;
 252                        if (!base_offset || base_offset & ~(~0UL >> 7))
 253                                bad_object(obj->offset, "offset value overflow for delta base object");
 254                        p = fill(1);
 255                        c = *p;
 256                        use(1);
 257                        base_offset = (base_offset << 7) + (c & 127);
 258                }
 259                delta_base->offset = obj->offset - base_offset;
 260                if (delta_base->offset >= obj->offset)
 261                        bad_object(obj->offset, "delta base offset is out of bound");
 262                break;
 263        case OBJ_COMMIT:
 264        case OBJ_TREE:
 265        case OBJ_BLOB:
 266        case OBJ_TAG:
 267                break;
 268        default:
 269                bad_object(obj->offset, "unknown object type %d", obj->type);
 270        }
 271        obj->hdr_size = consumed_bytes - obj->offset;
 272
 273        return unpack_entry_data(obj->offset, obj->size);
 274}
 275
 276static void *get_data_from_pack(struct object_entry *obj)
 277{
 278        unsigned long from = obj[0].offset + obj[0].hdr_size;
 279        unsigned long len = obj[1].offset - from;
 280        unsigned long rdy = 0;
 281        unsigned char *src, *data;
 282        z_stream stream;
 283        int st;
 284
 285        src = xmalloc(len);
 286        data = src;
 287        do {
 288                ssize_t n = pread(pack_fd, data + rdy, len - rdy, from + rdy);
 289                if (n <= 0)
 290                        die("cannot pread pack file: %s", strerror(errno));
 291                rdy += n;
 292        } while (rdy < len);
 293        data = xmalloc(obj->size);
 294        memset(&stream, 0, sizeof(stream));
 295        stream.next_out = data;
 296        stream.avail_out = obj->size;
 297        stream.next_in = src;
 298        stream.avail_in = len;
 299        inflateInit(&stream);
 300        while ((st = inflate(&stream, Z_FINISH)) == Z_OK);
 301        inflateEnd(&stream);
 302        if (st != Z_STREAM_END || stream.total_out != obj->size)
 303                die("serious inflate inconsistency");
 304        free(src);
 305        return data;
 306}
 307
 308static int find_delta(const union delta_base *base)
 309{
 310        int first = 0, last = nr_deltas;
 311
 312        while (first < last) {
 313                int next = (first + last) / 2;
 314                struct delta_entry *delta = &deltas[next];
 315                int cmp;
 316
 317                cmp = memcmp(base, &delta->base, UNION_BASE_SZ);
 318                if (!cmp)
 319                        return next;
 320                if (cmp < 0) {
 321                        last = next;
 322                        continue;
 323                }
 324                first = next+1;
 325        }
 326        return -first-1;
 327}
 328
 329static int find_delta_children(const union delta_base *base,
 330                               int *first_index, int *last_index)
 331{
 332        int first = find_delta(base);
 333        int last = first;
 334        int end = nr_deltas - 1;
 335
 336        if (first < 0)
 337                return -1;
 338        while (first > 0 && !memcmp(&deltas[first - 1].base, base, UNION_BASE_SZ))
 339                --first;
 340        while (last < end && !memcmp(&deltas[last + 1].base, base, UNION_BASE_SZ))
 341                ++last;
 342        *first_index = first;
 343        *last_index = last;
 344        return 0;
 345}
 346
 347static void sha1_object(const void *data, unsigned long size,
 348                        enum object_type type, unsigned char *sha1,
 349                        int test_for_collision)
 350{
 351        SHA_CTX ctx;
 352        char header[50];
 353        int header_size;
 354        const char *type_str;
 355
 356        switch (type) {
 357        case OBJ_COMMIT: type_str = commit_type; break;
 358        case OBJ_TREE:   type_str = tree_type; break;
 359        case OBJ_BLOB:   type_str = blob_type; break;
 360        case OBJ_TAG:    type_str = tag_type; break;
 361        default:
 362                die("bad type %d", type);
 363        }
 364
 365        header_size = sprintf(header, "%s %lu", type_str, size) + 1;
 366
 367        SHA1_Init(&ctx);
 368        SHA1_Update(&ctx, header, header_size);
 369        SHA1_Update(&ctx, data, size);
 370        SHA1_Final(sha1, &ctx);
 371
 372        if (test_for_collision && has_sha1_file(sha1)) {
 373                void *has_data;
 374                enum object_type has_type;
 375                unsigned long has_size;
 376                has_data = read_sha1_file(sha1, &has_type, &has_size);
 377                if (!has_data)
 378                        die("cannot read existing object %s", sha1_to_hex(sha1));
 379                if (size != has_size || type != has_type ||
 380                    memcmp(data, has_data, size) != 0)
 381                        die("SHA1 COLLISION FOUND WITH %s !", sha1_to_hex(sha1));
 382        }
 383}
 384
 385static void resolve_delta(struct object_entry *delta_obj, void *base_data,
 386                          unsigned long base_size, enum object_type type)
 387{
 388        void *delta_data;
 389        unsigned long delta_size;
 390        void *result;
 391        unsigned long result_size;
 392        union delta_base delta_base;
 393        int j, first, last;
 394
 395        delta_obj->real_type = type;
 396        delta_data = get_data_from_pack(delta_obj);
 397        delta_size = delta_obj->size;
 398        result = patch_delta(base_data, base_size, delta_data, delta_size,
 399                             &result_size);
 400        free(delta_data);
 401        if (!result)
 402                bad_object(delta_obj->offset, "failed to apply delta");
 403        sha1_object(result, result_size, type, delta_obj->sha1, 1);
 404        nr_resolved_deltas++;
 405
 406        hashcpy(delta_base.sha1, delta_obj->sha1);
 407        if (!find_delta_children(&delta_base, &first, &last)) {
 408                for (j = first; j <= last; j++) {
 409                        struct object_entry *child = objects + deltas[j].obj_no;
 410                        if (child->real_type == OBJ_REF_DELTA)
 411                                resolve_delta(child, result, result_size, type);
 412                }
 413        }
 414
 415        memset(&delta_base, 0, sizeof(delta_base));
 416        delta_base.offset = delta_obj->offset;
 417        if (!find_delta_children(&delta_base, &first, &last)) {
 418                for (j = first; j <= last; j++) {
 419                        struct object_entry *child = objects + deltas[j].obj_no;
 420                        if (child->real_type == OBJ_OFS_DELTA)
 421                                resolve_delta(child, result, result_size, type);
 422                }
 423        }
 424
 425        free(result);
 426}
 427
 428static int compare_delta_entry(const void *a, const void *b)
 429{
 430        const struct delta_entry *delta_a = a;
 431        const struct delta_entry *delta_b = b;
 432        return memcmp(&delta_a->base, &delta_b->base, UNION_BASE_SZ);
 433}
 434
 435/* Parse all objects and return the pack content SHA1 hash */
 436static void parse_pack_objects(unsigned char *sha1)
 437{
 438        int i, percent = -1;
 439        struct delta_entry *delta = deltas;
 440        void *data;
 441        struct stat st;
 442
 443        /*
 444         * First pass:
 445         * - find locations of all objects;
 446         * - calculate SHA1 of all non-delta objects;
 447         * - remember base (SHA1 or offset) for all deltas.
 448         */
 449        if (verbose)
 450                fprintf(stderr, "Indexing %d objects.\n", nr_objects);
 451        for (i = 0; i < nr_objects; i++) {
 452                struct object_entry *obj = &objects[i];
 453                data = unpack_raw_entry(obj, &delta->base);
 454                obj->real_type = obj->type;
 455                if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA) {
 456                        nr_deltas++;
 457                        delta->obj_no = i;
 458                        delta++;
 459                } else
 460                        sha1_object(data, obj->size, obj->type, obj->sha1, 1);
 461                free(data);
 462                if (verbose)
 463                        percent = display_progress(i+1, nr_objects, percent);
 464        }
 465        objects[i].offset = consumed_bytes;
 466        if (verbose)
 467                fputc('\n', stderr);
 468
 469        /* Check pack integrity */
 470        flush();
 471        SHA1_Final(sha1, &input_ctx);
 472        if (hashcmp(fill(20), sha1))
 473                die("pack is corrupted (SHA1 mismatch)");
 474        use(20);
 475
 476        /* If input_fd is a file, we should have reached its end now. */
 477        if (fstat(input_fd, &st))
 478                die("cannot fstat packfile: %s", strerror(errno));
 479        if (S_ISREG(st.st_mode) &&
 480                        lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
 481                die("pack has junk at the end");
 482
 483        if (!nr_deltas)
 484                return;
 485
 486        /* Sort deltas by base SHA1/offset for fast searching */
 487        qsort(deltas, nr_deltas, sizeof(struct delta_entry),
 488              compare_delta_entry);
 489
 490        /*
 491         * Second pass:
 492         * - for all non-delta objects, look if it is used as a base for
 493         *   deltas;
 494         * - if used as a base, uncompress the object and apply all deltas,
 495         *   recursively checking if the resulting object is used as a base
 496         *   for some more deltas.
 497         */
 498        if (verbose)
 499                fprintf(stderr, "Resolving %d deltas.\n", nr_deltas);
 500        for (i = 0; i < nr_objects; i++) {
 501                struct object_entry *obj = &objects[i];
 502                union delta_base base;
 503                int j, ref, ref_first, ref_last, ofs, ofs_first, ofs_last;
 504
 505                if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA)
 506                        continue;
 507                hashcpy(base.sha1, obj->sha1);
 508                ref = !find_delta_children(&base, &ref_first, &ref_last);
 509                memset(&base, 0, sizeof(base));
 510                base.offset = obj->offset;
 511                ofs = !find_delta_children(&base, &ofs_first, &ofs_last);
 512                if (!ref && !ofs)
 513                        continue;
 514                data = get_data_from_pack(obj);
 515                if (ref)
 516                        for (j = ref_first; j <= ref_last; j++) {
 517                                struct object_entry *child = objects + deltas[j].obj_no;
 518                                if (child->real_type == OBJ_REF_DELTA)
 519                                        resolve_delta(child, data,
 520                                                      obj->size, obj->type);
 521                        }
 522                if (ofs)
 523                        for (j = ofs_first; j <= ofs_last; j++) {
 524                                struct object_entry *child = objects + deltas[j].obj_no;
 525                                if (child->real_type == OBJ_OFS_DELTA)
 526                                        resolve_delta(child, data,
 527                                                      obj->size, obj->type);
 528                        }
 529                free(data);
 530                if (verbose)
 531                        percent = display_progress(nr_resolved_deltas,
 532                                                   nr_deltas, percent);
 533        }
 534        if (verbose && nr_resolved_deltas == nr_deltas)
 535                fputc('\n', stderr);
 536}
 537
 538static int write_compressed(int fd, void *in, unsigned int size)
 539{
 540        z_stream stream;
 541        unsigned long maxsize;
 542        void *out;
 543
 544        memset(&stream, 0, sizeof(stream));
 545        deflateInit(&stream, zlib_compression_level);
 546        maxsize = deflateBound(&stream, size);
 547        out = xmalloc(maxsize);
 548
 549        /* Compress it */
 550        stream.next_in = in;
 551        stream.avail_in = size;
 552        stream.next_out = out;
 553        stream.avail_out = maxsize;
 554        while (deflate(&stream, Z_FINISH) == Z_OK);
 555        deflateEnd(&stream);
 556
 557        size = stream.total_out;
 558        write_or_die(fd, out, size);
 559        free(out);
 560        return size;
 561}
 562
 563static void append_obj_to_pack(void *buf,
 564                               unsigned long size, enum object_type type)
 565{
 566        struct object_entry *obj = &objects[nr_objects++];
 567        unsigned char header[10];
 568        unsigned long s = size;
 569        int n = 0;
 570        unsigned char c = (type << 4) | (s & 15);
 571        s >>= 4;
 572        while (s) {
 573                header[n++] = c | 0x80;
 574                c = s & 0x7f;
 575                s >>= 7;
 576        }
 577        header[n++] = c;
 578        write_or_die(output_fd, header, n);
 579        obj[1].offset = obj[0].offset + n;
 580        obj[1].offset += write_compressed(output_fd, buf, size);
 581        sha1_object(buf, size, type, obj->sha1, 0);
 582}
 583
 584static int delta_pos_compare(const void *_a, const void *_b)
 585{
 586        struct delta_entry *a = *(struct delta_entry **)_a;
 587        struct delta_entry *b = *(struct delta_entry **)_b;
 588        return a->obj_no - b->obj_no;
 589}
 590
 591static void fix_unresolved_deltas(int nr_unresolved)
 592{
 593        struct delta_entry **sorted_by_pos;
 594        int i, n = 0, percent = -1;
 595
 596        /*
 597         * Since many unresolved deltas may well be themselves base objects
 598         * for more unresolved deltas, we really want to include the
 599         * smallest number of base objects that would cover as much delta
 600         * as possible by picking the
 601         * trunc deltas first, allowing for other deltas to resolve without
 602         * additional base objects.  Since most base objects are to be found
 603         * before deltas depending on them, a good heuristic is to start
 604         * resolving deltas in the same order as their position in the pack.
 605         */
 606        sorted_by_pos = xmalloc(nr_unresolved * sizeof(*sorted_by_pos));
 607        for (i = 0; i < nr_deltas; i++) {
 608                if (objects[deltas[i].obj_no].real_type != OBJ_REF_DELTA)
 609                        continue;
 610                sorted_by_pos[n++] = &deltas[i];
 611        }
 612        qsort(sorted_by_pos, n, sizeof(*sorted_by_pos), delta_pos_compare);
 613
 614        for (i = 0; i < n; i++) {
 615                struct delta_entry *d = sorted_by_pos[i];
 616                void *data;
 617                unsigned long size;
 618                enum object_type type;
 619                int j, first, last;
 620
 621                if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
 622                        continue;
 623                data = read_sha1_file(d->base.sha1, &type, &size);
 624                if (!data)
 625                        continue;
 626
 627                find_delta_children(&d->base, &first, &last);
 628                for (j = first; j <= last; j++) {
 629                        struct object_entry *child = objects + deltas[j].obj_no;
 630                        if (child->real_type == OBJ_REF_DELTA)
 631                                resolve_delta(child, data, size, type);
 632                }
 633
 634                append_obj_to_pack(data, size, type);
 635                free(data);
 636                if (verbose)
 637                        percent = display_progress(nr_resolved_deltas,
 638                                                   nr_deltas, percent);
 639        }
 640        free(sorted_by_pos);
 641        if (verbose)
 642                fputc('\n', stderr);
 643}
 644
 645static void readjust_pack_header_and_sha1(unsigned char *sha1)
 646{
 647        struct pack_header hdr;
 648        SHA_CTX ctx;
 649        int size;
 650
 651        /* Rewrite pack header with updated object number */
 652        if (lseek(output_fd, 0, SEEK_SET) != 0)
 653                die("cannot seek back: %s", strerror(errno));
 654        if (read_in_full(output_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
 655                die("cannot read pack header back: %s", strerror(errno));
 656        hdr.hdr_entries = htonl(nr_objects);
 657        if (lseek(output_fd, 0, SEEK_SET) != 0)
 658                die("cannot seek back: %s", strerror(errno));
 659        write_or_die(output_fd, &hdr, sizeof(hdr));
 660        if (lseek(output_fd, 0, SEEK_SET) != 0)
 661                die("cannot seek back: %s", strerror(errno));
 662
 663        /* Recompute and store the new pack's SHA1 */
 664        SHA1_Init(&ctx);
 665        do {
 666                unsigned char *buf[4096];
 667                size = xread(output_fd, buf, sizeof(buf));
 668                if (size < 0)
 669                        die("cannot read pack data back: %s", strerror(errno));
 670                SHA1_Update(&ctx, buf, size);
 671        } while (size > 0);
 672        SHA1_Final(sha1, &ctx);
 673        write_or_die(output_fd, sha1, 20);
 674}
 675
 676static int sha1_compare(const void *_a, const void *_b)
 677{
 678        struct object_entry *a = *(struct object_entry **)_a;
 679        struct object_entry *b = *(struct object_entry **)_b;
 680        return hashcmp(a->sha1, b->sha1);
 681}
 682
 683/*
 684 * On entry *sha1 contains the pack content SHA1 hash, on exit it is
 685 * the SHA1 hash of sorted object names.
 686 */
 687static const char *write_index_file(const char *index_name, unsigned char *sha1)
 688{
 689        struct sha1file *f;
 690        struct object_entry **sorted_by_sha, **list, **last;
 691        unsigned int array[256];
 692        int i, fd;
 693        SHA_CTX ctx;
 694
 695        if (nr_objects) {
 696                sorted_by_sha =
 697                        xcalloc(nr_objects, sizeof(struct object_entry *));
 698                list = sorted_by_sha;
 699                last = sorted_by_sha + nr_objects;
 700                for (i = 0; i < nr_objects; ++i)
 701                        sorted_by_sha[i] = &objects[i];
 702                qsort(sorted_by_sha, nr_objects, sizeof(sorted_by_sha[0]),
 703                      sha1_compare);
 704
 705        }
 706        else
 707                sorted_by_sha = list = last = NULL;
 708
 709        if (!index_name) {
 710                static char tmpfile[PATH_MAX];
 711                snprintf(tmpfile, sizeof(tmpfile),
 712                         "%s/index_XXXXXX", get_object_directory());
 713                fd = mkstemp(tmpfile);
 714                index_name = xstrdup(tmpfile);
 715        } else {
 716                unlink(index_name);
 717                fd = open(index_name, O_CREAT|O_EXCL|O_WRONLY, 0600);
 718        }
 719        if (fd < 0)
 720                die("unable to create %s: %s", index_name, strerror(errno));
 721        f = sha1fd(fd, index_name);
 722
 723        /*
 724         * Write the first-level table (the list is sorted,
 725         * but we use a 256-entry lookup to be able to avoid
 726         * having to do eight extra binary search iterations).
 727         */
 728        for (i = 0; i < 256; i++) {
 729                struct object_entry **next = list;
 730                while (next < last) {
 731                        struct object_entry *obj = *next;
 732                        if (obj->sha1[0] != i)
 733                                break;
 734                        next++;
 735                }
 736                array[i] = htonl(next - sorted_by_sha);
 737                list = next;
 738        }
 739        sha1write(f, array, 256 * sizeof(int));
 740
 741        /* recompute the SHA1 hash of sorted object names.
 742         * currently pack-objects does not do this, but that
 743         * can be fixed.
 744         */
 745        SHA1_Init(&ctx);
 746        /*
 747         * Write the actual SHA1 entries..
 748         */
 749        list = sorted_by_sha;
 750        for (i = 0; i < nr_objects; i++) {
 751                struct object_entry *obj = *list++;
 752                unsigned int offset = htonl(obj->offset);
 753                sha1write(f, &offset, 4);
 754                sha1write(f, obj->sha1, 20);
 755                SHA1_Update(&ctx, obj->sha1, 20);
 756        }
 757        sha1write(f, sha1, 20);
 758        sha1close(f, NULL, 1);
 759        free(sorted_by_sha);
 760        SHA1_Final(sha1, &ctx);
 761        return index_name;
 762}
 763
 764static void final(const char *final_pack_name, const char *curr_pack_name,
 765                  const char *final_index_name, const char *curr_index_name,
 766                  const char *keep_name, const char *keep_msg,
 767                  unsigned char *sha1)
 768{
 769        const char *report = "pack";
 770        char name[PATH_MAX];
 771        int err;
 772
 773        if (!from_stdin) {
 774                close(input_fd);
 775        } else {
 776                err = close(output_fd);
 777                if (err)
 778                        die("error while closing pack file: %s", strerror(errno));
 779                chmod(curr_pack_name, 0444);
 780        }
 781
 782        if (keep_msg) {
 783                int keep_fd, keep_msg_len = strlen(keep_msg);
 784                if (!keep_name) {
 785                        snprintf(name, sizeof(name), "%s/pack/pack-%s.keep",
 786                                 get_object_directory(), sha1_to_hex(sha1));
 787                        keep_name = name;
 788                }
 789                keep_fd = open(keep_name, O_RDWR|O_CREAT|O_EXCL, 0600);
 790                if (keep_fd < 0) {
 791                        if (errno != EEXIST)
 792                                die("cannot write keep file");
 793                } else {
 794                        if (keep_msg_len > 0) {
 795                                write_or_die(keep_fd, keep_msg, keep_msg_len);
 796                                write_or_die(keep_fd, "\n", 1);
 797                        }
 798                        close(keep_fd);
 799                        report = "keep";
 800                }
 801        }
 802
 803        if (final_pack_name != curr_pack_name) {
 804                if (!final_pack_name) {
 805                        snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
 806                                 get_object_directory(), sha1_to_hex(sha1));
 807                        final_pack_name = name;
 808                }
 809                if (move_temp_to_file(curr_pack_name, final_pack_name))
 810                        die("cannot store pack file");
 811        }
 812
 813        chmod(curr_index_name, 0444);
 814        if (final_index_name != curr_index_name) {
 815                if (!final_index_name) {
 816                        snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
 817                                 get_object_directory(), sha1_to_hex(sha1));
 818                        final_index_name = name;
 819                }
 820                if (move_temp_to_file(curr_index_name, final_index_name))
 821                        die("cannot store index file");
 822        }
 823
 824        if (!from_stdin) {
 825                printf("%s\n", sha1_to_hex(sha1));
 826        } else {
 827                char buf[48];
 828                int len = snprintf(buf, sizeof(buf), "%s\t%s\n",
 829                                   report, sha1_to_hex(sha1));
 830                write_or_die(1, buf, len);
 831
 832                /*
 833                 * Let's just mimic git-unpack-objects here and write
 834                 * the last part of the input buffer to stdout.
 835                 */
 836                while (input_len) {
 837                        err = xwrite(1, input_buffer + input_offset, input_len);
 838                        if (err <= 0)
 839                                break;
 840                        input_len -= err;
 841                        input_offset += err;
 842                }
 843        }
 844}
 845
 846int main(int argc, char **argv)
 847{
 848        int i, fix_thin_pack = 0;
 849        const char *curr_pack, *pack_name = NULL;
 850        const char *curr_index, *index_name = NULL;
 851        const char *keep_name = NULL, *keep_msg = NULL;
 852        char *index_name_buf = NULL, *keep_name_buf = NULL;
 853        unsigned char sha1[20];
 854
 855        for (i = 1; i < argc; i++) {
 856                const char *arg = argv[i];
 857
 858                if (*arg == '-') {
 859                        if (!strcmp(arg, "--stdin")) {
 860                                from_stdin = 1;
 861                        } else if (!strcmp(arg, "--fix-thin")) {
 862                                fix_thin_pack = 1;
 863                        } else if (!strcmp(arg, "--keep")) {
 864                                keep_msg = "";
 865                        } else if (!prefixcmp(arg, "--keep=")) {
 866                                keep_msg = arg + 7;
 867                        } else if (!prefixcmp(arg, "--pack_header=")) {
 868                                struct pack_header *hdr;
 869                                char *c;
 870
 871                                hdr = (struct pack_header *)input_buffer;
 872                                hdr->hdr_signature = htonl(PACK_SIGNATURE);
 873                                hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
 874                                if (*c != ',')
 875                                        die("bad %s", arg);
 876                                hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
 877                                if (*c)
 878                                        die("bad %s", arg);
 879                                input_len = sizeof(*hdr);
 880                        } else if (!strcmp(arg, "-v")) {
 881                                verbose = 1;
 882                        } else if (!strcmp(arg, "-o")) {
 883                                if (index_name || (i+1) >= argc)
 884                                        usage(index_pack_usage);
 885                                index_name = argv[++i];
 886                        } else
 887                                usage(index_pack_usage);
 888                        continue;
 889                }
 890
 891                if (pack_name)
 892                        usage(index_pack_usage);
 893                pack_name = arg;
 894        }
 895
 896        if (!pack_name && !from_stdin)
 897                usage(index_pack_usage);
 898        if (fix_thin_pack && !from_stdin)
 899                die("--fix-thin cannot be used without --stdin");
 900        if (!index_name && pack_name) {
 901                int len = strlen(pack_name);
 902                if (!has_extension(pack_name, ".pack"))
 903                        die("packfile name '%s' does not end with '.pack'",
 904                            pack_name);
 905                index_name_buf = xmalloc(len);
 906                memcpy(index_name_buf, pack_name, len - 5);
 907                strcpy(index_name_buf + len - 5, ".idx");
 908                index_name = index_name_buf;
 909        }
 910        if (keep_msg && !keep_name && pack_name) {
 911                int len = strlen(pack_name);
 912                if (!has_extension(pack_name, ".pack"))
 913                        die("packfile name '%s' does not end with '.pack'",
 914                            pack_name);
 915                keep_name_buf = xmalloc(len);
 916                memcpy(keep_name_buf, pack_name, len - 5);
 917                strcpy(keep_name_buf + len - 5, ".keep");
 918                keep_name = keep_name_buf;
 919        }
 920
 921        curr_pack = open_pack_file(pack_name);
 922        parse_pack_header();
 923        objects = xmalloc((nr_objects + 1) * sizeof(struct object_entry));
 924        deltas = xmalloc(nr_objects * sizeof(struct delta_entry));
 925        if (verbose)
 926                setup_progress_signal();
 927        parse_pack_objects(sha1);
 928        if (nr_deltas != nr_resolved_deltas) {
 929                if (fix_thin_pack) {
 930                        int nr_unresolved = nr_deltas - nr_resolved_deltas;
 931                        int nr_objects_initial = nr_objects;
 932                        if (nr_unresolved <= 0)
 933                                die("confusion beyond insanity");
 934                        objects = xrealloc(objects,
 935                                           (nr_objects + nr_unresolved + 1)
 936                                           * sizeof(*objects));
 937                        fix_unresolved_deltas(nr_unresolved);
 938                        if (verbose)
 939                                fprintf(stderr, "%d objects were added to complete this thin pack.\n",
 940                                        nr_objects - nr_objects_initial);
 941                        readjust_pack_header_and_sha1(sha1);
 942                }
 943                if (nr_deltas != nr_resolved_deltas)
 944                        die("pack has %d unresolved deltas",
 945                            nr_deltas - nr_resolved_deltas);
 946        } else {
 947                /* Flush remaining pack final 20-byte SHA1. */
 948                flush();
 949        }
 950        free(deltas);
 951        curr_index = write_index_file(index_name, sha1);
 952        final(pack_name, curr_pack,
 953                index_name, curr_index,
 954                keep_name, keep_msg,
 955                sha1);
 956        free(objects);
 957        free(index_name_buf);
 958        free(keep_name_buf);
 959
 960        return 0;
 961}