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