fetch-pack.con commit fetch-pack: support negotiation tip whitelist (3390e42)
   1#include "cache.h"
   2#include "repository.h"
   3#include "config.h"
   4#include "lockfile.h"
   5#include "refs.h"
   6#include "pkt-line.h"
   7#include "commit.h"
   8#include "tag.h"
   9#include "exec-cmd.h"
  10#include "pack.h"
  11#include "sideband.h"
  12#include "fetch-pack.h"
  13#include "remote.h"
  14#include "run-command.h"
  15#include "connect.h"
  16#include "transport.h"
  17#include "version.h"
  18#include "sha1-array.h"
  19#include "oidset.h"
  20#include "packfile.h"
  21#include "fetch-negotiator.h"
  22
  23static int transfer_unpack_limit = -1;
  24static int fetch_unpack_limit = -1;
  25static int unpack_limit = 100;
  26static int prefer_ofs_delta = 1;
  27static int no_done;
  28static int deepen_since_ok;
  29static int deepen_not_ok;
  30static int fetch_fsck_objects = -1;
  31static int transfer_fsck_objects = -1;
  32static int agent_supported;
  33static int server_supports_filtering;
  34static struct lock_file shallow_lock;
  35static const char *alternate_shallow_file;
  36
  37/* Remember to update object flag allocation in object.h */
  38#define COMPLETE        (1U << 0)
  39#define ALTERNATE       (1U << 1)
  40
  41/*
  42 * After sending this many "have"s if we do not get any new ACK , we
  43 * give up traversing our history.
  44 */
  45#define MAX_IN_VAIN 256
  46
  47static int multi_ack, use_sideband;
  48/* Allow specifying sha1 if it is a ref tip. */
  49#define ALLOW_TIP_SHA1  01
  50/* Allow request of a sha1 if it is reachable from a ref (possibly hidden ref). */
  51#define ALLOW_REACHABLE_SHA1    02
  52static unsigned int allow_unadvertised_object_request;
  53
  54__attribute__((format (printf, 2, 3)))
  55static inline void print_verbose(const struct fetch_pack_args *args,
  56                                 const char *fmt, ...)
  57{
  58        va_list params;
  59
  60        if (!args->verbose)
  61                return;
  62
  63        va_start(params, fmt);
  64        vfprintf(stderr, fmt, params);
  65        va_end(params);
  66        fputc('\n', stderr);
  67}
  68
  69struct alternate_object_cache {
  70        struct object **items;
  71        size_t nr, alloc;
  72};
  73
  74static void cache_one_alternate(const char *refname,
  75                                const struct object_id *oid,
  76                                void *vcache)
  77{
  78        struct alternate_object_cache *cache = vcache;
  79        struct object *obj = parse_object(oid);
  80
  81        if (!obj || (obj->flags & ALTERNATE))
  82                return;
  83
  84        obj->flags |= ALTERNATE;
  85        ALLOC_GROW(cache->items, cache->nr + 1, cache->alloc);
  86        cache->items[cache->nr++] = obj;
  87}
  88
  89static void for_each_cached_alternate(struct fetch_negotiator *negotiator,
  90                                      void (*cb)(struct fetch_negotiator *,
  91                                                 struct object *))
  92{
  93        static int initialized;
  94        static struct alternate_object_cache cache;
  95        size_t i;
  96
  97        if (!initialized) {
  98                for_each_alternate_ref(cache_one_alternate, &cache);
  99                initialized = 1;
 100        }
 101
 102        for (i = 0; i < cache.nr; i++)
 103                cb(negotiator, cache.items[i]);
 104}
 105
 106static int rev_list_insert_ref(struct fetch_negotiator *negotiator,
 107                               const char *refname,
 108                               const struct object_id *oid)
 109{
 110        struct object *o = deref_tag(parse_object(oid), refname, 0);
 111
 112        if (o && o->type == OBJ_COMMIT)
 113                negotiator->add_tip(negotiator, (struct commit *)o);
 114
 115        return 0;
 116}
 117
 118static int rev_list_insert_ref_oid(const char *refname, const struct object_id *oid,
 119                                   int flag, void *cb_data)
 120{
 121        return rev_list_insert_ref(cb_data, refname, oid);
 122}
 123
 124enum ack_type {
 125        NAK = 0,
 126        ACK,
 127        ACK_continue,
 128        ACK_common,
 129        ACK_ready
 130};
 131
 132static void consume_shallow_list(struct fetch_pack_args *args, int fd)
 133{
 134        if (args->stateless_rpc && args->deepen) {
 135                /* If we sent a depth we will get back "duplicate"
 136                 * shallow and unshallow commands every time there
 137                 * is a block of have lines exchanged.
 138                 */
 139                char *line;
 140                while ((line = packet_read_line(fd, NULL))) {
 141                        if (starts_with(line, "shallow "))
 142                                continue;
 143                        if (starts_with(line, "unshallow "))
 144                                continue;
 145                        die(_("git fetch-pack: expected shallow list"));
 146                }
 147        }
 148}
 149
 150static enum ack_type get_ack(int fd, struct object_id *result_oid)
 151{
 152        int len;
 153        char *line = packet_read_line(fd, &len);
 154        const char *arg;
 155
 156        if (!line)
 157                die(_("git fetch-pack: expected ACK/NAK, got a flush packet"));
 158        if (!strcmp(line, "NAK"))
 159                return NAK;
 160        if (skip_prefix(line, "ACK ", &arg)) {
 161                if (!get_oid_hex(arg, result_oid)) {
 162                        arg += 40;
 163                        len -= arg - line;
 164                        if (len < 1)
 165                                return ACK;
 166                        if (strstr(arg, "continue"))
 167                                return ACK_continue;
 168                        if (strstr(arg, "common"))
 169                                return ACK_common;
 170                        if (strstr(arg, "ready"))
 171                                return ACK_ready;
 172                        return ACK;
 173                }
 174        }
 175        if (skip_prefix(line, "ERR ", &arg))
 176                die(_("remote error: %s"), arg);
 177        die(_("git fetch-pack: expected ACK/NAK, got '%s'"), line);
 178}
 179
 180static void send_request(struct fetch_pack_args *args,
 181                         int fd, struct strbuf *buf)
 182{
 183        if (args->stateless_rpc) {
 184                send_sideband(fd, -1, buf->buf, buf->len, LARGE_PACKET_MAX);
 185                packet_flush(fd);
 186        } else
 187                write_or_die(fd, buf->buf, buf->len);
 188}
 189
 190static void insert_one_alternate_object(struct fetch_negotiator *negotiator,
 191                                        struct object *obj)
 192{
 193        rev_list_insert_ref(negotiator, NULL, &obj->oid);
 194}
 195
 196#define INITIAL_FLUSH 16
 197#define PIPESAFE_FLUSH 32
 198#define LARGE_FLUSH 16384
 199
 200static int next_flush(int stateless_rpc, int count)
 201{
 202        if (stateless_rpc) {
 203                if (count < LARGE_FLUSH)
 204                        count <<= 1;
 205                else
 206                        count = count * 11 / 10;
 207        } else {
 208                if (count < PIPESAFE_FLUSH)
 209                        count <<= 1;
 210                else
 211                        count += PIPESAFE_FLUSH;
 212        }
 213        return count;
 214}
 215
 216static void mark_tips(struct fetch_negotiator *negotiator,
 217                      const struct oid_array *negotiation_tips)
 218{
 219        int i;
 220
 221        if (!negotiation_tips) {
 222                for_each_ref(rev_list_insert_ref_oid, negotiator);
 223                return;
 224        }
 225
 226        for (i = 0; i < negotiation_tips->nr; i++)
 227                rev_list_insert_ref(negotiator, NULL,
 228                                    &negotiation_tips->oid[i]);
 229        return;
 230}
 231
 232static int find_common(struct fetch_negotiator *negotiator,
 233                       struct fetch_pack_args *args,
 234                       int fd[2], struct object_id *result_oid,
 235                       struct ref *refs)
 236{
 237        int fetching;
 238        int count = 0, flushes = 0, flush_at = INITIAL_FLUSH, retval;
 239        const struct object_id *oid;
 240        unsigned in_vain = 0;
 241        int got_continue = 0;
 242        int got_ready = 0;
 243        struct strbuf req_buf = STRBUF_INIT;
 244        size_t state_len = 0;
 245
 246        if (args->stateless_rpc && multi_ack == 1)
 247                die(_("--stateless-rpc requires multi_ack_detailed"));
 248
 249        mark_tips(negotiator, args->negotiation_tips);
 250        for_each_cached_alternate(negotiator, insert_one_alternate_object);
 251
 252        fetching = 0;
 253        for ( ; refs ; refs = refs->next) {
 254                struct object_id *remote = &refs->old_oid;
 255                const char *remote_hex;
 256                struct object *o;
 257
 258                /*
 259                 * If that object is complete (i.e. it is an ancestor of a
 260                 * local ref), we tell them we have it but do not have to
 261                 * tell them about its ancestors, which they already know
 262                 * about.
 263                 *
 264                 * We use lookup_object here because we are only
 265                 * interested in the case we *know* the object is
 266                 * reachable and we have already scanned it.
 267                 */
 268                if (((o = lookup_object(remote->hash)) != NULL) &&
 269                                (o->flags & COMPLETE)) {
 270                        continue;
 271                }
 272
 273                remote_hex = oid_to_hex(remote);
 274                if (!fetching) {
 275                        struct strbuf c = STRBUF_INIT;
 276                        if (multi_ack == 2)     strbuf_addstr(&c, " multi_ack_detailed");
 277                        if (multi_ack == 1)     strbuf_addstr(&c, " multi_ack");
 278                        if (no_done)            strbuf_addstr(&c, " no-done");
 279                        if (use_sideband == 2)  strbuf_addstr(&c, " side-band-64k");
 280                        if (use_sideband == 1)  strbuf_addstr(&c, " side-band");
 281                        if (args->deepen_relative) strbuf_addstr(&c, " deepen-relative");
 282                        if (args->use_thin_pack) strbuf_addstr(&c, " thin-pack");
 283                        if (args->no_progress)   strbuf_addstr(&c, " no-progress");
 284                        if (args->include_tag)   strbuf_addstr(&c, " include-tag");
 285                        if (prefer_ofs_delta)   strbuf_addstr(&c, " ofs-delta");
 286                        if (deepen_since_ok)    strbuf_addstr(&c, " deepen-since");
 287                        if (deepen_not_ok)      strbuf_addstr(&c, " deepen-not");
 288                        if (agent_supported)    strbuf_addf(&c, " agent=%s",
 289                                                            git_user_agent_sanitized());
 290                        if (args->filter_options.choice)
 291                                strbuf_addstr(&c, " filter");
 292                        packet_buf_write(&req_buf, "want %s%s\n", remote_hex, c.buf);
 293                        strbuf_release(&c);
 294                } else
 295                        packet_buf_write(&req_buf, "want %s\n", remote_hex);
 296                fetching++;
 297        }
 298
 299        if (!fetching) {
 300                strbuf_release(&req_buf);
 301                packet_flush(fd[1]);
 302                return 1;
 303        }
 304
 305        if (is_repository_shallow())
 306                write_shallow_commits(&req_buf, 1, NULL);
 307        if (args->depth > 0)
 308                packet_buf_write(&req_buf, "deepen %d", args->depth);
 309        if (args->deepen_since) {
 310                timestamp_t max_age = approxidate(args->deepen_since);
 311                packet_buf_write(&req_buf, "deepen-since %"PRItime, max_age);
 312        }
 313        if (args->deepen_not) {
 314                int i;
 315                for (i = 0; i < args->deepen_not->nr; i++) {
 316                        struct string_list_item *s = args->deepen_not->items + i;
 317                        packet_buf_write(&req_buf, "deepen-not %s", s->string);
 318                }
 319        }
 320        if (server_supports_filtering && args->filter_options.choice)
 321                packet_buf_write(&req_buf, "filter %s",
 322                                 args->filter_options.filter_spec);
 323        packet_buf_flush(&req_buf);
 324        state_len = req_buf.len;
 325
 326        if (args->deepen) {
 327                char *line;
 328                const char *arg;
 329                struct object_id oid;
 330
 331                send_request(args, fd[1], &req_buf);
 332                while ((line = packet_read_line(fd[0], NULL))) {
 333                        if (skip_prefix(line, "shallow ", &arg)) {
 334                                if (get_oid_hex(arg, &oid))
 335                                        die(_("invalid shallow line: %s"), line);
 336                                register_shallow(&oid);
 337                                continue;
 338                        }
 339                        if (skip_prefix(line, "unshallow ", &arg)) {
 340                                if (get_oid_hex(arg, &oid))
 341                                        die(_("invalid unshallow line: %s"), line);
 342                                if (!lookup_object(oid.hash))
 343                                        die(_("object not found: %s"), line);
 344                                /* make sure that it is parsed as shallow */
 345                                if (!parse_object(&oid))
 346                                        die(_("error in object: %s"), line);
 347                                if (unregister_shallow(&oid))
 348                                        die(_("no shallow found: %s"), line);
 349                                continue;
 350                        }
 351                        die(_("expected shallow/unshallow, got %s"), line);
 352                }
 353        } else if (!args->stateless_rpc)
 354                send_request(args, fd[1], &req_buf);
 355
 356        if (!args->stateless_rpc) {
 357                /* If we aren't using the stateless-rpc interface
 358                 * we don't need to retain the headers.
 359                 */
 360                strbuf_setlen(&req_buf, 0);
 361                state_len = 0;
 362        }
 363
 364        flushes = 0;
 365        retval = -1;
 366        if (args->no_dependents)
 367                goto done;
 368        while ((oid = negotiator->next(negotiator))) {
 369                packet_buf_write(&req_buf, "have %s\n", oid_to_hex(oid));
 370                print_verbose(args, "have %s", oid_to_hex(oid));
 371                in_vain++;
 372                if (flush_at <= ++count) {
 373                        int ack;
 374
 375                        packet_buf_flush(&req_buf);
 376                        send_request(args, fd[1], &req_buf);
 377                        strbuf_setlen(&req_buf, state_len);
 378                        flushes++;
 379                        flush_at = next_flush(args->stateless_rpc, count);
 380
 381                        /*
 382                         * We keep one window "ahead" of the other side, and
 383                         * will wait for an ACK only on the next one
 384                         */
 385                        if (!args->stateless_rpc && count == INITIAL_FLUSH)
 386                                continue;
 387
 388                        consume_shallow_list(args, fd[0]);
 389                        do {
 390                                ack = get_ack(fd[0], result_oid);
 391                                if (ack)
 392                                        print_verbose(args, _("got %s %d %s"), "ack",
 393                                                      ack, oid_to_hex(result_oid));
 394                                switch (ack) {
 395                                case ACK:
 396                                        flushes = 0;
 397                                        multi_ack = 0;
 398                                        retval = 0;
 399                                        goto done;
 400                                case ACK_common:
 401                                case ACK_ready:
 402                                case ACK_continue: {
 403                                        struct commit *commit =
 404                                                lookup_commit(result_oid);
 405                                        int was_common;
 406                                        if (!commit)
 407                                                die(_("invalid commit %s"), oid_to_hex(result_oid));
 408                                        was_common = negotiator->ack(negotiator, commit);
 409                                        if (args->stateless_rpc
 410                                         && ack == ACK_common
 411                                         && !was_common) {
 412                                                /* We need to replay the have for this object
 413                                                 * on the next RPC request so the peer knows
 414                                                 * it is in common with us.
 415                                                 */
 416                                                const char *hex = oid_to_hex(result_oid);
 417                                                packet_buf_write(&req_buf, "have %s\n", hex);
 418                                                state_len = req_buf.len;
 419                                                /*
 420                                                 * Reset in_vain because an ack
 421                                                 * for this commit has not been
 422                                                 * seen.
 423                                                 */
 424                                                in_vain = 0;
 425                                        } else if (!args->stateless_rpc
 426                                                   || ack != ACK_common)
 427                                                in_vain = 0;
 428                                        retval = 0;
 429                                        got_continue = 1;
 430                                        if (ack == ACK_ready)
 431                                                got_ready = 1;
 432                                        break;
 433                                        }
 434                                }
 435                        } while (ack);
 436                        flushes--;
 437                        if (got_continue && MAX_IN_VAIN < in_vain) {
 438                                print_verbose(args, _("giving up"));
 439                                break; /* give up */
 440                        }
 441                        if (got_ready)
 442                                break;
 443                }
 444        }
 445done:
 446        if (!got_ready || !no_done) {
 447                packet_buf_write(&req_buf, "done\n");
 448                send_request(args, fd[1], &req_buf);
 449        }
 450        print_verbose(args, _("done"));
 451        if (retval != 0) {
 452                multi_ack = 0;
 453                flushes++;
 454        }
 455        strbuf_release(&req_buf);
 456
 457        if (!got_ready || !no_done)
 458                consume_shallow_list(args, fd[0]);
 459        while (flushes || multi_ack) {
 460                int ack = get_ack(fd[0], result_oid);
 461                if (ack) {
 462                        print_verbose(args, _("got %s (%d) %s"), "ack",
 463                                      ack, oid_to_hex(result_oid));
 464                        if (ack == ACK)
 465                                return 0;
 466                        multi_ack = 1;
 467                        continue;
 468                }
 469                flushes--;
 470        }
 471        /* it is no error to fetch into a completely empty repo */
 472        return count ? retval : 0;
 473}
 474
 475static struct commit_list *complete;
 476
 477static int mark_complete(const struct object_id *oid)
 478{
 479        struct object *o = parse_object(oid);
 480
 481        while (o && o->type == OBJ_TAG) {
 482                struct tag *t = (struct tag *) o;
 483                if (!t->tagged)
 484                        break; /* broken repository */
 485                o->flags |= COMPLETE;
 486                o = parse_object(&t->tagged->oid);
 487        }
 488        if (o && o->type == OBJ_COMMIT) {
 489                struct commit *commit = (struct commit *)o;
 490                if (!(commit->object.flags & COMPLETE)) {
 491                        commit->object.flags |= COMPLETE;
 492                        commit_list_insert(commit, &complete);
 493                }
 494        }
 495        return 0;
 496}
 497
 498static int mark_complete_oid(const char *refname, const struct object_id *oid,
 499                             int flag, void *cb_data)
 500{
 501        return mark_complete(oid);
 502}
 503
 504static void mark_recent_complete_commits(struct fetch_pack_args *args,
 505                                         timestamp_t cutoff)
 506{
 507        while (complete && cutoff <= complete->item->date) {
 508                print_verbose(args, _("Marking %s as complete"),
 509                              oid_to_hex(&complete->item->object.oid));
 510                pop_most_recent_commit(&complete, COMPLETE);
 511        }
 512}
 513
 514static void add_refs_to_oidset(struct oidset *oids, struct ref *refs)
 515{
 516        for (; refs; refs = refs->next)
 517                oidset_insert(oids, &refs->old_oid);
 518}
 519
 520static int tip_oids_contain(struct oidset *tip_oids,
 521                            struct ref *unmatched, struct ref *newlist,
 522                            const struct object_id *id)
 523{
 524        /*
 525         * Note that this only looks at the ref lists the first time it's
 526         * called. This works out in filter_refs() because even though it may
 527         * add to "newlist" between calls, the additions will always be for
 528         * oids that are already in the set.
 529         */
 530        if (!tip_oids->map.map.tablesize) {
 531                add_refs_to_oidset(tip_oids, unmatched);
 532                add_refs_to_oidset(tip_oids, newlist);
 533        }
 534        return oidset_contains(tip_oids, id);
 535}
 536
 537static void filter_refs(struct fetch_pack_args *args,
 538                        struct ref **refs,
 539                        struct ref **sought, int nr_sought)
 540{
 541        struct ref *newlist = NULL;
 542        struct ref **newtail = &newlist;
 543        struct ref *unmatched = NULL;
 544        struct ref *ref, *next;
 545        struct oidset tip_oids = OIDSET_INIT;
 546        int i;
 547
 548        i = 0;
 549        for (ref = *refs; ref; ref = next) {
 550                int keep = 0;
 551                next = ref->next;
 552
 553                if (starts_with(ref->name, "refs/") &&
 554                    check_refname_format(ref->name, 0))
 555                        ; /* trash */
 556                else {
 557                        while (i < nr_sought) {
 558                                int cmp = strcmp(ref->name, sought[i]->name);
 559                                if (cmp < 0)
 560                                        break; /* definitely do not have it */
 561                                else if (cmp == 0) {
 562                                        keep = 1; /* definitely have it */
 563                                        sought[i]->match_status = REF_MATCHED;
 564                                }
 565                                i++;
 566                        }
 567                }
 568
 569                if (!keep && args->fetch_all &&
 570                    (!args->deepen || !starts_with(ref->name, "refs/tags/")))
 571                        keep = 1;
 572
 573                if (keep) {
 574                        *newtail = ref;
 575                        ref->next = NULL;
 576                        newtail = &ref->next;
 577                } else {
 578                        ref->next = unmatched;
 579                        unmatched = ref;
 580                }
 581        }
 582
 583        /* Append unmatched requests to the list */
 584        for (i = 0; i < nr_sought; i++) {
 585                struct object_id oid;
 586                const char *p;
 587
 588                ref = sought[i];
 589                if (ref->match_status != REF_NOT_MATCHED)
 590                        continue;
 591                if (parse_oid_hex(ref->name, &oid, &p) ||
 592                    *p != '\0' ||
 593                    oidcmp(&oid, &ref->old_oid))
 594                        continue;
 595
 596                if ((allow_unadvertised_object_request &
 597                     (ALLOW_TIP_SHA1 | ALLOW_REACHABLE_SHA1)) ||
 598                    tip_oids_contain(&tip_oids, unmatched, newlist,
 599                                     &ref->old_oid)) {
 600                        ref->match_status = REF_MATCHED;
 601                        *newtail = copy_ref(ref);
 602                        newtail = &(*newtail)->next;
 603                } else {
 604                        ref->match_status = REF_UNADVERTISED_NOT_ALLOWED;
 605                }
 606        }
 607
 608        oidset_clear(&tip_oids);
 609        for (ref = unmatched; ref; ref = next) {
 610                next = ref->next;
 611                free(ref);
 612        }
 613
 614        *refs = newlist;
 615}
 616
 617static void mark_alternate_complete(struct fetch_negotiator *unused,
 618                                    struct object *obj)
 619{
 620        mark_complete(&obj->oid);
 621}
 622
 623struct loose_object_iter {
 624        struct oidset *loose_object_set;
 625        struct ref *refs;
 626};
 627
 628/*
 629 *  If the number of refs is not larger than the number of loose objects,
 630 *  this function stops inserting.
 631 */
 632static int add_loose_objects_to_set(const struct object_id *oid,
 633                                    const char *path,
 634                                    void *data)
 635{
 636        struct loose_object_iter *iter = data;
 637        oidset_insert(iter->loose_object_set, oid);
 638        if (iter->refs == NULL)
 639                return 1;
 640
 641        iter->refs = iter->refs->next;
 642        return 0;
 643}
 644
 645/*
 646 * Mark recent commits available locally and reachable from a local ref as
 647 * COMPLETE. If args->no_dependents is false, also mark COMPLETE remote refs as
 648 * COMMON_REF (otherwise, we are not planning to participate in negotiation, and
 649 * thus do not need COMMON_REF marks).
 650 *
 651 * The cutoff time for recency is determined by this heuristic: it is the
 652 * earliest commit time of the objects in refs that are commits and that we know
 653 * the commit time of.
 654 */
 655static void mark_complete_and_common_ref(struct fetch_negotiator *negotiator,
 656                                         struct fetch_pack_args *args,
 657                                         struct ref **refs)
 658{
 659        struct ref *ref;
 660        int old_save_commit_buffer = save_commit_buffer;
 661        timestamp_t cutoff = 0;
 662        struct oidset loose_oid_set = OIDSET_INIT;
 663        int use_oidset = 0;
 664        struct loose_object_iter iter = {&loose_oid_set, *refs};
 665
 666        /* Enumerate all loose objects or know refs are not so many. */
 667        use_oidset = !for_each_loose_object(add_loose_objects_to_set,
 668                                            &iter, 0);
 669
 670        save_commit_buffer = 0;
 671
 672        for (ref = *refs; ref; ref = ref->next) {
 673                struct object *o;
 674                unsigned int flags = OBJECT_INFO_QUICK;
 675
 676                if (use_oidset &&
 677                    !oidset_contains(&loose_oid_set, &ref->old_oid)) {
 678                        /*
 679                         * I know this does not exist in the loose form,
 680                         * so check if it exists in a non-loose form.
 681                         */
 682                        flags |= OBJECT_INFO_IGNORE_LOOSE;
 683                }
 684
 685                if (!has_object_file_with_flags(&ref->old_oid, flags))
 686                        continue;
 687                o = parse_object(&ref->old_oid);
 688                if (!o)
 689                        continue;
 690
 691                /* We already have it -- which may mean that we were
 692                 * in sync with the other side at some time after
 693                 * that (it is OK if we guess wrong here).
 694                 */
 695                if (o->type == OBJ_COMMIT) {
 696                        struct commit *commit = (struct commit *)o;
 697                        if (!cutoff || cutoff < commit->date)
 698                                cutoff = commit->date;
 699                }
 700        }
 701
 702        oidset_clear(&loose_oid_set);
 703
 704        if (!args->no_dependents) {
 705                if (!args->deepen) {
 706                        for_each_ref(mark_complete_oid, NULL);
 707                        for_each_cached_alternate(NULL, mark_alternate_complete);
 708                        commit_list_sort_by_date(&complete);
 709                        if (cutoff)
 710                                mark_recent_complete_commits(args, cutoff);
 711                }
 712
 713                /*
 714                 * Mark all complete remote refs as common refs.
 715                 * Don't mark them common yet; the server has to be told so first.
 716                 */
 717                for (ref = *refs; ref; ref = ref->next) {
 718                        struct object *o = deref_tag(lookup_object(ref->old_oid.hash),
 719                                                     NULL, 0);
 720
 721                        if (!o || o->type != OBJ_COMMIT || !(o->flags & COMPLETE))
 722                                continue;
 723
 724                        negotiator->known_common(negotiator,
 725                                                 (struct commit *)o);
 726                }
 727        }
 728
 729        save_commit_buffer = old_save_commit_buffer;
 730}
 731
 732/*
 733 * Returns 1 if every object pointed to by the given remote refs is available
 734 * locally and reachable from a local ref, and 0 otherwise.
 735 */
 736static int everything_local(struct fetch_pack_args *args,
 737                            struct ref **refs)
 738{
 739        struct ref *ref;
 740        int retval;
 741
 742        for (retval = 1, ref = *refs; ref ; ref = ref->next) {
 743                const struct object_id *remote = &ref->old_oid;
 744                struct object *o;
 745
 746                o = lookup_object(remote->hash);
 747                if (!o || !(o->flags & COMPLETE)) {
 748                        retval = 0;
 749                        print_verbose(args, "want %s (%s)", oid_to_hex(remote),
 750                                      ref->name);
 751                        continue;
 752                }
 753                print_verbose(args, _("already have %s (%s)"), oid_to_hex(remote),
 754                              ref->name);
 755        }
 756
 757        return retval;
 758}
 759
 760static int sideband_demux(int in, int out, void *data)
 761{
 762        int *xd = data;
 763        int ret;
 764
 765        ret = recv_sideband("fetch-pack", xd[0], out);
 766        close(out);
 767        return ret;
 768}
 769
 770static int get_pack(struct fetch_pack_args *args,
 771                    int xd[2], char **pack_lockfile)
 772{
 773        struct async demux;
 774        int do_keep = args->keep_pack;
 775        const char *cmd_name;
 776        struct pack_header header;
 777        int pass_header = 0;
 778        struct child_process cmd = CHILD_PROCESS_INIT;
 779        int ret;
 780
 781        memset(&demux, 0, sizeof(demux));
 782        if (use_sideband) {
 783                /* xd[] is talking with upload-pack; subprocess reads from
 784                 * xd[0], spits out band#2 to stderr, and feeds us band#1
 785                 * through demux->out.
 786                 */
 787                demux.proc = sideband_demux;
 788                demux.data = xd;
 789                demux.out = -1;
 790                demux.isolate_sigpipe = 1;
 791                if (start_async(&demux))
 792                        die(_("fetch-pack: unable to fork off sideband demultiplexer"));
 793        }
 794        else
 795                demux.out = xd[0];
 796
 797        if (!args->keep_pack && unpack_limit) {
 798
 799                if (read_pack_header(demux.out, &header))
 800                        die(_("protocol error: bad pack header"));
 801                pass_header = 1;
 802                if (ntohl(header.hdr_entries) < unpack_limit)
 803                        do_keep = 0;
 804                else
 805                        do_keep = 1;
 806        }
 807
 808        if (alternate_shallow_file) {
 809                argv_array_push(&cmd.args, "--shallow-file");
 810                argv_array_push(&cmd.args, alternate_shallow_file);
 811        }
 812
 813        if (do_keep || args->from_promisor) {
 814                if (pack_lockfile)
 815                        cmd.out = -1;
 816                cmd_name = "index-pack";
 817                argv_array_push(&cmd.args, cmd_name);
 818                argv_array_push(&cmd.args, "--stdin");
 819                if (!args->quiet && !args->no_progress)
 820                        argv_array_push(&cmd.args, "-v");
 821                if (args->use_thin_pack)
 822                        argv_array_push(&cmd.args, "--fix-thin");
 823                if (do_keep && (args->lock_pack || unpack_limit)) {
 824                        char hostname[HOST_NAME_MAX + 1];
 825                        if (xgethostname(hostname, sizeof(hostname)))
 826                                xsnprintf(hostname, sizeof(hostname), "localhost");
 827                        argv_array_pushf(&cmd.args,
 828                                        "--keep=fetch-pack %"PRIuMAX " on %s",
 829                                        (uintmax_t)getpid(), hostname);
 830                }
 831                if (args->check_self_contained_and_connected)
 832                        argv_array_push(&cmd.args, "--check-self-contained-and-connected");
 833                if (args->from_promisor)
 834                        argv_array_push(&cmd.args, "--promisor");
 835        }
 836        else {
 837                cmd_name = "unpack-objects";
 838                argv_array_push(&cmd.args, cmd_name);
 839                if (args->quiet || args->no_progress)
 840                        argv_array_push(&cmd.args, "-q");
 841                args->check_self_contained_and_connected = 0;
 842        }
 843
 844        if (pass_header)
 845                argv_array_pushf(&cmd.args, "--pack_header=%"PRIu32",%"PRIu32,
 846                                 ntohl(header.hdr_version),
 847                                 ntohl(header.hdr_entries));
 848        if (fetch_fsck_objects >= 0
 849            ? fetch_fsck_objects
 850            : transfer_fsck_objects >= 0
 851            ? transfer_fsck_objects
 852            : 0) {
 853                if (args->from_promisor)
 854                        /*
 855                         * We cannot use --strict in index-pack because it
 856                         * checks both broken objects and links, but we only
 857                         * want to check for broken objects.
 858                         */
 859                        argv_array_push(&cmd.args, "--fsck-objects");
 860                else
 861                        argv_array_push(&cmd.args, "--strict");
 862        }
 863
 864        cmd.in = demux.out;
 865        cmd.git_cmd = 1;
 866        if (start_command(&cmd))
 867                die(_("fetch-pack: unable to fork off %s"), cmd_name);
 868        if (do_keep && pack_lockfile) {
 869                *pack_lockfile = index_pack_lockfile(cmd.out);
 870                close(cmd.out);
 871        }
 872
 873        if (!use_sideband)
 874                /* Closed by start_command() */
 875                xd[0] = -1;
 876
 877        ret = finish_command(&cmd);
 878        if (!ret || (args->check_self_contained_and_connected && ret == 1))
 879                args->self_contained_and_connected =
 880                        args->check_self_contained_and_connected &&
 881                        ret == 0;
 882        else
 883                die(_("%s failed"), cmd_name);
 884        if (use_sideband && finish_async(&demux))
 885                die(_("error in sideband demultiplexer"));
 886        return 0;
 887}
 888
 889static int cmp_ref_by_name(const void *a_, const void *b_)
 890{
 891        const struct ref *a = *((const struct ref **)a_);
 892        const struct ref *b = *((const struct ref **)b_);
 893        return strcmp(a->name, b->name);
 894}
 895
 896static struct ref *do_fetch_pack(struct fetch_pack_args *args,
 897                                 int fd[2],
 898                                 const struct ref *orig_ref,
 899                                 struct ref **sought, int nr_sought,
 900                                 struct shallow_info *si,
 901                                 char **pack_lockfile)
 902{
 903        struct ref *ref = copy_ref_list(orig_ref);
 904        struct object_id oid;
 905        const char *agent_feature;
 906        int agent_len;
 907        struct fetch_negotiator negotiator;
 908        fetch_negotiator_init(&negotiator);
 909
 910        sort_ref_list(&ref, ref_compare_name);
 911        QSORT(sought, nr_sought, cmp_ref_by_name);
 912
 913        if ((args->depth > 0 || is_repository_shallow()) && !server_supports("shallow"))
 914                die(_("Server does not support shallow clients"));
 915        if (args->depth > 0 || args->deepen_since || args->deepen_not)
 916                args->deepen = 1;
 917        if (server_supports("multi_ack_detailed")) {
 918                print_verbose(args, _("Server supports multi_ack_detailed"));
 919                multi_ack = 2;
 920                if (server_supports("no-done")) {
 921                        print_verbose(args, _("Server supports no-done"));
 922                        if (args->stateless_rpc)
 923                                no_done = 1;
 924                }
 925        }
 926        else if (server_supports("multi_ack")) {
 927                print_verbose(args, _("Server supports multi_ack"));
 928                multi_ack = 1;
 929        }
 930        if (server_supports("side-band-64k")) {
 931                print_verbose(args, _("Server supports side-band-64k"));
 932                use_sideband = 2;
 933        }
 934        else if (server_supports("side-band")) {
 935                print_verbose(args, _("Server supports side-band"));
 936                use_sideband = 1;
 937        }
 938        if (server_supports("allow-tip-sha1-in-want")) {
 939                print_verbose(args, _("Server supports allow-tip-sha1-in-want"));
 940                allow_unadvertised_object_request |= ALLOW_TIP_SHA1;
 941        }
 942        if (server_supports("allow-reachable-sha1-in-want")) {
 943                print_verbose(args, _("Server supports allow-reachable-sha1-in-want"));
 944                allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
 945        }
 946        if (!server_supports("thin-pack"))
 947                args->use_thin_pack = 0;
 948        if (!server_supports("no-progress"))
 949                args->no_progress = 0;
 950        if (!server_supports("include-tag"))
 951                args->include_tag = 0;
 952        if (server_supports("ofs-delta"))
 953                print_verbose(args, _("Server supports ofs-delta"));
 954        else
 955                prefer_ofs_delta = 0;
 956
 957        if (server_supports("filter")) {
 958                server_supports_filtering = 1;
 959                print_verbose(args, _("Server supports filter"));
 960        } else if (args->filter_options.choice) {
 961                warning("filtering not recognized by server, ignoring");
 962        }
 963
 964        if ((agent_feature = server_feature_value("agent", &agent_len))) {
 965                agent_supported = 1;
 966                if (agent_len)
 967                        print_verbose(args, _("Server version is %.*s"),
 968                                      agent_len, agent_feature);
 969        }
 970        if (server_supports("deepen-since"))
 971                deepen_since_ok = 1;
 972        else if (args->deepen_since)
 973                die(_("Server does not support --shallow-since"));
 974        if (server_supports("deepen-not"))
 975                deepen_not_ok = 1;
 976        else if (args->deepen_not)
 977                die(_("Server does not support --shallow-exclude"));
 978        if (!server_supports("deepen-relative") && args->deepen_relative)
 979                die(_("Server does not support --deepen"));
 980
 981        mark_complete_and_common_ref(&negotiator, args, &ref);
 982        filter_refs(args, &ref, sought, nr_sought);
 983        if (everything_local(args, &ref)) {
 984                packet_flush(fd[1]);
 985                goto all_done;
 986        }
 987        if (find_common(&negotiator, args, fd, &oid, ref) < 0)
 988                if (!args->keep_pack)
 989                        /* When cloning, it is not unusual to have
 990                         * no common commit.
 991                         */
 992                        warning(_("no common commits"));
 993
 994        if (args->stateless_rpc)
 995                packet_flush(fd[1]);
 996        if (args->deepen)
 997                setup_alternate_shallow(&shallow_lock, &alternate_shallow_file,
 998                                        NULL);
 999        else if (si->nr_ours || si->nr_theirs)
1000                alternate_shallow_file = setup_temporary_shallow(si->shallow);
1001        else
1002                alternate_shallow_file = NULL;
1003        if (get_pack(args, fd, pack_lockfile))
1004                die(_("git fetch-pack: fetch failed."));
1005
1006 all_done:
1007        negotiator.release(&negotiator);
1008        return ref;
1009}
1010
1011static void add_shallow_requests(struct strbuf *req_buf,
1012                                 const struct fetch_pack_args *args)
1013{
1014        if (is_repository_shallow())
1015                write_shallow_commits(req_buf, 1, NULL);
1016        if (args->depth > 0)
1017                packet_buf_write(req_buf, "deepen %d", args->depth);
1018        if (args->deepen_since) {
1019                timestamp_t max_age = approxidate(args->deepen_since);
1020                packet_buf_write(req_buf, "deepen-since %"PRItime, max_age);
1021        }
1022        if (args->deepen_not) {
1023                int i;
1024                for (i = 0; i < args->deepen_not->nr; i++) {
1025                        struct string_list_item *s = args->deepen_not->items + i;
1026                        packet_buf_write(req_buf, "deepen-not %s", s->string);
1027                }
1028        }
1029}
1030
1031static void add_wants(const struct ref *wants, struct strbuf *req_buf)
1032{
1033        for ( ; wants ; wants = wants->next) {
1034                const struct object_id *remote = &wants->old_oid;
1035                const char *remote_hex;
1036                struct object *o;
1037
1038                /*
1039                 * If that object is complete (i.e. it is an ancestor of a
1040                 * local ref), we tell them we have it but do not have to
1041                 * tell them about its ancestors, which they already know
1042                 * about.
1043                 *
1044                 * We use lookup_object here because we are only
1045                 * interested in the case we *know* the object is
1046                 * reachable and we have already scanned it.
1047                 */
1048                if (((o = lookup_object(remote->hash)) != NULL) &&
1049                    (o->flags & COMPLETE)) {
1050                        continue;
1051                }
1052
1053                remote_hex = oid_to_hex(remote);
1054                packet_buf_write(req_buf, "want %s\n", remote_hex);
1055        }
1056}
1057
1058static void add_common(struct strbuf *req_buf, struct oidset *common)
1059{
1060        struct oidset_iter iter;
1061        const struct object_id *oid;
1062        oidset_iter_init(common, &iter);
1063
1064        while ((oid = oidset_iter_next(&iter))) {
1065                packet_buf_write(req_buf, "have %s\n", oid_to_hex(oid));
1066        }
1067}
1068
1069static int add_haves(struct fetch_negotiator *negotiator,
1070                     struct strbuf *req_buf,
1071                     int *haves_to_send, int *in_vain)
1072{
1073        int ret = 0;
1074        int haves_added = 0;
1075        const struct object_id *oid;
1076
1077        while ((oid = negotiator->next(negotiator))) {
1078                packet_buf_write(req_buf, "have %s\n", oid_to_hex(oid));
1079                if (++haves_added >= *haves_to_send)
1080                        break;
1081        }
1082
1083        *in_vain += haves_added;
1084        if (!haves_added || *in_vain >= MAX_IN_VAIN) {
1085                /* Send Done */
1086                packet_buf_write(req_buf, "done\n");
1087                ret = 1;
1088        }
1089
1090        /* Increase haves to send on next round */
1091        *haves_to_send = next_flush(1, *haves_to_send);
1092
1093        return ret;
1094}
1095
1096static int send_fetch_request(struct fetch_negotiator *negotiator, int fd_out,
1097                              const struct fetch_pack_args *args,
1098                              const struct ref *wants, struct oidset *common,
1099                              int *haves_to_send, int *in_vain)
1100{
1101        int ret = 0;
1102        struct strbuf req_buf = STRBUF_INIT;
1103
1104        if (server_supports_v2("fetch", 1))
1105                packet_buf_write(&req_buf, "command=fetch");
1106        if (server_supports_v2("agent", 0))
1107                packet_buf_write(&req_buf, "agent=%s", git_user_agent_sanitized());
1108        if (args->server_options && args->server_options->nr &&
1109            server_supports_v2("server-option", 1)) {
1110                int i;
1111                for (i = 0; i < args->server_options->nr; i++)
1112                        packet_write_fmt(fd_out, "server-option=%s",
1113                                         args->server_options->items[i].string);
1114        }
1115
1116        packet_buf_delim(&req_buf);
1117        if (args->use_thin_pack)
1118                packet_buf_write(&req_buf, "thin-pack");
1119        if (args->no_progress)
1120                packet_buf_write(&req_buf, "no-progress");
1121        if (args->include_tag)
1122                packet_buf_write(&req_buf, "include-tag");
1123        if (prefer_ofs_delta)
1124                packet_buf_write(&req_buf, "ofs-delta");
1125
1126        /* Add shallow-info and deepen request */
1127        if (server_supports_feature("fetch", "shallow", 0))
1128                add_shallow_requests(&req_buf, args);
1129        else if (is_repository_shallow() || args->deepen)
1130                die(_("Server does not support shallow requests"));
1131
1132        /* Add filter */
1133        if (server_supports_feature("fetch", "filter", 0) &&
1134            args->filter_options.choice) {
1135                print_verbose(args, _("Server supports filter"));
1136                packet_buf_write(&req_buf, "filter %s",
1137                                 args->filter_options.filter_spec);
1138        } else if (args->filter_options.choice) {
1139                warning("filtering not recognized by server, ignoring");
1140        }
1141
1142        /* add wants */
1143        add_wants(wants, &req_buf);
1144
1145        if (args->no_dependents) {
1146                packet_buf_write(&req_buf, "done");
1147                ret = 1;
1148        } else {
1149                /* Add all of the common commits we've found in previous rounds */
1150                add_common(&req_buf, common);
1151
1152                /* Add initial haves */
1153                ret = add_haves(negotiator, &req_buf, haves_to_send, in_vain);
1154        }
1155
1156        /* Send request */
1157        packet_buf_flush(&req_buf);
1158        write_or_die(fd_out, req_buf.buf, req_buf.len);
1159
1160        strbuf_release(&req_buf);
1161        return ret;
1162}
1163
1164/*
1165 * Processes a section header in a server's response and checks if it matches
1166 * `section`.  If the value of `peek` is 1, the header line will be peeked (and
1167 * not consumed); if 0, the line will be consumed and the function will die if
1168 * the section header doesn't match what was expected.
1169 */
1170static int process_section_header(struct packet_reader *reader,
1171                                  const char *section, int peek)
1172{
1173        int ret;
1174
1175        if (packet_reader_peek(reader) != PACKET_READ_NORMAL)
1176                die("error reading section header '%s'", section);
1177
1178        ret = !strcmp(reader->line, section);
1179
1180        if (!peek) {
1181                if (!ret)
1182                        die("expected '%s', received '%s'",
1183                            section, reader->line);
1184                packet_reader_read(reader);
1185        }
1186
1187        return ret;
1188}
1189
1190static int process_acks(struct fetch_negotiator *negotiator,
1191                        struct packet_reader *reader,
1192                        struct oidset *common)
1193{
1194        /* received */
1195        int received_ready = 0;
1196        int received_ack = 0;
1197
1198        process_section_header(reader, "acknowledgments", 0);
1199        while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1200                const char *arg;
1201
1202                if (!strcmp(reader->line, "NAK"))
1203                        continue;
1204
1205                if (skip_prefix(reader->line, "ACK ", &arg)) {
1206                        struct object_id oid;
1207                        if (!get_oid_hex(arg, &oid)) {
1208                                struct commit *commit;
1209                                oidset_insert(common, &oid);
1210                                commit = lookup_commit(&oid);
1211                                negotiator->ack(negotiator, commit);
1212                        }
1213                        continue;
1214                }
1215
1216                if (!strcmp(reader->line, "ready")) {
1217                        received_ready = 1;
1218                        continue;
1219                }
1220
1221                die("unexpected acknowledgment line: '%s'", reader->line);
1222        }
1223
1224        if (reader->status != PACKET_READ_FLUSH &&
1225            reader->status != PACKET_READ_DELIM)
1226                die("error processing acks: %d", reader->status);
1227
1228        /* return 0 if no common, 1 if there are common, or 2 if ready */
1229        return received_ready ? 2 : (received_ack ? 1 : 0);
1230}
1231
1232static void receive_shallow_info(struct fetch_pack_args *args,
1233                                 struct packet_reader *reader)
1234{
1235        process_section_header(reader, "shallow-info", 0);
1236        while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1237                const char *arg;
1238                struct object_id oid;
1239
1240                if (skip_prefix(reader->line, "shallow ", &arg)) {
1241                        if (get_oid_hex(arg, &oid))
1242                                die(_("invalid shallow line: %s"), reader->line);
1243                        register_shallow(&oid);
1244                        continue;
1245                }
1246                if (skip_prefix(reader->line, "unshallow ", &arg)) {
1247                        if (get_oid_hex(arg, &oid))
1248                                die(_("invalid unshallow line: %s"), reader->line);
1249                        if (!lookup_object(oid.hash))
1250                                die(_("object not found: %s"), reader->line);
1251                        /* make sure that it is parsed as shallow */
1252                        if (!parse_object(&oid))
1253                                die(_("error in object: %s"), reader->line);
1254                        if (unregister_shallow(&oid))
1255                                die(_("no shallow found: %s"), reader->line);
1256                        continue;
1257                }
1258                die(_("expected shallow/unshallow, got %s"), reader->line);
1259        }
1260
1261        if (reader->status != PACKET_READ_FLUSH &&
1262            reader->status != PACKET_READ_DELIM)
1263                die("error processing shallow info: %d", reader->status);
1264
1265        setup_alternate_shallow(&shallow_lock, &alternate_shallow_file, NULL);
1266        args->deepen = 1;
1267}
1268
1269enum fetch_state {
1270        FETCH_CHECK_LOCAL = 0,
1271        FETCH_SEND_REQUEST,
1272        FETCH_PROCESS_ACKS,
1273        FETCH_GET_PACK,
1274        FETCH_DONE,
1275};
1276
1277static struct ref *do_fetch_pack_v2(struct fetch_pack_args *args,
1278                                    int fd[2],
1279                                    const struct ref *orig_ref,
1280                                    struct ref **sought, int nr_sought,
1281                                    char **pack_lockfile)
1282{
1283        struct ref *ref = copy_ref_list(orig_ref);
1284        enum fetch_state state = FETCH_CHECK_LOCAL;
1285        struct oidset common = OIDSET_INIT;
1286        struct packet_reader reader;
1287        int in_vain = 0;
1288        int haves_to_send = INITIAL_FLUSH;
1289        struct fetch_negotiator negotiator;
1290        fetch_negotiator_init(&negotiator);
1291        packet_reader_init(&reader, fd[0], NULL, 0,
1292                           PACKET_READ_CHOMP_NEWLINE);
1293
1294        while (state != FETCH_DONE) {
1295                switch (state) {
1296                case FETCH_CHECK_LOCAL:
1297                        sort_ref_list(&ref, ref_compare_name);
1298                        QSORT(sought, nr_sought, cmp_ref_by_name);
1299
1300                        /* v2 supports these by default */
1301                        allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
1302                        use_sideband = 2;
1303                        if (args->depth > 0 || args->deepen_since || args->deepen_not)
1304                                args->deepen = 1;
1305
1306                        /* Filter 'ref' by 'sought' and those that aren't local */
1307                        mark_complete_and_common_ref(&negotiator, args, &ref);
1308                        filter_refs(args, &ref, sought, nr_sought);
1309                        if (everything_local(args, &ref))
1310                                state = FETCH_DONE;
1311                        else
1312                                state = FETCH_SEND_REQUEST;
1313
1314                        mark_tips(&negotiator, args->negotiation_tips);
1315                        for_each_cached_alternate(&negotiator,
1316                                                  insert_one_alternate_object);
1317                        break;
1318                case FETCH_SEND_REQUEST:
1319                        if (send_fetch_request(&negotiator, fd[1], args, ref,
1320                                               &common,
1321                                               &haves_to_send, &in_vain))
1322                                state = FETCH_GET_PACK;
1323                        else
1324                                state = FETCH_PROCESS_ACKS;
1325                        break;
1326                case FETCH_PROCESS_ACKS:
1327                        /* Process ACKs/NAKs */
1328                        switch (process_acks(&negotiator, &reader, &common)) {
1329                        case 2:
1330                                state = FETCH_GET_PACK;
1331                                break;
1332                        case 1:
1333                                in_vain = 0;
1334                                /* fallthrough */
1335                        default:
1336                                state = FETCH_SEND_REQUEST;
1337                                break;
1338                        }
1339                        break;
1340                case FETCH_GET_PACK:
1341                        /* Check for shallow-info section */
1342                        if (process_section_header(&reader, "shallow-info", 1))
1343                                receive_shallow_info(args, &reader);
1344
1345                        /* get the pack */
1346                        process_section_header(&reader, "packfile", 0);
1347                        if (get_pack(args, fd, pack_lockfile))
1348                                die(_("git fetch-pack: fetch failed."));
1349
1350                        state = FETCH_DONE;
1351                        break;
1352                case FETCH_DONE:
1353                        continue;
1354                }
1355        }
1356
1357        negotiator.release(&negotiator);
1358        oidset_clear(&common);
1359        return ref;
1360}
1361
1362static void fetch_pack_config(void)
1363{
1364        git_config_get_int("fetch.unpacklimit", &fetch_unpack_limit);
1365        git_config_get_int("transfer.unpacklimit", &transfer_unpack_limit);
1366        git_config_get_bool("repack.usedeltabaseoffset", &prefer_ofs_delta);
1367        git_config_get_bool("fetch.fsckobjects", &fetch_fsck_objects);
1368        git_config_get_bool("transfer.fsckobjects", &transfer_fsck_objects);
1369
1370        git_config(git_default_config, NULL);
1371}
1372
1373static void fetch_pack_setup(void)
1374{
1375        static int did_setup;
1376        if (did_setup)
1377                return;
1378        fetch_pack_config();
1379        if (0 <= transfer_unpack_limit)
1380                unpack_limit = transfer_unpack_limit;
1381        else if (0 <= fetch_unpack_limit)
1382                unpack_limit = fetch_unpack_limit;
1383        did_setup = 1;
1384}
1385
1386static int remove_duplicates_in_refs(struct ref **ref, int nr)
1387{
1388        struct string_list names = STRING_LIST_INIT_NODUP;
1389        int src, dst;
1390
1391        for (src = dst = 0; src < nr; src++) {
1392                struct string_list_item *item;
1393                item = string_list_insert(&names, ref[src]->name);
1394                if (item->util)
1395                        continue; /* already have it */
1396                item->util = ref[src];
1397                if (src != dst)
1398                        ref[dst] = ref[src];
1399                dst++;
1400        }
1401        for (src = dst; src < nr; src++)
1402                ref[src] = NULL;
1403        string_list_clear(&names, 0);
1404        return dst;
1405}
1406
1407static void update_shallow(struct fetch_pack_args *args,
1408                           struct ref **sought, int nr_sought,
1409                           struct shallow_info *si)
1410{
1411        struct oid_array ref = OID_ARRAY_INIT;
1412        int *status;
1413        int i;
1414
1415        if (args->deepen && alternate_shallow_file) {
1416                if (*alternate_shallow_file == '\0') { /* --unshallow */
1417                        unlink_or_warn(git_path_shallow());
1418                        rollback_lock_file(&shallow_lock);
1419                } else
1420                        commit_lock_file(&shallow_lock);
1421                return;
1422        }
1423
1424        if (!si->shallow || !si->shallow->nr)
1425                return;
1426
1427        if (args->cloning) {
1428                /*
1429                 * remote is shallow, but this is a clone, there are
1430                 * no objects in repo to worry about. Accept any
1431                 * shallow points that exist in the pack (iow in repo
1432                 * after get_pack() and reprepare_packed_git())
1433                 */
1434                struct oid_array extra = OID_ARRAY_INIT;
1435                struct object_id *oid = si->shallow->oid;
1436                for (i = 0; i < si->shallow->nr; i++)
1437                        if (has_object_file(&oid[i]))
1438                                oid_array_append(&extra, &oid[i]);
1439                if (extra.nr) {
1440                        setup_alternate_shallow(&shallow_lock,
1441                                                &alternate_shallow_file,
1442                                                &extra);
1443                        commit_lock_file(&shallow_lock);
1444                }
1445                oid_array_clear(&extra);
1446                return;
1447        }
1448
1449        if (!si->nr_ours && !si->nr_theirs)
1450                return;
1451
1452        remove_nonexistent_theirs_shallow(si);
1453        if (!si->nr_ours && !si->nr_theirs)
1454                return;
1455        for (i = 0; i < nr_sought; i++)
1456                oid_array_append(&ref, &sought[i]->old_oid);
1457        si->ref = &ref;
1458
1459        if (args->update_shallow) {
1460                /*
1461                 * remote is also shallow, .git/shallow may be updated
1462                 * so all refs can be accepted. Make sure we only add
1463                 * shallow roots that are actually reachable from new
1464                 * refs.
1465                 */
1466                struct oid_array extra = OID_ARRAY_INIT;
1467                struct object_id *oid = si->shallow->oid;
1468                assign_shallow_commits_to_refs(si, NULL, NULL);
1469                if (!si->nr_ours && !si->nr_theirs) {
1470                        oid_array_clear(&ref);
1471                        return;
1472                }
1473                for (i = 0; i < si->nr_ours; i++)
1474                        oid_array_append(&extra, &oid[si->ours[i]]);
1475                for (i = 0; i < si->nr_theirs; i++)
1476                        oid_array_append(&extra, &oid[si->theirs[i]]);
1477                setup_alternate_shallow(&shallow_lock,
1478                                        &alternate_shallow_file,
1479                                        &extra);
1480                commit_lock_file(&shallow_lock);
1481                oid_array_clear(&extra);
1482                oid_array_clear(&ref);
1483                return;
1484        }
1485
1486        /*
1487         * remote is also shallow, check what ref is safe to update
1488         * without updating .git/shallow
1489         */
1490        status = xcalloc(nr_sought, sizeof(*status));
1491        assign_shallow_commits_to_refs(si, NULL, status);
1492        if (si->nr_ours || si->nr_theirs) {
1493                for (i = 0; i < nr_sought; i++)
1494                        if (status[i])
1495                                sought[i]->status = REF_STATUS_REJECT_SHALLOW;
1496        }
1497        free(status);
1498        oid_array_clear(&ref);
1499}
1500
1501struct ref *fetch_pack(struct fetch_pack_args *args,
1502                       int fd[], struct child_process *conn,
1503                       const struct ref *ref,
1504                       const char *dest,
1505                       struct ref **sought, int nr_sought,
1506                       struct oid_array *shallow,
1507                       char **pack_lockfile,
1508                       enum protocol_version version)
1509{
1510        struct ref *ref_cpy;
1511        struct shallow_info si;
1512
1513        fetch_pack_setup();
1514        if (nr_sought)
1515                nr_sought = remove_duplicates_in_refs(sought, nr_sought);
1516
1517        if (!ref) {
1518                packet_flush(fd[1]);
1519                die(_("no matching remote head"));
1520        }
1521        prepare_shallow_info(&si, shallow);
1522        if (version == protocol_v2)
1523                ref_cpy = do_fetch_pack_v2(args, fd, ref, sought, nr_sought,
1524                                           pack_lockfile);
1525        else
1526                ref_cpy = do_fetch_pack(args, fd, ref, sought, nr_sought,
1527                                        &si, pack_lockfile);
1528        reprepare_packed_git(the_repository);
1529        update_shallow(args, sought, nr_sought, &si);
1530        clear_shallow_info(&si);
1531        return ref_cpy;
1532}
1533
1534int report_unmatched_refs(struct ref **sought, int nr_sought)
1535{
1536        int i, ret = 0;
1537
1538        for (i = 0; i < nr_sought; i++) {
1539                if (!sought[i])
1540                        continue;
1541                switch (sought[i]->match_status) {
1542                case REF_MATCHED:
1543                        continue;
1544                case REF_NOT_MATCHED:
1545                        error(_("no such remote ref %s"), sought[i]->name);
1546                        break;
1547                case REF_UNADVERTISED_NOT_ALLOWED:
1548                        error(_("Server does not allow request for unadvertised object %s"),
1549                              sought[i]->name);
1550                        break;
1551                }
1552                ret = 1;
1553        }
1554        return ret;
1555}