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