pack-bitmap.c: fix formatting of error messages
[alt-git.git] / fetch-pack.c
blob4e1e88eea097dde85dbbe200ed28d2886a5f2dca
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 #include "sigchain.h"
30 static int transfer_unpack_limit = -1;
31 static int fetch_unpack_limit = -1;
32 static int unpack_limit = 100;
33 static int prefer_ofs_delta = 1;
34 static int no_done;
35 static int deepen_since_ok;
36 static int deepen_not_ok;
37 static int fetch_fsck_objects = -1;
38 static int transfer_fsck_objects = -1;
39 static int agent_supported;
40 static int server_supports_filtering;
41 static int advertise_sid;
42 static struct shallow_lock shallow_lock;
43 static const char *alternate_shallow_file;
44 static struct fsck_options fsck_options = FSCK_OPTIONS_MISSING_GITMODULES;
45 static struct strbuf fsck_msg_types = STRBUF_INIT;
46 static struct string_list uri_protocols = STRING_LIST_INIT_DUP;
48 /* Remember to update object flag allocation in object.h */
49 #define COMPLETE (1U << 0)
50 #define ALTERNATE (1U << 1)
51 #define COMMON (1U << 6)
52 #define REACH_SCRATCH (1U << 7)
55 * After sending this many "have"s if we do not get any new ACK , we
56 * give up traversing our history.
58 #define MAX_IN_VAIN 256
60 static int multi_ack, use_sideband;
61 /* Allow specifying sha1 if it is a ref tip. */
62 #define ALLOW_TIP_SHA1 01
63 /* Allow request of a sha1 if it is reachable from a ref (possibly hidden ref). */
64 #define ALLOW_REACHABLE_SHA1 02
65 static unsigned int allow_unadvertised_object_request;
67 __attribute__((format (printf, 2, 3)))
68 static inline void print_verbose(const struct fetch_pack_args *args,
69 const char *fmt, ...)
71 va_list params;
73 if (!args->verbose)
74 return;
76 va_start(params, fmt);
77 vfprintf(stderr, fmt, params);
78 va_end(params);
79 fputc('\n', stderr);
82 struct alternate_object_cache {
83 struct object **items;
84 size_t nr, alloc;
87 static void cache_one_alternate(const struct object_id *oid,
88 void *vcache)
90 struct alternate_object_cache *cache = vcache;
91 struct object *obj = parse_object(the_repository, oid);
93 if (!obj || (obj->flags & ALTERNATE))
94 return;
96 obj->flags |= ALTERNATE;
97 ALLOC_GROW(cache->items, cache->nr + 1, cache->alloc);
98 cache->items[cache->nr++] = obj;
101 static void for_each_cached_alternate(struct fetch_negotiator *negotiator,
102 void (*cb)(struct fetch_negotiator *,
103 struct object *))
105 static int initialized;
106 static struct alternate_object_cache cache;
107 size_t i;
109 if (!initialized) {
110 for_each_alternate_ref(cache_one_alternate, &cache);
111 initialized = 1;
114 for (i = 0; i < cache.nr; i++)
115 cb(negotiator, cache.items[i]);
118 static struct commit *deref_without_lazy_fetch(const struct object_id *oid,
119 int mark_tags_complete)
121 enum object_type type;
122 struct object_info info = { .typep = &type };
123 struct commit *commit;
125 commit = lookup_commit_in_graph(the_repository, oid);
126 if (commit)
127 return commit;
129 while (1) {
130 if (oid_object_info_extended(the_repository, oid, &info,
131 OBJECT_INFO_SKIP_FETCH_OBJECT | OBJECT_INFO_QUICK))
132 return NULL;
133 if (type == OBJ_TAG) {
134 struct tag *tag = (struct tag *)
135 parse_object(the_repository, oid);
137 if (!tag->tagged)
138 return NULL;
139 if (mark_tags_complete)
140 tag->object.flags |= COMPLETE;
141 oid = &tag->tagged->oid;
142 } else {
143 break;
147 if (type == OBJ_COMMIT) {
148 struct commit *commit = lookup_commit(the_repository, oid);
149 if (!commit || repo_parse_commit(the_repository, commit))
150 return NULL;
151 return commit;
154 return NULL;
157 static int rev_list_insert_ref(struct fetch_negotiator *negotiator,
158 const struct object_id *oid)
160 struct commit *c = deref_without_lazy_fetch(oid, 0);
162 if (c)
163 negotiator->add_tip(negotiator, c);
164 return 0;
167 static int rev_list_insert_ref_oid(const char *refname, const struct object_id *oid,
168 int flag, void *cb_data)
170 return rev_list_insert_ref(cb_data, oid);
173 enum ack_type {
174 NAK = 0,
175 ACK,
176 ACK_continue,
177 ACK_common,
178 ACK_ready
181 static void consume_shallow_list(struct fetch_pack_args *args,
182 struct packet_reader *reader)
184 if (args->stateless_rpc && args->deepen) {
185 /* If we sent a depth we will get back "duplicate"
186 * shallow and unshallow commands every time there
187 * is a block of have lines exchanged.
189 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
190 if (starts_with(reader->line, "shallow "))
191 continue;
192 if (starts_with(reader->line, "unshallow "))
193 continue;
194 die(_("git fetch-pack: expected shallow list"));
196 if (reader->status != PACKET_READ_FLUSH)
197 die(_("git fetch-pack: expected a flush packet after shallow list"));
201 static enum ack_type get_ack(struct packet_reader *reader,
202 struct object_id *result_oid)
204 int len;
205 const char *arg;
207 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
208 die(_("git fetch-pack: expected ACK/NAK, got a flush packet"));
209 len = reader->pktlen;
211 if (!strcmp(reader->line, "NAK"))
212 return NAK;
213 if (skip_prefix(reader->line, "ACK ", &arg)) {
214 const char *p;
215 if (!parse_oid_hex(arg, result_oid, &p)) {
216 len -= p - reader->line;
217 if (len < 1)
218 return ACK;
219 if (strstr(p, "continue"))
220 return ACK_continue;
221 if (strstr(p, "common"))
222 return ACK_common;
223 if (strstr(p, "ready"))
224 return ACK_ready;
225 return ACK;
228 die(_("git fetch-pack: expected ACK/NAK, got '%s'"), reader->line);
231 static void send_request(struct fetch_pack_args *args,
232 int fd, struct strbuf *buf)
234 if (args->stateless_rpc) {
235 send_sideband(fd, -1, buf->buf, buf->len, LARGE_PACKET_MAX);
236 packet_flush(fd);
237 } else {
238 if (write_in_full(fd, buf->buf, buf->len) < 0)
239 die_errno(_("unable to write to remote"));
243 static void insert_one_alternate_object(struct fetch_negotiator *negotiator,
244 struct object *obj)
246 rev_list_insert_ref(negotiator, &obj->oid);
249 #define INITIAL_FLUSH 16
250 #define PIPESAFE_FLUSH 32
251 #define LARGE_FLUSH 16384
253 static int next_flush(int stateless_rpc, int count)
255 if (stateless_rpc) {
256 if (count < LARGE_FLUSH)
257 count <<= 1;
258 else
259 count = count * 11 / 10;
260 } else {
261 if (count < PIPESAFE_FLUSH)
262 count <<= 1;
263 else
264 count += PIPESAFE_FLUSH;
266 return count;
269 static void mark_tips(struct fetch_negotiator *negotiator,
270 const struct oid_array *negotiation_tips)
272 int i;
274 if (!negotiation_tips) {
275 for_each_rawref(rev_list_insert_ref_oid, negotiator);
276 return;
279 for (i = 0; i < negotiation_tips->nr; i++)
280 rev_list_insert_ref(negotiator, &negotiation_tips->oid[i]);
281 return;
284 static int find_common(struct fetch_negotiator *negotiator,
285 struct fetch_pack_args *args,
286 int fd[2], struct object_id *result_oid,
287 struct ref *refs)
289 int fetching;
290 int count = 0, flushes = 0, flush_at = INITIAL_FLUSH, retval;
291 const struct object_id *oid;
292 unsigned in_vain = 0;
293 int got_continue = 0;
294 int got_ready = 0;
295 struct strbuf req_buf = STRBUF_INIT;
296 size_t state_len = 0;
297 struct packet_reader reader;
299 if (args->stateless_rpc && multi_ack == 1)
300 die(_("the option '%s' requires '%s'"), "--stateless-rpc", "multi_ack_detailed");
302 packet_reader_init(&reader, fd[0], NULL, 0,
303 PACKET_READ_CHOMP_NEWLINE |
304 PACKET_READ_DIE_ON_ERR_PACKET);
306 mark_tips(negotiator, args->negotiation_tips);
307 for_each_cached_alternate(negotiator, insert_one_alternate_object);
309 fetching = 0;
310 for ( ; refs ; refs = refs->next) {
311 struct object_id *remote = &refs->old_oid;
312 const char *remote_hex;
313 struct object *o;
315 if (!args->refetch) {
317 * If that object is complete (i.e. it is an ancestor of a
318 * local ref), we tell them we have it but do not have to
319 * tell them about its ancestors, which they already know
320 * about.
322 * We use lookup_object here because we are only
323 * interested in the case we *know* the object is
324 * reachable and we have already scanned it.
326 if (((o = lookup_object(the_repository, remote)) != NULL) &&
327 (o->flags & COMPLETE)) {
328 continue;
332 remote_hex = oid_to_hex(remote);
333 if (!fetching) {
334 struct strbuf c = STRBUF_INIT;
335 if (multi_ack == 2) strbuf_addstr(&c, " multi_ack_detailed");
336 if (multi_ack == 1) strbuf_addstr(&c, " multi_ack");
337 if (no_done) strbuf_addstr(&c, " no-done");
338 if (use_sideband == 2) strbuf_addstr(&c, " side-band-64k");
339 if (use_sideband == 1) strbuf_addstr(&c, " side-band");
340 if (args->deepen_relative) strbuf_addstr(&c, " deepen-relative");
341 if (args->use_thin_pack) strbuf_addstr(&c, " thin-pack");
342 if (args->no_progress) strbuf_addstr(&c, " no-progress");
343 if (args->include_tag) strbuf_addstr(&c, " include-tag");
344 if (prefer_ofs_delta) strbuf_addstr(&c, " ofs-delta");
345 if (deepen_since_ok) strbuf_addstr(&c, " deepen-since");
346 if (deepen_not_ok) strbuf_addstr(&c, " deepen-not");
347 if (agent_supported) strbuf_addf(&c, " agent=%s",
348 git_user_agent_sanitized());
349 if (advertise_sid)
350 strbuf_addf(&c, " session-id=%s", trace2_session_id());
351 if (args->filter_options.choice)
352 strbuf_addstr(&c, " filter");
353 packet_buf_write(&req_buf, "want %s%s\n", remote_hex, c.buf);
354 strbuf_release(&c);
355 } else
356 packet_buf_write(&req_buf, "want %s\n", remote_hex);
357 fetching++;
360 if (!fetching) {
361 strbuf_release(&req_buf);
362 packet_flush(fd[1]);
363 return 1;
366 if (is_repository_shallow(the_repository))
367 write_shallow_commits(&req_buf, 1, NULL);
368 if (args->depth > 0)
369 packet_buf_write(&req_buf, "deepen %d", args->depth);
370 if (args->deepen_since) {
371 timestamp_t max_age = approxidate(args->deepen_since);
372 packet_buf_write(&req_buf, "deepen-since %"PRItime, max_age);
374 if (args->deepen_not) {
375 int i;
376 for (i = 0; i < args->deepen_not->nr; i++) {
377 struct string_list_item *s = args->deepen_not->items + i;
378 packet_buf_write(&req_buf, "deepen-not %s", s->string);
381 if (server_supports_filtering && args->filter_options.choice) {
382 const char *spec =
383 expand_list_objects_filter_spec(&args->filter_options);
384 packet_buf_write(&req_buf, "filter %s", spec);
386 packet_buf_flush(&req_buf);
387 state_len = req_buf.len;
389 if (args->deepen) {
390 const char *arg;
391 struct object_id oid;
393 send_request(args, fd[1], &req_buf);
394 while (packet_reader_read(&reader) == PACKET_READ_NORMAL) {
395 if (skip_prefix(reader.line, "shallow ", &arg)) {
396 if (get_oid_hex(arg, &oid))
397 die(_("invalid shallow line: %s"), reader.line);
398 register_shallow(the_repository, &oid);
399 continue;
401 if (skip_prefix(reader.line, "unshallow ", &arg)) {
402 if (get_oid_hex(arg, &oid))
403 die(_("invalid unshallow line: %s"), reader.line);
404 if (!lookup_object(the_repository, &oid))
405 die(_("object not found: %s"), reader.line);
406 /* make sure that it is parsed as shallow */
407 if (!parse_object(the_repository, &oid))
408 die(_("error in object: %s"), reader.line);
409 if (unregister_shallow(&oid))
410 die(_("no shallow found: %s"), reader.line);
411 continue;
413 die(_("expected shallow/unshallow, got %s"), reader.line);
415 } else if (!args->stateless_rpc)
416 send_request(args, fd[1], &req_buf);
418 if (!args->stateless_rpc) {
419 /* If we aren't using the stateless-rpc interface
420 * we don't need to retain the headers.
422 strbuf_setlen(&req_buf, 0);
423 state_len = 0;
426 trace2_region_enter("fetch-pack", "negotiation_v0_v1", the_repository);
427 flushes = 0;
428 retval = -1;
429 while ((oid = negotiator->next(negotiator))) {
430 packet_buf_write(&req_buf, "have %s\n", oid_to_hex(oid));
431 print_verbose(args, "have %s", oid_to_hex(oid));
432 in_vain++;
433 if (flush_at <= ++count) {
434 int ack;
436 packet_buf_flush(&req_buf);
437 send_request(args, fd[1], &req_buf);
438 strbuf_setlen(&req_buf, state_len);
439 flushes++;
440 flush_at = next_flush(args->stateless_rpc, count);
443 * We keep one window "ahead" of the other side, and
444 * will wait for an ACK only on the next one
446 if (!args->stateless_rpc && count == INITIAL_FLUSH)
447 continue;
449 consume_shallow_list(args, &reader);
450 do {
451 ack = get_ack(&reader, result_oid);
452 if (ack)
453 print_verbose(args, _("got %s %d %s"), "ack",
454 ack, oid_to_hex(result_oid));
455 switch (ack) {
456 case ACK:
457 flushes = 0;
458 multi_ack = 0;
459 retval = 0;
460 goto done;
461 case ACK_common:
462 case ACK_ready:
463 case ACK_continue: {
464 struct commit *commit =
465 lookup_commit(the_repository,
466 result_oid);
467 int was_common;
469 if (!commit)
470 die(_("invalid commit %s"), oid_to_hex(result_oid));
471 was_common = negotiator->ack(negotiator, commit);
472 if (args->stateless_rpc
473 && ack == ACK_common
474 && !was_common) {
475 /* We need to replay the have for this object
476 * on the next RPC request so the peer knows
477 * it is in common with us.
479 const char *hex = oid_to_hex(result_oid);
480 packet_buf_write(&req_buf, "have %s\n", hex);
481 state_len = req_buf.len;
483 * Reset in_vain because an ack
484 * for this commit has not been
485 * seen.
487 in_vain = 0;
488 } else if (!args->stateless_rpc
489 || ack != ACK_common)
490 in_vain = 0;
491 retval = 0;
492 got_continue = 1;
493 if (ack == ACK_ready)
494 got_ready = 1;
495 break;
498 } while (ack);
499 flushes--;
500 if (got_continue && MAX_IN_VAIN < in_vain) {
501 print_verbose(args, _("giving up"));
502 break; /* give up */
504 if (got_ready)
505 break;
508 done:
509 trace2_region_leave("fetch-pack", "negotiation_v0_v1", the_repository);
510 if (!got_ready || !no_done) {
511 packet_buf_write(&req_buf, "done\n");
512 send_request(args, fd[1], &req_buf);
514 print_verbose(args, _("done"));
515 if (retval != 0) {
516 multi_ack = 0;
517 flushes++;
519 strbuf_release(&req_buf);
521 if (!got_ready || !no_done)
522 consume_shallow_list(args, &reader);
523 while (flushes || multi_ack) {
524 int ack = get_ack(&reader, result_oid);
525 if (ack) {
526 print_verbose(args, _("got %s (%d) %s"), "ack",
527 ack, oid_to_hex(result_oid));
528 if (ack == ACK)
529 return 0;
530 multi_ack = 1;
531 continue;
533 flushes--;
535 /* it is no error to fetch into a completely empty repo */
536 return count ? retval : 0;
539 static struct commit_list *complete;
541 static int mark_complete(const struct object_id *oid)
543 struct commit *commit = deref_without_lazy_fetch(oid, 1);
545 if (commit && !(commit->object.flags & COMPLETE)) {
546 commit->object.flags |= COMPLETE;
547 commit_list_insert(commit, &complete);
549 return 0;
552 static int mark_complete_oid(const char *refname, const struct object_id *oid,
553 int flag, void *cb_data)
555 return mark_complete(oid);
558 static void mark_recent_complete_commits(struct fetch_pack_args *args,
559 timestamp_t cutoff)
561 while (complete && cutoff <= complete->item->date) {
562 print_verbose(args, _("Marking %s as complete"),
563 oid_to_hex(&complete->item->object.oid));
564 pop_most_recent_commit(&complete, COMPLETE);
568 static void add_refs_to_oidset(struct oidset *oids, struct ref *refs)
570 for (; refs; refs = refs->next)
571 oidset_insert(oids, &refs->old_oid);
574 static int is_unmatched_ref(const struct ref *ref)
576 struct object_id oid;
577 const char *p;
578 return ref->match_status == REF_NOT_MATCHED &&
579 !parse_oid_hex(ref->name, &oid, &p) &&
580 *p == '\0' &&
581 oideq(&oid, &ref->old_oid);
584 static void filter_refs(struct fetch_pack_args *args,
585 struct ref **refs,
586 struct ref **sought, int nr_sought)
588 struct ref *newlist = NULL;
589 struct ref **newtail = &newlist;
590 struct ref *unmatched = NULL;
591 struct ref *ref, *next;
592 struct oidset tip_oids = OIDSET_INIT;
593 int i;
594 int strict = !(allow_unadvertised_object_request &
595 (ALLOW_TIP_SHA1 | ALLOW_REACHABLE_SHA1));
597 i = 0;
598 for (ref = *refs; ref; ref = next) {
599 int keep = 0;
600 next = ref->next;
602 if (starts_with(ref->name, "refs/") &&
603 check_refname_format(ref->name, 0)) {
605 * trash or a peeled value; do not even add it to
606 * unmatched list
608 free_one_ref(ref);
609 continue;
610 } else {
611 while (i < nr_sought) {
612 int cmp = strcmp(ref->name, sought[i]->name);
613 if (cmp < 0)
614 break; /* definitely do not have it */
615 else if (cmp == 0) {
616 keep = 1; /* definitely have it */
617 sought[i]->match_status = REF_MATCHED;
619 i++;
622 if (!keep && args->fetch_all &&
623 (!args->deepen || !starts_with(ref->name, "refs/tags/")))
624 keep = 1;
627 if (keep) {
628 *newtail = ref;
629 ref->next = NULL;
630 newtail = &ref->next;
631 } else {
632 ref->next = unmatched;
633 unmatched = ref;
637 if (strict) {
638 for (i = 0; i < nr_sought; i++) {
639 ref = sought[i];
640 if (!is_unmatched_ref(ref))
641 continue;
643 add_refs_to_oidset(&tip_oids, unmatched);
644 add_refs_to_oidset(&tip_oids, newlist);
645 break;
649 /* Append unmatched requests to the list */
650 for (i = 0; i < nr_sought; i++) {
651 ref = sought[i];
652 if (!is_unmatched_ref(ref))
653 continue;
655 if (!strict || oidset_contains(&tip_oids, &ref->old_oid)) {
656 ref->match_status = REF_MATCHED;
657 *newtail = copy_ref(ref);
658 newtail = &(*newtail)->next;
659 } else {
660 ref->match_status = REF_UNADVERTISED_NOT_ALLOWED;
664 oidset_clear(&tip_oids);
665 free_refs(unmatched);
667 *refs = newlist;
670 static void mark_alternate_complete(struct fetch_negotiator *unused,
671 struct object *obj)
673 mark_complete(&obj->oid);
676 struct loose_object_iter {
677 struct oidset *loose_object_set;
678 struct ref *refs;
682 * Mark recent commits available locally and reachable from a local ref as
683 * COMPLETE.
685 * The cutoff time for recency is determined by this heuristic: it is the
686 * earliest commit time of the objects in refs that are commits and that we know
687 * the commit time of.
689 static void mark_complete_and_common_ref(struct fetch_negotiator *negotiator,
690 struct fetch_pack_args *args,
691 struct ref **refs)
693 struct ref *ref;
694 int old_save_commit_buffer = save_commit_buffer;
695 timestamp_t cutoff = 0;
697 if (args->refetch)
698 return;
700 save_commit_buffer = 0;
702 trace2_region_enter("fetch-pack", "parse_remote_refs_and_find_cutoff", NULL);
703 for (ref = *refs; ref; ref = ref->next) {
704 struct commit *commit;
706 commit = lookup_commit_in_graph(the_repository, &ref->old_oid);
707 if (!commit) {
708 struct object *o;
710 if (!has_object_file_with_flags(&ref->old_oid,
711 OBJECT_INFO_QUICK |
712 OBJECT_INFO_SKIP_FETCH_OBJECT))
713 continue;
714 o = parse_object(the_repository, &ref->old_oid);
715 if (!o || o->type != OBJ_COMMIT)
716 continue;
718 commit = (struct commit *)o;
722 * We already have it -- which may mean that we were
723 * in sync with the other side at some time after
724 * that (it is OK if we guess wrong here).
726 if (!cutoff || cutoff < commit->date)
727 cutoff = commit->date;
729 trace2_region_leave("fetch-pack", "parse_remote_refs_and_find_cutoff", NULL);
732 * This block marks all local refs as COMPLETE, and then recursively marks all
733 * parents of those refs as COMPLETE.
735 trace2_region_enter("fetch-pack", "mark_complete_local_refs", NULL);
736 if (!args->deepen) {
737 for_each_rawref(mark_complete_oid, NULL);
738 for_each_cached_alternate(NULL, mark_alternate_complete);
739 commit_list_sort_by_date(&complete);
740 if (cutoff)
741 mark_recent_complete_commits(args, cutoff);
743 trace2_region_leave("fetch-pack", "mark_complete_local_refs", NULL);
746 * Mark all complete remote refs as common refs.
747 * Don't mark them common yet; the server has to be told so first.
749 trace2_region_enter("fetch-pack", "mark_common_remote_refs", NULL);
750 for (ref = *refs; ref; ref = ref->next) {
751 struct commit *c = deref_without_lazy_fetch(&ref->old_oid, 0);
753 if (!c || !(c->object.flags & COMPLETE))
754 continue;
756 negotiator->known_common(negotiator, c);
758 trace2_region_leave("fetch-pack", "mark_common_remote_refs", NULL);
760 save_commit_buffer = old_save_commit_buffer;
764 * Returns 1 if every object pointed to by the given remote refs is available
765 * locally and reachable from a local ref, and 0 otherwise.
767 static int everything_local(struct fetch_pack_args *args,
768 struct ref **refs)
770 struct ref *ref;
771 int retval;
773 for (retval = 1, ref = *refs; ref ; ref = ref->next) {
774 const struct object_id *remote = &ref->old_oid;
775 struct object *o;
777 o = lookup_object(the_repository, remote);
778 if (!o || !(o->flags & COMPLETE)) {
779 retval = 0;
780 print_verbose(args, "want %s (%s)", oid_to_hex(remote),
781 ref->name);
782 continue;
784 print_verbose(args, _("already have %s (%s)"), oid_to_hex(remote),
785 ref->name);
788 return retval;
791 static int sideband_demux(int in, int out, void *data)
793 int *xd = data;
794 int ret;
796 ret = recv_sideband("fetch-pack", xd[0], out);
797 close(out);
798 return ret;
801 static void create_promisor_file(const char *keep_name,
802 struct ref **sought, int nr_sought)
804 struct strbuf promisor_name = STRBUF_INIT;
805 int suffix_stripped;
807 strbuf_addstr(&promisor_name, keep_name);
808 suffix_stripped = strbuf_strip_suffix(&promisor_name, ".keep");
809 if (!suffix_stripped)
810 BUG("name of pack lockfile should end with .keep (was '%s')",
811 keep_name);
812 strbuf_addstr(&promisor_name, ".promisor");
814 write_promisor_file(promisor_name.buf, sought, nr_sought);
816 strbuf_release(&promisor_name);
819 static void parse_gitmodules_oids(int fd, struct oidset *gitmodules_oids)
821 int len = the_hash_algo->hexsz + 1; /* hash + NL */
823 do {
824 char hex_hash[GIT_MAX_HEXSZ + 1];
825 int read_len = read_in_full(fd, hex_hash, len);
826 struct object_id oid;
827 const char *end;
829 if (!read_len)
830 return;
831 if (read_len != len)
832 die("invalid length read %d", read_len);
833 if (parse_oid_hex(hex_hash, &oid, &end) || *end != '\n')
834 die("invalid hash");
835 oidset_insert(gitmodules_oids, &oid);
836 } while (1);
840 * If packfile URIs were provided, pass a non-NULL pointer to index_pack_args.
841 * The strings to pass as the --index-pack-arg arguments to http-fetch will be
842 * stored there. (It must be freed by the caller.)
844 static int get_pack(struct fetch_pack_args *args,
845 int xd[2], struct string_list *pack_lockfiles,
846 struct strvec *index_pack_args,
847 struct ref **sought, int nr_sought,
848 struct oidset *gitmodules_oids)
850 struct async demux;
851 int do_keep = args->keep_pack;
852 const char *cmd_name;
853 struct pack_header header;
854 int pass_header = 0;
855 struct child_process cmd = CHILD_PROCESS_INIT;
856 int fsck_objects = 0;
857 int ret;
859 memset(&demux, 0, sizeof(demux));
860 if (use_sideband) {
861 /* xd[] is talking with upload-pack; subprocess reads from
862 * xd[0], spits out band#2 to stderr, and feeds us band#1
863 * through demux->out.
865 demux.proc = sideband_demux;
866 demux.data = xd;
867 demux.out = -1;
868 demux.isolate_sigpipe = 1;
869 if (start_async(&demux))
870 die(_("fetch-pack: unable to fork off sideband demultiplexer"));
872 else
873 demux.out = xd[0];
875 if (!args->keep_pack && unpack_limit && !index_pack_args) {
877 if (read_pack_header(demux.out, &header))
878 die(_("protocol error: bad pack header"));
879 pass_header = 1;
880 if (ntohl(header.hdr_entries) < unpack_limit)
881 do_keep = 0;
882 else
883 do_keep = 1;
886 if (alternate_shallow_file) {
887 strvec_push(&cmd.args, "--shallow-file");
888 strvec_push(&cmd.args, alternate_shallow_file);
891 if (fetch_fsck_objects >= 0
892 ? fetch_fsck_objects
893 : transfer_fsck_objects >= 0
894 ? transfer_fsck_objects
895 : 0)
896 fsck_objects = 1;
898 if (do_keep || args->from_promisor || index_pack_args || fsck_objects) {
899 if (pack_lockfiles || fsck_objects)
900 cmd.out = -1;
901 cmd_name = "index-pack";
902 strvec_push(&cmd.args, cmd_name);
903 strvec_push(&cmd.args, "--stdin");
904 if (!args->quiet && !args->no_progress)
905 strvec_push(&cmd.args, "-v");
906 if (args->use_thin_pack)
907 strvec_push(&cmd.args, "--fix-thin");
908 if ((do_keep || index_pack_args) && (args->lock_pack || unpack_limit)) {
909 char hostname[HOST_NAME_MAX + 1];
910 if (xgethostname(hostname, sizeof(hostname)))
911 xsnprintf(hostname, sizeof(hostname), "localhost");
912 strvec_pushf(&cmd.args,
913 "--keep=fetch-pack %"PRIuMAX " on %s",
914 (uintmax_t)getpid(), hostname);
916 if (!index_pack_args && args->check_self_contained_and_connected)
917 strvec_push(&cmd.args, "--check-self-contained-and-connected");
918 else
920 * We cannot perform any connectivity checks because
921 * not all packs have been downloaded; let the caller
922 * have this responsibility.
924 args->check_self_contained_and_connected = 0;
926 if (args->from_promisor)
928 * create_promisor_file() may be called afterwards but
929 * we still need index-pack to know that this is a
930 * promisor pack. For example, if transfer.fsckobjects
931 * is true, index-pack needs to know that .gitmodules
932 * is a promisor object (so that it won't complain if
933 * it is missing).
935 strvec_push(&cmd.args, "--promisor");
937 else {
938 cmd_name = "unpack-objects";
939 strvec_push(&cmd.args, cmd_name);
940 if (args->quiet || args->no_progress)
941 strvec_push(&cmd.args, "-q");
942 args->check_self_contained_and_connected = 0;
945 if (pass_header)
946 strvec_pushf(&cmd.args, "--pack_header=%"PRIu32",%"PRIu32,
947 ntohl(header.hdr_version),
948 ntohl(header.hdr_entries));
949 if (fsck_objects) {
950 if (args->from_promisor || index_pack_args)
952 * We cannot use --strict in index-pack because it
953 * checks both broken objects and links, but we only
954 * want to check for broken objects.
956 strvec_push(&cmd.args, "--fsck-objects");
957 else
958 strvec_pushf(&cmd.args, "--strict%s",
959 fsck_msg_types.buf);
962 if (index_pack_args) {
963 int i;
965 for (i = 0; i < cmd.args.nr; i++)
966 strvec_push(index_pack_args, cmd.args.v[i]);
969 sigchain_push(SIGPIPE, SIG_IGN);
971 cmd.in = demux.out;
972 cmd.git_cmd = 1;
973 if (start_command(&cmd))
974 die(_("fetch-pack: unable to fork off %s"), cmd_name);
975 if (do_keep && (pack_lockfiles || fsck_objects)) {
976 int is_well_formed;
977 char *pack_lockfile = index_pack_lockfile(cmd.out, &is_well_formed);
979 if (!is_well_formed)
980 die(_("fetch-pack: invalid index-pack output"));
981 if (pack_lockfile)
982 string_list_append_nodup(pack_lockfiles, pack_lockfile);
983 parse_gitmodules_oids(cmd.out, gitmodules_oids);
984 close(cmd.out);
987 if (!use_sideband)
988 /* Closed by start_command() */
989 xd[0] = -1;
991 ret = finish_command(&cmd);
992 if (!ret || (args->check_self_contained_and_connected && ret == 1))
993 args->self_contained_and_connected =
994 args->check_self_contained_and_connected &&
995 ret == 0;
996 else
997 die(_("%s failed"), cmd_name);
998 if (use_sideband && finish_async(&demux))
999 die(_("error in sideband demultiplexer"));
1001 sigchain_pop(SIGPIPE);
1004 * Now that index-pack has succeeded, write the promisor file using the
1005 * obtained .keep filename if necessary
1007 if (do_keep && pack_lockfiles && pack_lockfiles->nr && args->from_promisor)
1008 create_promisor_file(pack_lockfiles->items[0].string, sought, nr_sought);
1010 return 0;
1013 static int cmp_ref_by_name(const void *a_, const void *b_)
1015 const struct ref *a = *((const struct ref **)a_);
1016 const struct ref *b = *((const struct ref **)b_);
1017 return strcmp(a->name, b->name);
1020 static struct ref *do_fetch_pack(struct fetch_pack_args *args,
1021 int fd[2],
1022 const struct ref *orig_ref,
1023 struct ref **sought, int nr_sought,
1024 struct shallow_info *si,
1025 struct string_list *pack_lockfiles)
1027 struct repository *r = the_repository;
1028 struct ref *ref = copy_ref_list(orig_ref);
1029 struct object_id oid;
1030 const char *agent_feature;
1031 int agent_len;
1032 struct fetch_negotiator negotiator_alloc;
1033 struct fetch_negotiator *negotiator;
1035 negotiator = &negotiator_alloc;
1036 if (args->refetch) {
1037 fetch_negotiator_init_noop(negotiator);
1038 } else {
1039 fetch_negotiator_init(r, negotiator);
1042 sort_ref_list(&ref, ref_compare_name);
1043 QSORT(sought, nr_sought, cmp_ref_by_name);
1045 if ((agent_feature = server_feature_value("agent", &agent_len))) {
1046 agent_supported = 1;
1047 if (agent_len)
1048 print_verbose(args, _("Server version is %.*s"),
1049 agent_len, agent_feature);
1052 if (!server_supports("session-id"))
1053 advertise_sid = 0;
1055 if (server_supports("shallow"))
1056 print_verbose(args, _("Server supports %s"), "shallow");
1057 else if (args->depth > 0 || is_repository_shallow(r))
1058 die(_("Server does not support shallow clients"));
1059 if (args->depth > 0 || args->deepen_since || args->deepen_not)
1060 args->deepen = 1;
1061 if (server_supports("multi_ack_detailed")) {
1062 print_verbose(args, _("Server supports %s"), "multi_ack_detailed");
1063 multi_ack = 2;
1064 if (server_supports("no-done")) {
1065 print_verbose(args, _("Server supports %s"), "no-done");
1066 if (args->stateless_rpc)
1067 no_done = 1;
1070 else if (server_supports("multi_ack")) {
1071 print_verbose(args, _("Server supports %s"), "multi_ack");
1072 multi_ack = 1;
1074 if (server_supports("side-band-64k")) {
1075 print_verbose(args, _("Server supports %s"), "side-band-64k");
1076 use_sideband = 2;
1078 else if (server_supports("side-band")) {
1079 print_verbose(args, _("Server supports %s"), "side-band");
1080 use_sideband = 1;
1082 if (server_supports("allow-tip-sha1-in-want")) {
1083 print_verbose(args, _("Server supports %s"), "allow-tip-sha1-in-want");
1084 allow_unadvertised_object_request |= ALLOW_TIP_SHA1;
1086 if (server_supports("allow-reachable-sha1-in-want")) {
1087 print_verbose(args, _("Server supports %s"), "allow-reachable-sha1-in-want");
1088 allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
1090 if (server_supports("thin-pack"))
1091 print_verbose(args, _("Server supports %s"), "thin-pack");
1092 else
1093 args->use_thin_pack = 0;
1094 if (server_supports("no-progress"))
1095 print_verbose(args, _("Server supports %s"), "no-progress");
1096 else
1097 args->no_progress = 0;
1098 if (server_supports("include-tag"))
1099 print_verbose(args, _("Server supports %s"), "include-tag");
1100 else
1101 args->include_tag = 0;
1102 if (server_supports("ofs-delta"))
1103 print_verbose(args, _("Server supports %s"), "ofs-delta");
1104 else
1105 prefer_ofs_delta = 0;
1107 if (server_supports("filter")) {
1108 server_supports_filtering = 1;
1109 print_verbose(args, _("Server supports %s"), "filter");
1110 } else if (args->filter_options.choice) {
1111 warning("filtering not recognized by server, ignoring");
1114 if (server_supports("deepen-since")) {
1115 print_verbose(args, _("Server supports %s"), "deepen-since");
1116 deepen_since_ok = 1;
1117 } else if (args->deepen_since)
1118 die(_("Server does not support --shallow-since"));
1119 if (server_supports("deepen-not")) {
1120 print_verbose(args, _("Server supports %s"), "deepen-not");
1121 deepen_not_ok = 1;
1122 } else if (args->deepen_not)
1123 die(_("Server does not support --shallow-exclude"));
1124 if (server_supports("deepen-relative"))
1125 print_verbose(args, _("Server supports %s"), "deepen-relative");
1126 else if (args->deepen_relative)
1127 die(_("Server does not support --deepen"));
1128 if (!server_supports_hash(the_hash_algo->name, NULL))
1129 die(_("Server does not support this repository's object format"));
1131 mark_complete_and_common_ref(negotiator, args, &ref);
1132 filter_refs(args, &ref, sought, nr_sought);
1133 if (!args->refetch && everything_local(args, &ref)) {
1134 packet_flush(fd[1]);
1135 goto all_done;
1137 if (find_common(negotiator, args, fd, &oid, ref) < 0)
1138 if (!args->keep_pack)
1139 /* When cloning, it is not unusual to have
1140 * no common commit.
1142 warning(_("no common commits"));
1144 if (args->stateless_rpc)
1145 packet_flush(fd[1]);
1146 if (args->deepen)
1147 setup_alternate_shallow(&shallow_lock, &alternate_shallow_file,
1148 NULL);
1149 else if (si->nr_ours || si->nr_theirs) {
1150 if (args->reject_shallow_remote)
1151 die(_("source repository is shallow, reject to clone."));
1152 alternate_shallow_file = setup_temporary_shallow(si->shallow);
1153 } else
1154 alternate_shallow_file = NULL;
1155 if (get_pack(args, fd, pack_lockfiles, NULL, sought, nr_sought,
1156 &fsck_options.gitmodules_found))
1157 die(_("git fetch-pack: fetch failed."));
1158 if (fsck_finish(&fsck_options))
1159 die("fsck failed");
1161 all_done:
1162 if (negotiator)
1163 negotiator->release(negotiator);
1164 return ref;
1167 static void add_shallow_requests(struct strbuf *req_buf,
1168 const struct fetch_pack_args *args)
1170 if (is_repository_shallow(the_repository))
1171 write_shallow_commits(req_buf, 1, NULL);
1172 if (args->depth > 0)
1173 packet_buf_write(req_buf, "deepen %d", args->depth);
1174 if (args->deepen_since) {
1175 timestamp_t max_age = approxidate(args->deepen_since);
1176 packet_buf_write(req_buf, "deepen-since %"PRItime, max_age);
1178 if (args->deepen_not) {
1179 int i;
1180 for (i = 0; i < args->deepen_not->nr; i++) {
1181 struct string_list_item *s = args->deepen_not->items + i;
1182 packet_buf_write(req_buf, "deepen-not %s", s->string);
1185 if (args->deepen_relative)
1186 packet_buf_write(req_buf, "deepen-relative\n");
1189 static void add_wants(const struct ref *wants, struct strbuf *req_buf)
1191 int use_ref_in_want = server_supports_feature("fetch", "ref-in-want", 0);
1193 for ( ; wants ; wants = wants->next) {
1194 const struct object_id *remote = &wants->old_oid;
1195 struct object *o;
1198 * If that object is complete (i.e. it is an ancestor of a
1199 * local ref), we tell them we have it but do not have to
1200 * tell them about its ancestors, which they already know
1201 * about.
1203 * We use lookup_object here because we are only
1204 * interested in the case we *know* the object is
1205 * reachable and we have already scanned it.
1207 if (((o = lookup_object(the_repository, remote)) != NULL) &&
1208 (o->flags & COMPLETE)) {
1209 continue;
1212 if (!use_ref_in_want || wants->exact_oid)
1213 packet_buf_write(req_buf, "want %s\n", oid_to_hex(remote));
1214 else
1215 packet_buf_write(req_buf, "want-ref %s\n", wants->name);
1219 static void add_common(struct strbuf *req_buf, struct oidset *common)
1221 struct oidset_iter iter;
1222 const struct object_id *oid;
1223 oidset_iter_init(common, &iter);
1225 while ((oid = oidset_iter_next(&iter))) {
1226 packet_buf_write(req_buf, "have %s\n", oid_to_hex(oid));
1230 static int add_haves(struct fetch_negotiator *negotiator,
1231 struct strbuf *req_buf,
1232 int *haves_to_send)
1234 int haves_added = 0;
1235 const struct object_id *oid;
1237 while ((oid = negotiator->next(negotiator))) {
1238 packet_buf_write(req_buf, "have %s\n", oid_to_hex(oid));
1239 if (++haves_added >= *haves_to_send)
1240 break;
1243 /* Increase haves to send on next round */
1244 *haves_to_send = next_flush(1, *haves_to_send);
1246 return haves_added;
1249 static void write_fetch_command_and_capabilities(struct strbuf *req_buf,
1250 const struct string_list *server_options)
1252 const char *hash_name;
1254 if (server_supports_v2("fetch", 1))
1255 packet_buf_write(req_buf, "command=fetch");
1256 if (server_supports_v2("agent", 0))
1257 packet_buf_write(req_buf, "agent=%s", git_user_agent_sanitized());
1258 if (advertise_sid && server_supports_v2("session-id", 0))
1259 packet_buf_write(req_buf, "session-id=%s", trace2_session_id());
1260 if (server_options && server_options->nr &&
1261 server_supports_v2("server-option", 1)) {
1262 int i;
1263 for (i = 0; i < server_options->nr; i++)
1264 packet_buf_write(req_buf, "server-option=%s",
1265 server_options->items[i].string);
1268 if (server_feature_v2("object-format", &hash_name)) {
1269 int hash_algo = hash_algo_by_name(hash_name);
1270 if (hash_algo_by_ptr(the_hash_algo) != hash_algo)
1271 die(_("mismatched algorithms: client %s; server %s"),
1272 the_hash_algo->name, hash_name);
1273 packet_buf_write(req_buf, "object-format=%s", the_hash_algo->name);
1274 } else if (hash_algo_by_ptr(the_hash_algo) != GIT_HASH_SHA1) {
1275 die(_("the server does not support algorithm '%s'"),
1276 the_hash_algo->name);
1278 packet_buf_delim(req_buf);
1281 static int send_fetch_request(struct fetch_negotiator *negotiator, int fd_out,
1282 struct fetch_pack_args *args,
1283 const struct ref *wants, struct oidset *common,
1284 int *haves_to_send, int *in_vain,
1285 int sideband_all, int seen_ack)
1287 int haves_added;
1288 int done_sent = 0;
1289 struct strbuf req_buf = STRBUF_INIT;
1291 write_fetch_command_and_capabilities(&req_buf, args->server_options);
1293 if (args->use_thin_pack)
1294 packet_buf_write(&req_buf, "thin-pack");
1295 if (args->no_progress)
1296 packet_buf_write(&req_buf, "no-progress");
1297 if (args->include_tag)
1298 packet_buf_write(&req_buf, "include-tag");
1299 if (prefer_ofs_delta)
1300 packet_buf_write(&req_buf, "ofs-delta");
1301 if (sideband_all)
1302 packet_buf_write(&req_buf, "sideband-all");
1304 /* Add shallow-info and deepen request */
1305 if (server_supports_feature("fetch", "shallow", 0))
1306 add_shallow_requests(&req_buf, args);
1307 else if (is_repository_shallow(the_repository) || args->deepen)
1308 die(_("Server does not support shallow requests"));
1310 /* Add filter */
1311 if (server_supports_feature("fetch", "filter", 0) &&
1312 args->filter_options.choice) {
1313 const char *spec =
1314 expand_list_objects_filter_spec(&args->filter_options);
1315 print_verbose(args, _("Server supports filter"));
1316 packet_buf_write(&req_buf, "filter %s", spec);
1317 } else if (args->filter_options.choice) {
1318 warning("filtering not recognized by server, ignoring");
1321 if (server_supports_feature("fetch", "packfile-uris", 0)) {
1322 int i;
1323 struct strbuf to_send = STRBUF_INIT;
1325 for (i = 0; i < uri_protocols.nr; i++) {
1326 const char *s = uri_protocols.items[i].string;
1328 if (!strcmp(s, "https") || !strcmp(s, "http")) {
1329 if (to_send.len)
1330 strbuf_addch(&to_send, ',');
1331 strbuf_addstr(&to_send, s);
1334 if (to_send.len) {
1335 packet_buf_write(&req_buf, "packfile-uris %s",
1336 to_send.buf);
1337 strbuf_release(&to_send);
1341 /* add wants */
1342 add_wants(wants, &req_buf);
1344 /* Add all of the common commits we've found in previous rounds */
1345 add_common(&req_buf, common);
1347 haves_added = add_haves(negotiator, &req_buf, haves_to_send);
1348 *in_vain += haves_added;
1349 if (!haves_added || (seen_ack && *in_vain >= MAX_IN_VAIN)) {
1350 /* Send Done */
1351 packet_buf_write(&req_buf, "done\n");
1352 done_sent = 1;
1355 /* Send request */
1356 packet_buf_flush(&req_buf);
1357 if (write_in_full(fd_out, req_buf.buf, req_buf.len) < 0)
1358 die_errno(_("unable to write request to remote"));
1360 strbuf_release(&req_buf);
1361 return done_sent;
1365 * Processes a section header in a server's response and checks if it matches
1366 * `section`. If the value of `peek` is 1, the header line will be peeked (and
1367 * not consumed); if 0, the line will be consumed and the function will die if
1368 * the section header doesn't match what was expected.
1370 static int process_section_header(struct packet_reader *reader,
1371 const char *section, int peek)
1373 int ret;
1375 if (packet_reader_peek(reader) != PACKET_READ_NORMAL)
1376 die(_("error reading section header '%s'"), section);
1378 ret = !strcmp(reader->line, section);
1380 if (!peek) {
1381 if (!ret)
1382 die(_("expected '%s', received '%s'"),
1383 section, reader->line);
1384 packet_reader_read(reader);
1387 return ret;
1390 static int process_ack(struct fetch_negotiator *negotiator,
1391 struct packet_reader *reader,
1392 struct object_id *common_oid,
1393 int *received_ready)
1395 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1396 const char *arg;
1398 if (!strcmp(reader->line, "NAK"))
1399 continue;
1401 if (skip_prefix(reader->line, "ACK ", &arg)) {
1402 if (!get_oid_hex(arg, common_oid)) {
1403 struct commit *commit;
1404 commit = lookup_commit(the_repository, common_oid);
1405 if (negotiator)
1406 negotiator->ack(negotiator, commit);
1408 return 1;
1411 if (!strcmp(reader->line, "ready")) {
1412 *received_ready = 1;
1413 continue;
1416 die(_("unexpected acknowledgment line: '%s'"), reader->line);
1419 if (reader->status != PACKET_READ_FLUSH &&
1420 reader->status != PACKET_READ_DELIM)
1421 die(_("error processing acks: %d"), reader->status);
1424 * If an "acknowledgments" section is sent, a packfile is sent if and
1425 * only if "ready" was sent in this section. The other sections
1426 * ("shallow-info" and "wanted-refs") are sent only if a packfile is
1427 * sent. Therefore, a DELIM is expected if "ready" is sent, and a FLUSH
1428 * otherwise.
1430 if (*received_ready && reader->status != PACKET_READ_DELIM)
1432 * TRANSLATORS: The parameter will be 'ready', a protocol
1433 * keyword.
1435 die(_("expected packfile to be sent after '%s'"), "ready");
1436 if (!*received_ready && reader->status != PACKET_READ_FLUSH)
1438 * TRANSLATORS: The parameter will be 'ready', a protocol
1439 * keyword.
1441 die(_("expected no other sections to be sent after no '%s'"), "ready");
1443 return 0;
1446 static void receive_shallow_info(struct fetch_pack_args *args,
1447 struct packet_reader *reader,
1448 struct oid_array *shallows,
1449 struct shallow_info *si)
1451 int unshallow_received = 0;
1453 process_section_header(reader, "shallow-info", 0);
1454 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1455 const char *arg;
1456 struct object_id oid;
1458 if (skip_prefix(reader->line, "shallow ", &arg)) {
1459 if (get_oid_hex(arg, &oid))
1460 die(_("invalid shallow line: %s"), reader->line);
1461 oid_array_append(shallows, &oid);
1462 continue;
1464 if (skip_prefix(reader->line, "unshallow ", &arg)) {
1465 if (get_oid_hex(arg, &oid))
1466 die(_("invalid unshallow line: %s"), reader->line);
1467 if (!lookup_object(the_repository, &oid))
1468 die(_("object not found: %s"), reader->line);
1469 /* make sure that it is parsed as shallow */
1470 if (!parse_object(the_repository, &oid))
1471 die(_("error in object: %s"), reader->line);
1472 if (unregister_shallow(&oid))
1473 die(_("no shallow found: %s"), reader->line);
1474 unshallow_received = 1;
1475 continue;
1477 die(_("expected shallow/unshallow, got %s"), reader->line);
1480 if (reader->status != PACKET_READ_FLUSH &&
1481 reader->status != PACKET_READ_DELIM)
1482 die(_("error processing shallow info: %d"), reader->status);
1484 if (args->deepen || unshallow_received) {
1486 * Treat these as shallow lines caused by our depth settings.
1487 * In v0, these lines cannot cause refs to be rejected; do the
1488 * same.
1490 int i;
1492 for (i = 0; i < shallows->nr; i++)
1493 register_shallow(the_repository, &shallows->oid[i]);
1494 setup_alternate_shallow(&shallow_lock, &alternate_shallow_file,
1495 NULL);
1496 args->deepen = 1;
1497 } else if (shallows->nr) {
1499 * Treat these as shallow lines caused by the remote being
1500 * shallow. In v0, remote refs that reach these objects are
1501 * rejected (unless --update-shallow is set); do the same.
1503 prepare_shallow_info(si, shallows);
1504 if (si->nr_ours || si->nr_theirs) {
1505 if (args->reject_shallow_remote)
1506 die(_("source repository is shallow, reject to clone."));
1507 alternate_shallow_file =
1508 setup_temporary_shallow(si->shallow);
1509 } else
1510 alternate_shallow_file = NULL;
1511 } else {
1512 alternate_shallow_file = NULL;
1516 static int cmp_name_ref(const void *name, const void *ref)
1518 return strcmp(name, (*(struct ref **)ref)->name);
1521 static void receive_wanted_refs(struct packet_reader *reader,
1522 struct ref **sought, int nr_sought)
1524 process_section_header(reader, "wanted-refs", 0);
1525 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1526 struct object_id oid;
1527 const char *end;
1528 struct ref **found;
1530 if (parse_oid_hex(reader->line, &oid, &end) || *end++ != ' ')
1531 die(_("expected wanted-ref, got '%s'"), reader->line);
1533 found = bsearch(end, sought, nr_sought, sizeof(*sought),
1534 cmp_name_ref);
1535 if (!found)
1536 die(_("unexpected wanted-ref: '%s'"), reader->line);
1537 oidcpy(&(*found)->old_oid, &oid);
1540 if (reader->status != PACKET_READ_DELIM)
1541 die(_("error processing wanted refs: %d"), reader->status);
1544 static void receive_packfile_uris(struct packet_reader *reader,
1545 struct string_list *uris)
1547 process_section_header(reader, "packfile-uris", 0);
1548 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1549 if (reader->pktlen < the_hash_algo->hexsz ||
1550 reader->line[the_hash_algo->hexsz] != ' ')
1551 die("expected '<hash> <uri>', got: %s\n", reader->line);
1553 string_list_append(uris, reader->line);
1555 if (reader->status != PACKET_READ_DELIM)
1556 die("expected DELIM");
1559 enum fetch_state {
1560 FETCH_CHECK_LOCAL = 0,
1561 FETCH_SEND_REQUEST,
1562 FETCH_PROCESS_ACKS,
1563 FETCH_GET_PACK,
1564 FETCH_DONE,
1567 static void do_check_stateless_delimiter(int stateless_rpc,
1568 struct packet_reader *reader)
1570 check_stateless_delimiter(stateless_rpc, reader,
1571 _("git fetch-pack: expected response end packet"));
1574 static struct ref *do_fetch_pack_v2(struct fetch_pack_args *args,
1575 int fd[2],
1576 const struct ref *orig_ref,
1577 struct ref **sought, int nr_sought,
1578 struct oid_array *shallows,
1579 struct shallow_info *si,
1580 struct string_list *pack_lockfiles)
1582 struct repository *r = the_repository;
1583 struct ref *ref = copy_ref_list(orig_ref);
1584 enum fetch_state state = FETCH_CHECK_LOCAL;
1585 struct oidset common = OIDSET_INIT;
1586 struct packet_reader reader;
1587 int in_vain = 0, negotiation_started = 0;
1588 int haves_to_send = INITIAL_FLUSH;
1589 struct fetch_negotiator negotiator_alloc;
1590 struct fetch_negotiator *negotiator;
1591 int seen_ack = 0;
1592 struct object_id common_oid;
1593 int received_ready = 0;
1594 struct string_list packfile_uris = STRING_LIST_INIT_DUP;
1595 int i;
1596 struct strvec index_pack_args = STRVEC_INIT;
1598 negotiator = &negotiator_alloc;
1599 if (args->refetch)
1600 fetch_negotiator_init_noop(negotiator);
1601 else
1602 fetch_negotiator_init(r, negotiator);
1604 packet_reader_init(&reader, fd[0], NULL, 0,
1605 PACKET_READ_CHOMP_NEWLINE |
1606 PACKET_READ_DIE_ON_ERR_PACKET);
1607 if (git_env_bool("GIT_TEST_SIDEBAND_ALL", 1) &&
1608 server_supports_feature("fetch", "sideband-all", 0)) {
1609 reader.use_sideband = 1;
1610 reader.me = "fetch-pack";
1613 while (state != FETCH_DONE) {
1614 switch (state) {
1615 case FETCH_CHECK_LOCAL:
1616 sort_ref_list(&ref, ref_compare_name);
1617 QSORT(sought, nr_sought, cmp_ref_by_name);
1619 /* v2 supports these by default */
1620 allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
1621 use_sideband = 2;
1622 if (args->depth > 0 || args->deepen_since || args->deepen_not)
1623 args->deepen = 1;
1625 /* Filter 'ref' by 'sought' and those that aren't local */
1626 mark_complete_and_common_ref(negotiator, args, &ref);
1627 filter_refs(args, &ref, sought, nr_sought);
1628 if (!args->refetch && everything_local(args, &ref))
1629 state = FETCH_DONE;
1630 else
1631 state = FETCH_SEND_REQUEST;
1633 mark_tips(negotiator, args->negotiation_tips);
1634 for_each_cached_alternate(negotiator,
1635 insert_one_alternate_object);
1636 break;
1637 case FETCH_SEND_REQUEST:
1638 if (!negotiation_started) {
1639 negotiation_started = 1;
1640 trace2_region_enter("fetch-pack",
1641 "negotiation_v2",
1642 the_repository);
1644 if (send_fetch_request(negotiator, fd[1], args, ref,
1645 &common,
1646 &haves_to_send, &in_vain,
1647 reader.use_sideband,
1648 seen_ack))
1649 state = FETCH_GET_PACK;
1650 else
1651 state = FETCH_PROCESS_ACKS;
1652 break;
1653 case FETCH_PROCESS_ACKS:
1654 /* Process ACKs/NAKs */
1655 process_section_header(&reader, "acknowledgments", 0);
1656 while (process_ack(negotiator, &reader, &common_oid,
1657 &received_ready)) {
1658 in_vain = 0;
1659 seen_ack = 1;
1660 oidset_insert(&common, &common_oid);
1662 if (received_ready) {
1664 * Don't check for response delimiter; get_pack() will
1665 * read the rest of this response.
1667 state = FETCH_GET_PACK;
1668 } else {
1669 do_check_stateless_delimiter(args->stateless_rpc, &reader);
1670 state = FETCH_SEND_REQUEST;
1672 break;
1673 case FETCH_GET_PACK:
1674 trace2_region_leave("fetch-pack",
1675 "negotiation_v2",
1676 the_repository);
1677 /* Check for shallow-info section */
1678 if (process_section_header(&reader, "shallow-info", 1))
1679 receive_shallow_info(args, &reader, shallows, si);
1681 if (process_section_header(&reader, "wanted-refs", 1))
1682 receive_wanted_refs(&reader, sought, nr_sought);
1684 /* get the pack(s) */
1685 if (git_env_bool("GIT_TRACE_REDACT", 1))
1686 reader.options |= PACKET_READ_REDACT_URI_PATH;
1687 if (process_section_header(&reader, "packfile-uris", 1))
1688 receive_packfile_uris(&reader, &packfile_uris);
1689 /* We don't expect more URIs. Reset to avoid expensive URI check. */
1690 reader.options &= ~PACKET_READ_REDACT_URI_PATH;
1692 process_section_header(&reader, "packfile", 0);
1695 * this is the final request we'll make of the server;
1696 * do a half-duplex shutdown to indicate that they can
1697 * hang up as soon as the pack is sent.
1699 close(fd[1]);
1700 fd[1] = -1;
1702 if (get_pack(args, fd, pack_lockfiles,
1703 packfile_uris.nr ? &index_pack_args : NULL,
1704 sought, nr_sought, &fsck_options.gitmodules_found))
1705 die(_("git fetch-pack: fetch failed."));
1706 do_check_stateless_delimiter(args->stateless_rpc, &reader);
1708 state = FETCH_DONE;
1709 break;
1710 case FETCH_DONE:
1711 continue;
1715 for (i = 0; i < packfile_uris.nr; i++) {
1716 int j;
1717 struct child_process cmd = CHILD_PROCESS_INIT;
1718 char packname[GIT_MAX_HEXSZ + 1];
1719 const char *uri = packfile_uris.items[i].string +
1720 the_hash_algo->hexsz + 1;
1722 strvec_push(&cmd.args, "http-fetch");
1723 strvec_pushf(&cmd.args, "--packfile=%.*s",
1724 (int) the_hash_algo->hexsz,
1725 packfile_uris.items[i].string);
1726 for (j = 0; j < index_pack_args.nr; j++)
1727 strvec_pushf(&cmd.args, "--index-pack-arg=%s",
1728 index_pack_args.v[j]);
1729 strvec_push(&cmd.args, uri);
1730 cmd.git_cmd = 1;
1731 cmd.no_stdin = 1;
1732 cmd.out = -1;
1733 if (start_command(&cmd))
1734 die("fetch-pack: unable to spawn http-fetch");
1736 if (read_in_full(cmd.out, packname, 5) < 0 ||
1737 memcmp(packname, "keep\t", 5))
1738 die("fetch-pack: expected keep then TAB at start of http-fetch output");
1740 if (read_in_full(cmd.out, packname,
1741 the_hash_algo->hexsz + 1) < 0 ||
1742 packname[the_hash_algo->hexsz] != '\n')
1743 die("fetch-pack: expected hash then LF at end of http-fetch output");
1745 packname[the_hash_algo->hexsz] = '\0';
1747 parse_gitmodules_oids(cmd.out, &fsck_options.gitmodules_found);
1749 close(cmd.out);
1751 if (finish_command(&cmd))
1752 die("fetch-pack: unable to finish http-fetch");
1754 if (memcmp(packfile_uris.items[i].string, packname,
1755 the_hash_algo->hexsz))
1756 die("fetch-pack: pack downloaded from %s does not match expected hash %.*s",
1757 uri, (int) the_hash_algo->hexsz,
1758 packfile_uris.items[i].string);
1760 string_list_append_nodup(pack_lockfiles,
1761 xstrfmt("%s/pack/pack-%s.keep",
1762 get_object_directory(),
1763 packname));
1765 string_list_clear(&packfile_uris, 0);
1766 strvec_clear(&index_pack_args);
1768 if (fsck_finish(&fsck_options))
1769 die("fsck failed");
1771 if (negotiator)
1772 negotiator->release(negotiator);
1774 oidset_clear(&common);
1775 return ref;
1778 static int fetch_pack_config_cb(const char *var, const char *value, void *cb)
1780 if (strcmp(var, "fetch.fsck.skiplist") == 0) {
1781 const char *path;
1783 if (git_config_pathname(&path, var, value))
1784 return 1;
1785 strbuf_addf(&fsck_msg_types, "%cskiplist=%s",
1786 fsck_msg_types.len ? ',' : '=', path);
1787 free((char *)path);
1788 return 0;
1791 if (skip_prefix(var, "fetch.fsck.", &var)) {
1792 if (is_valid_msg_type(var, value))
1793 strbuf_addf(&fsck_msg_types, "%c%s=%s",
1794 fsck_msg_types.len ? ',' : '=', var, value);
1795 else
1796 warning("Skipping unknown msg id '%s'", var);
1797 return 0;
1800 return git_default_config(var, value, cb);
1803 static void fetch_pack_config(void)
1805 git_config_get_int("fetch.unpacklimit", &fetch_unpack_limit);
1806 git_config_get_int("transfer.unpacklimit", &transfer_unpack_limit);
1807 git_config_get_bool("repack.usedeltabaseoffset", &prefer_ofs_delta);
1808 git_config_get_bool("fetch.fsckobjects", &fetch_fsck_objects);
1809 git_config_get_bool("transfer.fsckobjects", &transfer_fsck_objects);
1810 git_config_get_bool("transfer.advertisesid", &advertise_sid);
1811 if (!uri_protocols.nr) {
1812 char *str;
1814 if (!git_config_get_string("fetch.uriprotocols", &str) && str) {
1815 string_list_split(&uri_protocols, str, ',', -1);
1816 free(str);
1820 git_config(fetch_pack_config_cb, NULL);
1823 static void fetch_pack_setup(void)
1825 static int did_setup;
1826 if (did_setup)
1827 return;
1828 fetch_pack_config();
1829 if (0 <= transfer_unpack_limit)
1830 unpack_limit = transfer_unpack_limit;
1831 else if (0 <= fetch_unpack_limit)
1832 unpack_limit = fetch_unpack_limit;
1833 did_setup = 1;
1836 static int remove_duplicates_in_refs(struct ref **ref, int nr)
1838 struct string_list names = STRING_LIST_INIT_NODUP;
1839 int src, dst;
1841 for (src = dst = 0; src < nr; src++) {
1842 struct string_list_item *item;
1843 item = string_list_insert(&names, ref[src]->name);
1844 if (item->util)
1845 continue; /* already have it */
1846 item->util = ref[src];
1847 if (src != dst)
1848 ref[dst] = ref[src];
1849 dst++;
1851 for (src = dst; src < nr; src++)
1852 ref[src] = NULL;
1853 string_list_clear(&names, 0);
1854 return dst;
1857 static void update_shallow(struct fetch_pack_args *args,
1858 struct ref **sought, int nr_sought,
1859 struct shallow_info *si)
1861 struct oid_array ref = OID_ARRAY_INIT;
1862 int *status;
1863 int i;
1865 if (args->deepen && alternate_shallow_file) {
1866 if (*alternate_shallow_file == '\0') { /* --unshallow */
1867 unlink_or_warn(git_path_shallow(the_repository));
1868 rollback_shallow_file(the_repository, &shallow_lock);
1869 } else
1870 commit_shallow_file(the_repository, &shallow_lock);
1871 alternate_shallow_file = NULL;
1872 return;
1875 if (!si->shallow || !si->shallow->nr)
1876 return;
1878 if (args->cloning) {
1880 * remote is shallow, but this is a clone, there are
1881 * no objects in repo to worry about. Accept any
1882 * shallow points that exist in the pack (iow in repo
1883 * after get_pack() and reprepare_packed_git())
1885 struct oid_array extra = OID_ARRAY_INIT;
1886 struct object_id *oid = si->shallow->oid;
1887 for (i = 0; i < si->shallow->nr; i++)
1888 if (has_object_file(&oid[i]))
1889 oid_array_append(&extra, &oid[i]);
1890 if (extra.nr) {
1891 setup_alternate_shallow(&shallow_lock,
1892 &alternate_shallow_file,
1893 &extra);
1894 commit_shallow_file(the_repository, &shallow_lock);
1895 alternate_shallow_file = NULL;
1897 oid_array_clear(&extra);
1898 return;
1901 if (!si->nr_ours && !si->nr_theirs)
1902 return;
1904 remove_nonexistent_theirs_shallow(si);
1905 if (!si->nr_ours && !si->nr_theirs)
1906 return;
1907 for (i = 0; i < nr_sought; i++)
1908 oid_array_append(&ref, &sought[i]->old_oid);
1909 si->ref = &ref;
1911 if (args->update_shallow) {
1913 * remote is also shallow, .git/shallow may be updated
1914 * so all refs can be accepted. Make sure we only add
1915 * shallow roots that are actually reachable from new
1916 * refs.
1918 struct oid_array extra = OID_ARRAY_INIT;
1919 struct object_id *oid = si->shallow->oid;
1920 assign_shallow_commits_to_refs(si, NULL, NULL);
1921 if (!si->nr_ours && !si->nr_theirs) {
1922 oid_array_clear(&ref);
1923 return;
1925 for (i = 0; i < si->nr_ours; i++)
1926 oid_array_append(&extra, &oid[si->ours[i]]);
1927 for (i = 0; i < si->nr_theirs; i++)
1928 oid_array_append(&extra, &oid[si->theirs[i]]);
1929 setup_alternate_shallow(&shallow_lock,
1930 &alternate_shallow_file,
1931 &extra);
1932 commit_shallow_file(the_repository, &shallow_lock);
1933 oid_array_clear(&extra);
1934 oid_array_clear(&ref);
1935 alternate_shallow_file = NULL;
1936 return;
1940 * remote is also shallow, check what ref is safe to update
1941 * without updating .git/shallow
1943 CALLOC_ARRAY(status, nr_sought);
1944 assign_shallow_commits_to_refs(si, NULL, status);
1945 if (si->nr_ours || si->nr_theirs) {
1946 for (i = 0; i < nr_sought; i++)
1947 if (status[i])
1948 sought[i]->status = REF_STATUS_REJECT_SHALLOW;
1950 free(status);
1951 oid_array_clear(&ref);
1954 static const struct object_id *iterate_ref_map(void *cb_data)
1956 struct ref **rm = cb_data;
1957 struct ref *ref = *rm;
1959 if (!ref)
1960 return NULL;
1961 *rm = ref->next;
1962 return &ref->old_oid;
1965 struct ref *fetch_pack(struct fetch_pack_args *args,
1966 int fd[],
1967 const struct ref *ref,
1968 struct ref **sought, int nr_sought,
1969 struct oid_array *shallow,
1970 struct string_list *pack_lockfiles,
1971 enum protocol_version version)
1973 struct ref *ref_cpy;
1974 struct shallow_info si;
1975 struct oid_array shallows_scratch = OID_ARRAY_INIT;
1977 fetch_pack_setup();
1978 if (nr_sought)
1979 nr_sought = remove_duplicates_in_refs(sought, nr_sought);
1981 if (version != protocol_v2 && !ref) {
1982 packet_flush(fd[1]);
1983 die(_("no matching remote head"));
1985 if (version == protocol_v2) {
1986 if (shallow->nr)
1987 BUG("Protocol V2 does not provide shallows at this point in the fetch");
1988 memset(&si, 0, sizeof(si));
1989 ref_cpy = do_fetch_pack_v2(args, fd, ref, sought, nr_sought,
1990 &shallows_scratch, &si,
1991 pack_lockfiles);
1992 } else {
1993 prepare_shallow_info(&si, shallow);
1994 ref_cpy = do_fetch_pack(args, fd, ref, sought, nr_sought,
1995 &si, pack_lockfiles);
1997 reprepare_packed_git(the_repository);
1999 if (!args->cloning && args->deepen) {
2000 struct check_connected_options opt = CHECK_CONNECTED_INIT;
2001 struct ref *iterator = ref_cpy;
2002 opt.shallow_file = alternate_shallow_file;
2003 if (args->deepen)
2004 opt.is_deepening_fetch = 1;
2005 if (check_connected(iterate_ref_map, &iterator, &opt)) {
2006 error(_("remote did not send all necessary objects"));
2007 free_refs(ref_cpy);
2008 ref_cpy = NULL;
2009 rollback_shallow_file(the_repository, &shallow_lock);
2010 goto cleanup;
2012 args->connectivity_checked = 1;
2015 update_shallow(args, sought, nr_sought, &si);
2016 cleanup:
2017 clear_shallow_info(&si);
2018 oid_array_clear(&shallows_scratch);
2019 return ref_cpy;
2022 static int add_to_object_array(const struct object_id *oid, void *data)
2024 struct object_array *a = data;
2026 add_object_array(lookup_object(the_repository, oid), "", a);
2027 return 0;
2030 static void clear_common_flag(struct oidset *s)
2032 struct oidset_iter iter;
2033 const struct object_id *oid;
2034 oidset_iter_init(s, &iter);
2036 while ((oid = oidset_iter_next(&iter))) {
2037 struct object *obj = lookup_object(the_repository, oid);
2038 obj->flags &= ~COMMON;
2042 void negotiate_using_fetch(const struct oid_array *negotiation_tips,
2043 const struct string_list *server_options,
2044 int stateless_rpc,
2045 int fd[],
2046 struct oidset *acked_commits)
2048 struct fetch_negotiator negotiator;
2049 struct packet_reader reader;
2050 struct object_array nt_object_array = OBJECT_ARRAY_INIT;
2051 struct strbuf req_buf = STRBUF_INIT;
2052 int haves_to_send = INITIAL_FLUSH;
2053 int in_vain = 0;
2054 int seen_ack = 0;
2055 int last_iteration = 0;
2056 timestamp_t min_generation = GENERATION_NUMBER_INFINITY;
2058 fetch_negotiator_init(the_repository, &negotiator);
2059 mark_tips(&negotiator, negotiation_tips);
2061 packet_reader_init(&reader, fd[0], NULL, 0,
2062 PACKET_READ_CHOMP_NEWLINE |
2063 PACKET_READ_DIE_ON_ERR_PACKET);
2065 oid_array_for_each((struct oid_array *) negotiation_tips,
2066 add_to_object_array,
2067 &nt_object_array);
2069 while (!last_iteration) {
2070 int haves_added;
2071 struct object_id common_oid;
2072 int received_ready = 0;
2074 strbuf_reset(&req_buf);
2075 write_fetch_command_and_capabilities(&req_buf, server_options);
2077 packet_buf_write(&req_buf, "wait-for-done");
2079 haves_added = add_haves(&negotiator, &req_buf, &haves_to_send);
2080 in_vain += haves_added;
2081 if (!haves_added || (seen_ack && in_vain >= MAX_IN_VAIN))
2082 last_iteration = 1;
2084 /* Send request */
2085 packet_buf_flush(&req_buf);
2086 if (write_in_full(fd[1], req_buf.buf, req_buf.len) < 0)
2087 die_errno(_("unable to write request to remote"));
2089 /* Process ACKs/NAKs */
2090 process_section_header(&reader, "acknowledgments", 0);
2091 while (process_ack(&negotiator, &reader, &common_oid,
2092 &received_ready)) {
2093 struct commit *commit = lookup_commit(the_repository,
2094 &common_oid);
2095 if (commit) {
2096 timestamp_t generation;
2098 parse_commit_or_die(commit);
2099 commit->object.flags |= COMMON;
2100 generation = commit_graph_generation(commit);
2101 if (generation < min_generation)
2102 min_generation = generation;
2104 in_vain = 0;
2105 seen_ack = 1;
2106 oidset_insert(acked_commits, &common_oid);
2108 if (received_ready)
2109 die(_("unexpected 'ready' from remote"));
2110 else
2111 do_check_stateless_delimiter(stateless_rpc, &reader);
2112 if (can_all_from_reach_with_flag(&nt_object_array, COMMON,
2113 REACH_SCRATCH, 0,
2114 min_generation))
2115 last_iteration = 1;
2117 clear_common_flag(acked_commits);
2118 strbuf_release(&req_buf);
2121 int report_unmatched_refs(struct ref **sought, int nr_sought)
2123 int i, ret = 0;
2125 for (i = 0; i < nr_sought; i++) {
2126 if (!sought[i])
2127 continue;
2128 switch (sought[i]->match_status) {
2129 case REF_MATCHED:
2130 continue;
2131 case REF_NOT_MATCHED:
2132 error(_("no such remote ref %s"), sought[i]->name);
2133 break;
2134 case REF_UNADVERTISED_NOT_ALLOWED:
2135 error(_("Server does not allow request for unadvertised object %s"),
2136 sought[i]->name);
2137 break;
2139 ret = 1;
2141 return ret;