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