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