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