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