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