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