index-pack.con commit git-upload-pack: make sure we close unused pipe ends (3ac53e0)
   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{
 350        SHA_CTX ctx;
 351        char header[50];
 352        int header_size;
 353        const char *type_str;
 354
 355        switch (type) {
 356        case OBJ_COMMIT: type_str = commit_type; break;
 357        case OBJ_TREE:   type_str = tree_type; break;
 358        case OBJ_BLOB:   type_str = blob_type; break;
 359        case OBJ_TAG:    type_str = tag_type; break;
 360        default:
 361                die("bad type %d", type);
 362        }
 363
 364        header_size = sprintf(header, "%s %lu", type_str, size) + 1;
 365
 366        SHA1_Init(&ctx);
 367        SHA1_Update(&ctx, header, header_size);
 368        SHA1_Update(&ctx, data, size);
 369        SHA1_Final(sha1, &ctx);
 370}
 371
 372static void resolve_delta(struct object_entry *delta_obj, void *base_data,
 373                          unsigned long base_size, enum object_type type)
 374{
 375        void *delta_data;
 376        unsigned long delta_size;
 377        void *result;
 378        unsigned long result_size;
 379        union delta_base delta_base;
 380        int j, first, last;
 381
 382        delta_obj->real_type = type;
 383        delta_data = get_data_from_pack(delta_obj);
 384        delta_size = delta_obj->size;
 385        result = patch_delta(base_data, base_size, delta_data, delta_size,
 386                             &result_size);
 387        free(delta_data);
 388        if (!result)
 389                bad_object(delta_obj->offset, "failed to apply delta");
 390        sha1_object(result, result_size, type, delta_obj->sha1);
 391        nr_resolved_deltas++;
 392
 393        hashcpy(delta_base.sha1, delta_obj->sha1);
 394        if (!find_delta_children(&delta_base, &first, &last)) {
 395                for (j = first; j <= last; j++) {
 396                        struct object_entry *child = objects + deltas[j].obj_no;
 397                        if (child->real_type == OBJ_REF_DELTA)
 398                                resolve_delta(child, result, result_size, type);
 399                }
 400        }
 401
 402        memset(&delta_base, 0, sizeof(delta_base));
 403        delta_base.offset = delta_obj->offset;
 404        if (!find_delta_children(&delta_base, &first, &last)) {
 405                for (j = first; j <= last; j++) {
 406                        struct object_entry *child = objects + deltas[j].obj_no;
 407                        if (child->real_type == OBJ_OFS_DELTA)
 408                                resolve_delta(child, result, result_size, type);
 409                }
 410        }
 411
 412        free(result);
 413}
 414
 415static int compare_delta_entry(const void *a, const void *b)
 416{
 417        const struct delta_entry *delta_a = a;
 418        const struct delta_entry *delta_b = b;
 419        return memcmp(&delta_a->base, &delta_b->base, UNION_BASE_SZ);
 420}
 421
 422/* Parse all objects and return the pack content SHA1 hash */
 423static void parse_pack_objects(unsigned char *sha1)
 424{
 425        int i, percent = -1;
 426        struct delta_entry *delta = deltas;
 427        void *data;
 428        struct stat st;
 429
 430        /*
 431         * First pass:
 432         * - find locations of all objects;
 433         * - calculate SHA1 of all non-delta objects;
 434         * - remember base (SHA1 or offset) for all deltas.
 435         */
 436        if (verbose)
 437                fprintf(stderr, "Indexing %d objects.\n", nr_objects);
 438        for (i = 0; i < nr_objects; i++) {
 439                struct object_entry *obj = &objects[i];
 440                data = unpack_raw_entry(obj, &delta->base);
 441                obj->real_type = obj->type;
 442                if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA) {
 443                        nr_deltas++;
 444                        delta->obj_no = i;
 445                        delta++;
 446                } else
 447                        sha1_object(data, obj->size, obj->type, obj->sha1);
 448                free(data);
 449                if (verbose)
 450                        percent = display_progress(i+1, nr_objects, percent);
 451        }
 452        objects[i].offset = consumed_bytes;
 453        if (verbose)
 454                fputc('\n', stderr);
 455
 456        /* Check pack integrity */
 457        flush();
 458        SHA1_Final(sha1, &input_ctx);
 459        if (hashcmp(fill(20), sha1))
 460                die("pack is corrupted (SHA1 mismatch)");
 461        use(20);
 462
 463        /* If input_fd is a file, we should have reached its end now. */
 464        if (fstat(input_fd, &st))
 465                die("cannot fstat packfile: %s", strerror(errno));
 466        if (S_ISREG(st.st_mode) && st.st_size != consumed_bytes)
 467                die("pack has junk at the end");
 468
 469        if (!nr_deltas)
 470                return;
 471
 472        /* Sort deltas by base SHA1/offset for fast searching */
 473        qsort(deltas, nr_deltas, sizeof(struct delta_entry),
 474              compare_delta_entry);
 475
 476        /*
 477         * Second pass:
 478         * - for all non-delta objects, look if it is used as a base for
 479         *   deltas;
 480         * - if used as a base, uncompress the object and apply all deltas,
 481         *   recursively checking if the resulting object is used as a base
 482         *   for some more deltas.
 483         */
 484        if (verbose)
 485                fprintf(stderr, "Resolving %d deltas.\n", nr_deltas);
 486        for (i = 0; i < nr_objects; i++) {
 487                struct object_entry *obj = &objects[i];
 488                union delta_base base;
 489                int j, ref, ref_first, ref_last, ofs, ofs_first, ofs_last;
 490
 491                if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA)
 492                        continue;
 493                hashcpy(base.sha1, obj->sha1);
 494                ref = !find_delta_children(&base, &ref_first, &ref_last);
 495                memset(&base, 0, sizeof(base));
 496                base.offset = obj->offset;
 497                ofs = !find_delta_children(&base, &ofs_first, &ofs_last);
 498                if (!ref && !ofs)
 499                        continue;
 500                data = get_data_from_pack(obj);
 501                if (ref)
 502                        for (j = ref_first; j <= ref_last; j++) {
 503                                struct object_entry *child = objects + deltas[j].obj_no;
 504                                if (child->real_type == OBJ_REF_DELTA)
 505                                        resolve_delta(child, data,
 506                                                      obj->size, obj->type);
 507                        }
 508                if (ofs)
 509                        for (j = ofs_first; j <= ofs_last; j++) {
 510                                struct object_entry *child = objects + deltas[j].obj_no;
 511                                if (child->real_type == OBJ_OFS_DELTA)
 512                                        resolve_delta(child, data,
 513                                                      obj->size, obj->type);
 514                        }
 515                free(data);
 516                if (verbose)
 517                        percent = display_progress(nr_resolved_deltas,
 518                                                   nr_deltas, percent);
 519        }
 520        if (verbose && nr_resolved_deltas == nr_deltas)
 521                fputc('\n', stderr);
 522}
 523
 524static int write_compressed(int fd, void *in, unsigned int size)
 525{
 526        z_stream stream;
 527        unsigned long maxsize;
 528        void *out;
 529
 530        memset(&stream, 0, sizeof(stream));
 531        deflateInit(&stream, zlib_compression_level);
 532        maxsize = deflateBound(&stream, size);
 533        out = xmalloc(maxsize);
 534
 535        /* Compress it */
 536        stream.next_in = in;
 537        stream.avail_in = size;
 538        stream.next_out = out;
 539        stream.avail_out = maxsize;
 540        while (deflate(&stream, Z_FINISH) == Z_OK);
 541        deflateEnd(&stream);
 542
 543        size = stream.total_out;
 544        write_or_die(fd, out, size);
 545        free(out);
 546        return size;
 547}
 548
 549static void append_obj_to_pack(void *buf,
 550                               unsigned long size, enum object_type type)
 551{
 552        struct object_entry *obj = &objects[nr_objects++];
 553        unsigned char header[10];
 554        unsigned long s = size;
 555        int n = 0;
 556        unsigned char c = (type << 4) | (s & 15);
 557        s >>= 4;
 558        while (s) {
 559                header[n++] = c | 0x80;
 560                c = s & 0x7f;
 561                s >>= 7;
 562        }
 563        header[n++] = c;
 564        write_or_die(output_fd, header, n);
 565        obj[1].offset = obj[0].offset + n;
 566        obj[1].offset += write_compressed(output_fd, buf, size);
 567        sha1_object(buf, size, type, obj->sha1);
 568}
 569
 570static int delta_pos_compare(const void *_a, const void *_b)
 571{
 572        struct delta_entry *a = *(struct delta_entry **)_a;
 573        struct delta_entry *b = *(struct delta_entry **)_b;
 574        return a->obj_no - b->obj_no;
 575}
 576
 577static void fix_unresolved_deltas(int nr_unresolved)
 578{
 579        struct delta_entry **sorted_by_pos;
 580        int i, n = 0, percent = -1;
 581
 582        /*
 583         * Since many unresolved deltas may well be themselves base objects
 584         * for more unresolved deltas, we really want to include the
 585         * smallest number of base objects that would cover as much delta
 586         * as possible by picking the
 587         * trunc deltas first, allowing for other deltas to resolve without
 588         * additional base objects.  Since most base objects are to be found
 589         * before deltas depending on them, a good heuristic is to start
 590         * resolving deltas in the same order as their position in the pack.
 591         */
 592        sorted_by_pos = xmalloc(nr_unresolved * sizeof(*sorted_by_pos));
 593        for (i = 0; i < nr_deltas; i++) {
 594                if (objects[deltas[i].obj_no].real_type != OBJ_REF_DELTA)
 595                        continue;
 596                sorted_by_pos[n++] = &deltas[i];
 597        }
 598        qsort(sorted_by_pos, n, sizeof(*sorted_by_pos), delta_pos_compare);
 599
 600        for (i = 0; i < n; i++) {
 601                struct delta_entry *d = sorted_by_pos[i];
 602                void *data;
 603                unsigned long size;
 604                char type[10];
 605                enum object_type obj_type;
 606                int j, first, last;
 607
 608                if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
 609                        continue;
 610                data = read_sha1_file(d->base.sha1, type, &size);
 611                if (!data)
 612                        continue;
 613                if      (!strcmp(type, blob_type))   obj_type = OBJ_BLOB;
 614                else if (!strcmp(type, tree_type))   obj_type = OBJ_TREE;
 615                else if (!strcmp(type, commit_type)) obj_type = OBJ_COMMIT;
 616                else if (!strcmp(type, tag_type))    obj_type = OBJ_TAG;
 617                else die("base object %s is of type '%s'",
 618                         sha1_to_hex(d->base.sha1), type);
 619
 620                find_delta_children(&d->base, &first, &last);
 621                for (j = first; j <= last; j++) {
 622                        struct object_entry *child = objects + deltas[j].obj_no;
 623                        if (child->real_type == OBJ_REF_DELTA)
 624                                resolve_delta(child, data, size, obj_type);
 625                }
 626
 627                append_obj_to_pack(data, size, obj_type);
 628                free(data);
 629                if (verbose)
 630                        percent = display_progress(nr_resolved_deltas,
 631                                                   nr_deltas, percent);
 632        }
 633        free(sorted_by_pos);
 634        if (verbose)
 635                fputc('\n', stderr);
 636}
 637
 638static void readjust_pack_header_and_sha1(unsigned char *sha1)
 639{
 640        struct pack_header hdr;
 641        SHA_CTX ctx;
 642        int size;
 643
 644        /* Rewrite pack header with updated object number */
 645        if (lseek(output_fd, 0, SEEK_SET) != 0)
 646                die("cannot seek back: %s", strerror(errno));
 647        if (read_in_full(output_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
 648                die("cannot read pack header back: %s", strerror(errno));
 649        hdr.hdr_entries = htonl(nr_objects);
 650        if (lseek(output_fd, 0, SEEK_SET) != 0)
 651                die("cannot seek back: %s", strerror(errno));
 652        write_or_die(output_fd, &hdr, sizeof(hdr));
 653        if (lseek(output_fd, 0, SEEK_SET) != 0)
 654                die("cannot seek back: %s", strerror(errno));
 655
 656        /* Recompute and store the new pack's SHA1 */
 657        SHA1_Init(&ctx);
 658        do {
 659                unsigned char *buf[4096];
 660                size = xread(output_fd, buf, sizeof(buf));
 661                if (size < 0)
 662                        die("cannot read pack data back: %s", strerror(errno));
 663                SHA1_Update(&ctx, buf, size);
 664        } while (size > 0);
 665        SHA1_Final(sha1, &ctx);
 666        write_or_die(output_fd, sha1, 20);
 667}
 668
 669static int sha1_compare(const void *_a, const void *_b)
 670{
 671        struct object_entry *a = *(struct object_entry **)_a;
 672        struct object_entry *b = *(struct object_entry **)_b;
 673        return hashcmp(a->sha1, b->sha1);
 674}
 675
 676/*
 677 * On entry *sha1 contains the pack content SHA1 hash, on exit it is
 678 * the SHA1 hash of sorted object names.
 679 */
 680static const char *write_index_file(const char *index_name, unsigned char *sha1)
 681{
 682        struct sha1file *f;
 683        struct object_entry **sorted_by_sha, **list, **last;
 684        unsigned int array[256];
 685        int i, fd;
 686        SHA_CTX ctx;
 687
 688        if (nr_objects) {
 689                sorted_by_sha =
 690                        xcalloc(nr_objects, sizeof(struct object_entry *));
 691                list = sorted_by_sha;
 692                last = sorted_by_sha + nr_objects;
 693                for (i = 0; i < nr_objects; ++i)
 694                        sorted_by_sha[i] = &objects[i];
 695                qsort(sorted_by_sha, nr_objects, sizeof(sorted_by_sha[0]),
 696                      sha1_compare);
 697
 698        }
 699        else
 700                sorted_by_sha = list = last = NULL;
 701
 702        if (!index_name) {
 703                static char tmpfile[PATH_MAX];
 704                snprintf(tmpfile, sizeof(tmpfile),
 705                         "%s/index_XXXXXX", get_object_directory());
 706                fd = mkstemp(tmpfile);
 707                index_name = xstrdup(tmpfile);
 708        } else {
 709                unlink(index_name);
 710                fd = open(index_name, O_CREAT|O_EXCL|O_WRONLY, 0600);
 711        }
 712        if (fd < 0)
 713                die("unable to create %s: %s", index_name, strerror(errno));
 714        f = sha1fd(fd, index_name);
 715
 716        /*
 717         * Write the first-level table (the list is sorted,
 718         * but we use a 256-entry lookup to be able to avoid
 719         * having to do eight extra binary search iterations).
 720         */
 721        for (i = 0; i < 256; i++) {
 722                struct object_entry **next = list;
 723                while (next < last) {
 724                        struct object_entry *obj = *next;
 725                        if (obj->sha1[0] != i)
 726                                break;
 727                        next++;
 728                }
 729                array[i] = htonl(next - sorted_by_sha);
 730                list = next;
 731        }
 732        sha1write(f, array, 256 * sizeof(int));
 733
 734        /* recompute the SHA1 hash of sorted object names.
 735         * currently pack-objects does not do this, but that
 736         * can be fixed.
 737         */
 738        SHA1_Init(&ctx);
 739        /*
 740         * Write the actual SHA1 entries..
 741         */
 742        list = sorted_by_sha;
 743        for (i = 0; i < nr_objects; i++) {
 744                struct object_entry *obj = *list++;
 745                unsigned int offset = htonl(obj->offset);
 746                sha1write(f, &offset, 4);
 747                sha1write(f, obj->sha1, 20);
 748                SHA1_Update(&ctx, obj->sha1, 20);
 749        }
 750        sha1write(f, sha1, 20);
 751        sha1close(f, NULL, 1);
 752        free(sorted_by_sha);
 753        SHA1_Final(sha1, &ctx);
 754        return index_name;
 755}
 756
 757static void final(const char *final_pack_name, const char *curr_pack_name,
 758                  const char *final_index_name, const char *curr_index_name,
 759                  const char *keep_name, const char *keep_msg,
 760                  unsigned char *sha1)
 761{
 762        char *report = "pack";
 763        char name[PATH_MAX];
 764        int err;
 765
 766        if (!from_stdin) {
 767                close(input_fd);
 768        } else {
 769                err = close(output_fd);
 770                if (err)
 771                        die("error while closing pack file: %s", strerror(errno));
 772                chmod(curr_pack_name, 0444);
 773        }
 774
 775        if (keep_msg) {
 776                int keep_fd, keep_msg_len = strlen(keep_msg);
 777                if (!keep_name) {
 778                        snprintf(name, sizeof(name), "%s/pack/pack-%s.keep",
 779                                 get_object_directory(), sha1_to_hex(sha1));
 780                        keep_name = name;
 781                }
 782                keep_fd = open(keep_name, O_RDWR|O_CREAT|O_EXCL, 0600);
 783                if (keep_fd < 0) {
 784                        if (errno != EEXIST)
 785                                die("cannot write keep file");
 786                } else {
 787                        if (keep_msg_len > 0) {
 788                                write_or_die(keep_fd, keep_msg, keep_msg_len);
 789                                write_or_die(keep_fd, "\n", 1);
 790                        }
 791                        close(keep_fd);
 792                        report = "keep";
 793                }
 794        }
 795
 796        if (final_pack_name != curr_pack_name) {
 797                if (!final_pack_name) {
 798                        snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
 799                                 get_object_directory(), sha1_to_hex(sha1));
 800                        final_pack_name = name;
 801                }
 802                if (move_temp_to_file(curr_pack_name, final_pack_name))
 803                        die("cannot store pack file");
 804        }
 805
 806        chmod(curr_index_name, 0444);
 807        if (final_index_name != curr_index_name) {
 808                if (!final_index_name) {
 809                        snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
 810                                 get_object_directory(), sha1_to_hex(sha1));
 811                        final_index_name = name;
 812                }
 813                if (move_temp_to_file(curr_index_name, final_index_name))
 814                        die("cannot store index file");
 815        }
 816
 817        if (!from_stdin) {
 818                printf("%s\n", sha1_to_hex(sha1));
 819        } else {
 820                char buf[48];
 821                int len = snprintf(buf, sizeof(buf), "%s\t%s\n",
 822                                   report, sha1_to_hex(sha1));
 823                write_or_die(1, buf, len);
 824
 825                /*
 826                 * Let's just mimic git-unpack-objects here and write
 827                 * the last part of the input buffer to stdout.
 828                 */
 829                while (input_len) {
 830                        err = xwrite(1, input_buffer + input_offset, input_len);
 831                        if (err <= 0)
 832                                break;
 833                        input_len -= err;
 834                        input_offset += err;
 835                }
 836        }
 837}
 838
 839int main(int argc, char **argv)
 840{
 841        int i, fix_thin_pack = 0;
 842        const char *curr_pack, *pack_name = NULL;
 843        const char *curr_index, *index_name = NULL;
 844        const char *keep_name = NULL, *keep_msg = NULL;
 845        char *index_name_buf = NULL, *keep_name_buf = NULL;
 846        unsigned char sha1[20];
 847
 848        for (i = 1; i < argc; i++) {
 849                const char *arg = argv[i];
 850
 851                if (*arg == '-') {
 852                        if (!strcmp(arg, "--stdin")) {
 853                                from_stdin = 1;
 854                        } else if (!strcmp(arg, "--fix-thin")) {
 855                                fix_thin_pack = 1;
 856                        } else if (!strcmp(arg, "--keep")) {
 857                                keep_msg = "";
 858                        } else if (!strncmp(arg, "--keep=", 7)) {
 859                                keep_msg = arg + 7;
 860                        } else if (!strncmp(arg, "--pack_header=", 14)) {
 861                                struct pack_header *hdr;
 862                                char *c;
 863
 864                                hdr = (struct pack_header *)input_buffer;
 865                                hdr->hdr_signature = htonl(PACK_SIGNATURE);
 866                                hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
 867                                if (*c != ',')
 868                                        die("bad %s", arg);
 869                                hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
 870                                if (*c)
 871                                        die("bad %s", arg);
 872                                input_len = sizeof(*hdr);
 873                        } else if (!strcmp(arg, "-v")) {
 874                                verbose = 1;
 875                        } else if (!strcmp(arg, "-o")) {
 876                                if (index_name || (i+1) >= argc)
 877                                        usage(index_pack_usage);
 878                                index_name = argv[++i];
 879                        } else
 880                                usage(index_pack_usage);
 881                        continue;
 882                }
 883
 884                if (pack_name)
 885                        usage(index_pack_usage);
 886                pack_name = arg;
 887        }
 888
 889        if (!pack_name && !from_stdin)
 890                usage(index_pack_usage);
 891        if (fix_thin_pack && !from_stdin)
 892                die("--fix-thin cannot be used without --stdin");
 893        if (!index_name && pack_name) {
 894                int len = strlen(pack_name);
 895                if (!has_extension(pack_name, ".pack"))
 896                        die("packfile name '%s' does not end with '.pack'",
 897                            pack_name);
 898                index_name_buf = xmalloc(len);
 899                memcpy(index_name_buf, pack_name, len - 5);
 900                strcpy(index_name_buf + len - 5, ".idx");
 901                index_name = index_name_buf;
 902        }
 903        if (keep_msg && !keep_name && pack_name) {
 904                int len = strlen(pack_name);
 905                if (!has_extension(pack_name, ".pack"))
 906                        die("packfile name '%s' does not end with '.pack'",
 907                            pack_name);
 908                keep_name_buf = xmalloc(len);
 909                memcpy(keep_name_buf, pack_name, len - 5);
 910                strcpy(keep_name_buf + len - 5, ".keep");
 911                keep_name = keep_name_buf;
 912        }
 913
 914        curr_pack = open_pack_file(pack_name);
 915        parse_pack_header();
 916        objects = xmalloc((nr_objects + 1) * sizeof(struct object_entry));
 917        deltas = xmalloc(nr_objects * sizeof(struct delta_entry));
 918        if (verbose)
 919                setup_progress_signal();
 920        parse_pack_objects(sha1);
 921        if (nr_deltas != nr_resolved_deltas) {
 922                if (fix_thin_pack) {
 923                        int nr_unresolved = nr_deltas - nr_resolved_deltas;
 924                        int nr_objects_initial = nr_objects;
 925                        if (nr_unresolved <= 0)
 926                                die("confusion beyond insanity");
 927                        objects = xrealloc(objects,
 928                                           (nr_objects + nr_unresolved + 1)
 929                                           * sizeof(*objects));
 930                        fix_unresolved_deltas(nr_unresolved);
 931                        if (verbose)
 932                                fprintf(stderr, "%d objects were added to complete this thin pack.\n",
 933                                        nr_objects - nr_objects_initial);
 934                        readjust_pack_header_and_sha1(sha1);
 935                }
 936                if (nr_deltas != nr_resolved_deltas)
 937                        die("pack has %d unresolved deltas",
 938                            nr_deltas - nr_resolved_deltas);
 939        } else {
 940                /* Flush remaining pack final 20-byte SHA1. */
 941                flush();
 942        }
 943        free(deltas);
 944        curr_index = write_index_file(index_name, sha1);
 945        final(pack_name, curr_pack,
 946                index_name, curr_index,
 947                keep_name, keep_msg,
 948                sha1);
 949        free(objects);
 950        free(index_name_buf);
 951        free(keep_name_buf);
 952
 953        return 0;
 954}