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