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