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