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