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