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