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