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