Merge branch 'bs/forbid-i18n-of-protocol-token-in-fetch-pack'
[alt-git.git] / fetch-pack.c
blobdbcaaf4dbb253b1c10321d0b8955b0c352a53936
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;
316 * If that object is complete (i.e. it is an ancestor of a
317 * local ref), we tell them we have it but do not have to
318 * tell them about its ancestors, which they already know
319 * about.
321 * We use lookup_object here because we are only
322 * interested in the case we *know* the object is
323 * reachable and we have already scanned it.
325 if (((o = lookup_object(the_repository, remote)) != NULL) &&
326 (o->flags & COMPLETE)) {
327 continue;
330 remote_hex = oid_to_hex(remote);
331 if (!fetching) {
332 struct strbuf c = STRBUF_INIT;
333 if (multi_ack == 2) strbuf_addstr(&c, " multi_ack_detailed");
334 if (multi_ack == 1) strbuf_addstr(&c, " multi_ack");
335 if (no_done) strbuf_addstr(&c, " no-done");
336 if (use_sideband == 2) strbuf_addstr(&c, " side-band-64k");
337 if (use_sideband == 1) strbuf_addstr(&c, " side-band");
338 if (args->deepen_relative) strbuf_addstr(&c, " deepen-relative");
339 if (args->use_thin_pack) strbuf_addstr(&c, " thin-pack");
340 if (args->no_progress) strbuf_addstr(&c, " no-progress");
341 if (args->include_tag) strbuf_addstr(&c, " include-tag");
342 if (prefer_ofs_delta) strbuf_addstr(&c, " ofs-delta");
343 if (deepen_since_ok) strbuf_addstr(&c, " deepen-since");
344 if (deepen_not_ok) strbuf_addstr(&c, " deepen-not");
345 if (agent_supported) strbuf_addf(&c, " agent=%s",
346 git_user_agent_sanitized());
347 if (advertise_sid)
348 strbuf_addf(&c, " session-id=%s", trace2_session_id());
349 if (args->filter_options.choice)
350 strbuf_addstr(&c, " filter");
351 packet_buf_write(&req_buf, "want %s%s\n", remote_hex, c.buf);
352 strbuf_release(&c);
353 } else
354 packet_buf_write(&req_buf, "want %s\n", remote_hex);
355 fetching++;
358 if (!fetching) {
359 strbuf_release(&req_buf);
360 packet_flush(fd[1]);
361 return 1;
364 if (is_repository_shallow(the_repository))
365 write_shallow_commits(&req_buf, 1, NULL);
366 if (args->depth > 0)
367 packet_buf_write(&req_buf, "deepen %d", args->depth);
368 if (args->deepen_since) {
369 timestamp_t max_age = approxidate(args->deepen_since);
370 packet_buf_write(&req_buf, "deepen-since %"PRItime, max_age);
372 if (args->deepen_not) {
373 int i;
374 for (i = 0; i < args->deepen_not->nr; i++) {
375 struct string_list_item *s = args->deepen_not->items + i;
376 packet_buf_write(&req_buf, "deepen-not %s", s->string);
379 if (server_supports_filtering && args->filter_options.choice) {
380 const char *spec =
381 expand_list_objects_filter_spec(&args->filter_options);
382 packet_buf_write(&req_buf, "filter %s", spec);
384 packet_buf_flush(&req_buf);
385 state_len = req_buf.len;
387 if (args->deepen) {
388 const char *arg;
389 struct object_id oid;
391 send_request(args, fd[1], &req_buf);
392 while (packet_reader_read(&reader) == PACKET_READ_NORMAL) {
393 if (skip_prefix(reader.line, "shallow ", &arg)) {
394 if (get_oid_hex(arg, &oid))
395 die(_("invalid shallow line: %s"), reader.line);
396 register_shallow(the_repository, &oid);
397 continue;
399 if (skip_prefix(reader.line, "unshallow ", &arg)) {
400 if (get_oid_hex(arg, &oid))
401 die(_("invalid unshallow line: %s"), reader.line);
402 if (!lookup_object(the_repository, &oid))
403 die(_("object not found: %s"), reader.line);
404 /* make sure that it is parsed as shallow */
405 if (!parse_object(the_repository, &oid))
406 die(_("error in object: %s"), reader.line);
407 if (unregister_shallow(&oid))
408 die(_("no shallow found: %s"), reader.line);
409 continue;
411 die(_("expected shallow/unshallow, got %s"), reader.line);
413 } else if (!args->stateless_rpc)
414 send_request(args, fd[1], &req_buf);
416 if (!args->stateless_rpc) {
417 /* If we aren't using the stateless-rpc interface
418 * we don't need to retain the headers.
420 strbuf_setlen(&req_buf, 0);
421 state_len = 0;
424 trace2_region_enter("fetch-pack", "negotiation_v0_v1", the_repository);
425 flushes = 0;
426 retval = -1;
427 while ((oid = negotiator->next(negotiator))) {
428 packet_buf_write(&req_buf, "have %s\n", oid_to_hex(oid));
429 print_verbose(args, "have %s", oid_to_hex(oid));
430 in_vain++;
431 if (flush_at <= ++count) {
432 int ack;
434 packet_buf_flush(&req_buf);
435 send_request(args, fd[1], &req_buf);
436 strbuf_setlen(&req_buf, state_len);
437 flushes++;
438 flush_at = next_flush(args->stateless_rpc, count);
441 * We keep one window "ahead" of the other side, and
442 * will wait for an ACK only on the next one
444 if (!args->stateless_rpc && count == INITIAL_FLUSH)
445 continue;
447 consume_shallow_list(args, &reader);
448 do {
449 ack = get_ack(&reader, result_oid);
450 if (ack)
451 print_verbose(args, _("got %s %d %s"), "ack",
452 ack, oid_to_hex(result_oid));
453 switch (ack) {
454 case ACK:
455 flushes = 0;
456 multi_ack = 0;
457 retval = 0;
458 goto done;
459 case ACK_common:
460 case ACK_ready:
461 case ACK_continue: {
462 struct commit *commit =
463 lookup_commit(the_repository,
464 result_oid);
465 int was_common;
467 if (!commit)
468 die(_("invalid commit %s"), oid_to_hex(result_oid));
469 was_common = negotiator->ack(negotiator, commit);
470 if (args->stateless_rpc
471 && ack == ACK_common
472 && !was_common) {
473 /* We need to replay the have for this object
474 * on the next RPC request so the peer knows
475 * it is in common with us.
477 const char *hex = oid_to_hex(result_oid);
478 packet_buf_write(&req_buf, "have %s\n", hex);
479 state_len = req_buf.len;
481 * Reset in_vain because an ack
482 * for this commit has not been
483 * seen.
485 in_vain = 0;
486 } else if (!args->stateless_rpc
487 || ack != ACK_common)
488 in_vain = 0;
489 retval = 0;
490 got_continue = 1;
491 if (ack == ACK_ready)
492 got_ready = 1;
493 break;
496 } while (ack);
497 flushes--;
498 if (got_continue && MAX_IN_VAIN < in_vain) {
499 print_verbose(args, _("giving up"));
500 break; /* give up */
502 if (got_ready)
503 break;
506 done:
507 trace2_region_leave("fetch-pack", "negotiation_v0_v1", the_repository);
508 if (!got_ready || !no_done) {
509 packet_buf_write(&req_buf, "done\n");
510 send_request(args, fd[1], &req_buf);
512 print_verbose(args, _("done"));
513 if (retval != 0) {
514 multi_ack = 0;
515 flushes++;
517 strbuf_release(&req_buf);
519 if (!got_ready || !no_done)
520 consume_shallow_list(args, &reader);
521 while (flushes || multi_ack) {
522 int ack = get_ack(&reader, result_oid);
523 if (ack) {
524 print_verbose(args, _("got %s (%d) %s"), "ack",
525 ack, oid_to_hex(result_oid));
526 if (ack == ACK)
527 return 0;
528 multi_ack = 1;
529 continue;
531 flushes--;
533 /* it is no error to fetch into a completely empty repo */
534 return count ? retval : 0;
537 static struct commit_list *complete;
539 static int mark_complete(const struct object_id *oid)
541 struct commit *commit = deref_without_lazy_fetch(oid, 1);
543 if (commit && !(commit->object.flags & COMPLETE)) {
544 commit->object.flags |= COMPLETE;
545 commit_list_insert(commit, &complete);
547 return 0;
550 static int mark_complete_oid(const char *refname, const struct object_id *oid,
551 int flag, void *cb_data)
553 return mark_complete(oid);
556 static void mark_recent_complete_commits(struct fetch_pack_args *args,
557 timestamp_t cutoff)
559 while (complete && cutoff <= complete->item->date) {
560 print_verbose(args, _("Marking %s as complete"),
561 oid_to_hex(&complete->item->object.oid));
562 pop_most_recent_commit(&complete, COMPLETE);
566 static void add_refs_to_oidset(struct oidset *oids, struct ref *refs)
568 for (; refs; refs = refs->next)
569 oidset_insert(oids, &refs->old_oid);
572 static int is_unmatched_ref(const struct ref *ref)
574 struct object_id oid;
575 const char *p;
576 return ref->match_status == REF_NOT_MATCHED &&
577 !parse_oid_hex(ref->name, &oid, &p) &&
578 *p == '\0' &&
579 oideq(&oid, &ref->old_oid);
582 static void filter_refs(struct fetch_pack_args *args,
583 struct ref **refs,
584 struct ref **sought, int nr_sought)
586 struct ref *newlist = NULL;
587 struct ref **newtail = &newlist;
588 struct ref *unmatched = NULL;
589 struct ref *ref, *next;
590 struct oidset tip_oids = OIDSET_INIT;
591 int i;
592 int strict = !(allow_unadvertised_object_request &
593 (ALLOW_TIP_SHA1 | ALLOW_REACHABLE_SHA1));
595 i = 0;
596 for (ref = *refs; ref; ref = next) {
597 int keep = 0;
598 next = ref->next;
600 if (starts_with(ref->name, "refs/") &&
601 check_refname_format(ref->name, 0)) {
603 * trash or a peeled value; do not even add it to
604 * unmatched list
606 free_one_ref(ref);
607 continue;
608 } else {
609 while (i < nr_sought) {
610 int cmp = strcmp(ref->name, sought[i]->name);
611 if (cmp < 0)
612 break; /* definitely do not have it */
613 else if (cmp == 0) {
614 keep = 1; /* definitely have it */
615 sought[i]->match_status = REF_MATCHED;
617 i++;
620 if (!keep && args->fetch_all &&
621 (!args->deepen || !starts_with(ref->name, "refs/tags/")))
622 keep = 1;
625 if (keep) {
626 *newtail = ref;
627 ref->next = NULL;
628 newtail = &ref->next;
629 } else {
630 ref->next = unmatched;
631 unmatched = ref;
635 if (strict) {
636 for (i = 0; i < nr_sought; i++) {
637 ref = sought[i];
638 if (!is_unmatched_ref(ref))
639 continue;
641 add_refs_to_oidset(&tip_oids, unmatched);
642 add_refs_to_oidset(&tip_oids, newlist);
643 break;
647 /* Append unmatched requests to the list */
648 for (i = 0; i < nr_sought; i++) {
649 ref = sought[i];
650 if (!is_unmatched_ref(ref))
651 continue;
653 if (!strict || oidset_contains(&tip_oids, &ref->old_oid)) {
654 ref->match_status = REF_MATCHED;
655 *newtail = copy_ref(ref);
656 newtail = &(*newtail)->next;
657 } else {
658 ref->match_status = REF_UNADVERTISED_NOT_ALLOWED;
662 oidset_clear(&tip_oids);
663 free_refs(unmatched);
665 *refs = newlist;
668 static void mark_alternate_complete(struct fetch_negotiator *unused,
669 struct object *obj)
671 mark_complete(&obj->oid);
674 struct loose_object_iter {
675 struct oidset *loose_object_set;
676 struct ref *refs;
680 * Mark recent commits available locally and reachable from a local ref as
681 * COMPLETE.
683 * The cutoff time for recency is determined by this heuristic: it is the
684 * earliest commit time of the objects in refs that are commits and that we know
685 * the commit time of.
687 static void mark_complete_and_common_ref(struct fetch_negotiator *negotiator,
688 struct fetch_pack_args *args,
689 struct ref **refs)
691 struct ref *ref;
692 int old_save_commit_buffer = save_commit_buffer;
693 timestamp_t cutoff = 0;
695 save_commit_buffer = 0;
697 trace2_region_enter("fetch-pack", "parse_remote_refs_and_find_cutoff", NULL);
698 for (ref = *refs; ref; ref = ref->next) {
699 struct object *o;
701 if (!has_object_file_with_flags(&ref->old_oid,
702 OBJECT_INFO_QUICK |
703 OBJECT_INFO_SKIP_FETCH_OBJECT))
704 continue;
705 o = parse_object(the_repository, &ref->old_oid);
706 if (!o)
707 continue;
710 * We already have it -- which may mean that we were
711 * in sync with the other side at some time after
712 * that (it is OK if we guess wrong here).
714 if (o->type == OBJ_COMMIT) {
715 struct commit *commit = (struct commit *)o;
716 if (!cutoff || cutoff < commit->date)
717 cutoff = commit->date;
720 trace2_region_leave("fetch-pack", "parse_remote_refs_and_find_cutoff", NULL);
723 * This block marks all local refs as COMPLETE, and then recursively marks all
724 * parents of those refs as COMPLETE.
726 trace2_region_enter("fetch-pack", "mark_complete_local_refs", NULL);
727 if (!args->deepen) {
728 for_each_rawref(mark_complete_oid, NULL);
729 for_each_cached_alternate(NULL, mark_alternate_complete);
730 commit_list_sort_by_date(&complete);
731 if (cutoff)
732 mark_recent_complete_commits(args, cutoff);
734 trace2_region_leave("fetch-pack", "mark_complete_local_refs", NULL);
737 * Mark all complete remote refs as common refs.
738 * Don't mark them common yet; the server has to be told so first.
740 trace2_region_enter("fetch-pack", "mark_common_remote_refs", NULL);
741 for (ref = *refs; ref; ref = ref->next) {
742 struct commit *c = deref_without_lazy_fetch(&ref->old_oid, 0);
744 if (!c || !(c->object.flags & COMPLETE))
745 continue;
747 negotiator->known_common(negotiator, c);
749 trace2_region_leave("fetch-pack", "mark_common_remote_refs", NULL);
751 save_commit_buffer = old_save_commit_buffer;
755 * Returns 1 if every object pointed to by the given remote refs is available
756 * locally and reachable from a local ref, and 0 otherwise.
758 static int everything_local(struct fetch_pack_args *args,
759 struct ref **refs)
761 struct ref *ref;
762 int retval;
764 for (retval = 1, ref = *refs; ref ; ref = ref->next) {
765 const struct object_id *remote = &ref->old_oid;
766 struct object *o;
768 o = lookup_object(the_repository, remote);
769 if (!o || !(o->flags & COMPLETE)) {
770 retval = 0;
771 print_verbose(args, "want %s (%s)", oid_to_hex(remote),
772 ref->name);
773 continue;
775 print_verbose(args, _("already have %s (%s)"), oid_to_hex(remote),
776 ref->name);
779 return retval;
782 static int sideband_demux(int in, int out, void *data)
784 int *xd = data;
785 int ret;
787 ret = recv_sideband("fetch-pack", xd[0], out);
788 close(out);
789 return ret;
792 static void create_promisor_file(const char *keep_name,
793 struct ref **sought, int nr_sought)
795 struct strbuf promisor_name = STRBUF_INIT;
796 int suffix_stripped;
798 strbuf_addstr(&promisor_name, keep_name);
799 suffix_stripped = strbuf_strip_suffix(&promisor_name, ".keep");
800 if (!suffix_stripped)
801 BUG("name of pack lockfile should end with .keep (was '%s')",
802 keep_name);
803 strbuf_addstr(&promisor_name, ".promisor");
805 write_promisor_file(promisor_name.buf, sought, nr_sought);
807 strbuf_release(&promisor_name);
810 static void parse_gitmodules_oids(int fd, struct oidset *gitmodules_oids)
812 int len = the_hash_algo->hexsz + 1; /* hash + NL */
814 do {
815 char hex_hash[GIT_MAX_HEXSZ + 1];
816 int read_len = read_in_full(fd, hex_hash, len);
817 struct object_id oid;
818 const char *end;
820 if (!read_len)
821 return;
822 if (read_len != len)
823 die("invalid length read %d", read_len);
824 if (parse_oid_hex(hex_hash, &oid, &end) || *end != '\n')
825 die("invalid hash");
826 oidset_insert(gitmodules_oids, &oid);
827 } while (1);
831 * If packfile URIs were provided, pass a non-NULL pointer to index_pack_args.
832 * The strings to pass as the --index-pack-arg arguments to http-fetch will be
833 * stored there. (It must be freed by the caller.)
835 static int get_pack(struct fetch_pack_args *args,
836 int xd[2], struct string_list *pack_lockfiles,
837 struct strvec *index_pack_args,
838 struct ref **sought, int nr_sought,
839 struct oidset *gitmodules_oids)
841 struct async demux;
842 int do_keep = args->keep_pack;
843 const char *cmd_name;
844 struct pack_header header;
845 int pass_header = 0;
846 struct child_process cmd = CHILD_PROCESS_INIT;
847 int fsck_objects = 0;
848 int ret;
850 memset(&demux, 0, sizeof(demux));
851 if (use_sideband) {
852 /* xd[] is talking with upload-pack; subprocess reads from
853 * xd[0], spits out band#2 to stderr, and feeds us band#1
854 * through demux->out.
856 demux.proc = sideband_demux;
857 demux.data = xd;
858 demux.out = -1;
859 demux.isolate_sigpipe = 1;
860 if (start_async(&demux))
861 die(_("fetch-pack: unable to fork off sideband demultiplexer"));
863 else
864 demux.out = xd[0];
866 if (!args->keep_pack && unpack_limit && !index_pack_args) {
868 if (read_pack_header(demux.out, &header))
869 die(_("protocol error: bad pack header"));
870 pass_header = 1;
871 if (ntohl(header.hdr_entries) < unpack_limit)
872 do_keep = 0;
873 else
874 do_keep = 1;
877 if (alternate_shallow_file) {
878 strvec_push(&cmd.args, "--shallow-file");
879 strvec_push(&cmd.args, alternate_shallow_file);
882 if (fetch_fsck_objects >= 0
883 ? fetch_fsck_objects
884 : transfer_fsck_objects >= 0
885 ? transfer_fsck_objects
886 : 0)
887 fsck_objects = 1;
889 if (do_keep || args->from_promisor || index_pack_args || fsck_objects) {
890 if (pack_lockfiles || fsck_objects)
891 cmd.out = -1;
892 cmd_name = "index-pack";
893 strvec_push(&cmd.args, cmd_name);
894 strvec_push(&cmd.args, "--stdin");
895 if (!args->quiet && !args->no_progress)
896 strvec_push(&cmd.args, "-v");
897 if (args->use_thin_pack)
898 strvec_push(&cmd.args, "--fix-thin");
899 if ((do_keep || index_pack_args) && (args->lock_pack || unpack_limit)) {
900 char hostname[HOST_NAME_MAX + 1];
901 if (xgethostname(hostname, sizeof(hostname)))
902 xsnprintf(hostname, sizeof(hostname), "localhost");
903 strvec_pushf(&cmd.args,
904 "--keep=fetch-pack %"PRIuMAX " on %s",
905 (uintmax_t)getpid(), hostname);
907 if (!index_pack_args && args->check_self_contained_and_connected)
908 strvec_push(&cmd.args, "--check-self-contained-and-connected");
909 else
911 * We cannot perform any connectivity checks because
912 * not all packs have been downloaded; let the caller
913 * have this responsibility.
915 args->check_self_contained_and_connected = 0;
917 if (args->from_promisor)
919 * create_promisor_file() may be called afterwards but
920 * we still need index-pack to know that this is a
921 * promisor pack. For example, if transfer.fsckobjects
922 * is true, index-pack needs to know that .gitmodules
923 * is a promisor object (so that it won't complain if
924 * it is missing).
926 strvec_push(&cmd.args, "--promisor");
928 else {
929 cmd_name = "unpack-objects";
930 strvec_push(&cmd.args, cmd_name);
931 if (args->quiet || args->no_progress)
932 strvec_push(&cmd.args, "-q");
933 args->check_self_contained_and_connected = 0;
936 if (pass_header)
937 strvec_pushf(&cmd.args, "--pack_header=%"PRIu32",%"PRIu32,
938 ntohl(header.hdr_version),
939 ntohl(header.hdr_entries));
940 if (fsck_objects) {
941 if (args->from_promisor || index_pack_args)
943 * We cannot use --strict in index-pack because it
944 * checks both broken objects and links, but we only
945 * want to check for broken objects.
947 strvec_push(&cmd.args, "--fsck-objects");
948 else
949 strvec_pushf(&cmd.args, "--strict%s",
950 fsck_msg_types.buf);
953 if (index_pack_args) {
954 int i;
956 for (i = 0; i < cmd.args.nr; i++)
957 strvec_push(index_pack_args, cmd.args.v[i]);
960 sigchain_push(SIGPIPE, SIG_IGN);
962 cmd.in = demux.out;
963 cmd.git_cmd = 1;
964 if (start_command(&cmd))
965 die(_("fetch-pack: unable to fork off %s"), cmd_name);
966 if (do_keep && (pack_lockfiles || fsck_objects)) {
967 int is_well_formed;
968 char *pack_lockfile = index_pack_lockfile(cmd.out, &is_well_formed);
970 if (!is_well_formed)
971 die(_("fetch-pack: invalid index-pack output"));
972 if (pack_lockfile)
973 string_list_append_nodup(pack_lockfiles, pack_lockfile);
974 parse_gitmodules_oids(cmd.out, gitmodules_oids);
975 close(cmd.out);
978 if (!use_sideband)
979 /* Closed by start_command() */
980 xd[0] = -1;
982 ret = finish_command(&cmd);
983 if (!ret || (args->check_self_contained_and_connected && ret == 1))
984 args->self_contained_and_connected =
985 args->check_self_contained_and_connected &&
986 ret == 0;
987 else
988 die(_("%s failed"), cmd_name);
989 if (use_sideband && finish_async(&demux))
990 die(_("error in sideband demultiplexer"));
992 sigchain_pop(SIGPIPE);
995 * Now that index-pack has succeeded, write the promisor file using the
996 * obtained .keep filename if necessary
998 if (do_keep && pack_lockfiles && pack_lockfiles->nr && args->from_promisor)
999 create_promisor_file(pack_lockfiles->items[0].string, sought, nr_sought);
1001 return 0;
1004 static int cmp_ref_by_name(const void *a_, const void *b_)
1006 const struct ref *a = *((const struct ref **)a_);
1007 const struct ref *b = *((const struct ref **)b_);
1008 return strcmp(a->name, b->name);
1011 static struct ref *do_fetch_pack(struct fetch_pack_args *args,
1012 int fd[2],
1013 const struct ref *orig_ref,
1014 struct ref **sought, int nr_sought,
1015 struct shallow_info *si,
1016 struct string_list *pack_lockfiles)
1018 struct repository *r = the_repository;
1019 struct ref *ref = copy_ref_list(orig_ref);
1020 struct object_id oid;
1021 const char *agent_feature;
1022 int agent_len;
1023 struct fetch_negotiator negotiator_alloc;
1024 struct fetch_negotiator *negotiator;
1026 negotiator = &negotiator_alloc;
1027 fetch_negotiator_init(r, negotiator);
1029 sort_ref_list(&ref, ref_compare_name);
1030 QSORT(sought, nr_sought, cmp_ref_by_name);
1032 if ((agent_feature = server_feature_value("agent", &agent_len))) {
1033 agent_supported = 1;
1034 if (agent_len)
1035 print_verbose(args, _("Server version is %.*s"),
1036 agent_len, agent_feature);
1039 if (!server_supports("session-id"))
1040 advertise_sid = 0;
1042 if (server_supports("shallow"))
1043 print_verbose(args, _("Server supports %s"), "shallow");
1044 else if (args->depth > 0 || is_repository_shallow(r))
1045 die(_("Server does not support shallow clients"));
1046 if (args->depth > 0 || args->deepen_since || args->deepen_not)
1047 args->deepen = 1;
1048 if (server_supports("multi_ack_detailed")) {
1049 print_verbose(args, _("Server supports %s"), "multi_ack_detailed");
1050 multi_ack = 2;
1051 if (server_supports("no-done")) {
1052 print_verbose(args, _("Server supports %s"), "no-done");
1053 if (args->stateless_rpc)
1054 no_done = 1;
1057 else if (server_supports("multi_ack")) {
1058 print_verbose(args, _("Server supports %s"), "multi_ack");
1059 multi_ack = 1;
1061 if (server_supports("side-band-64k")) {
1062 print_verbose(args, _("Server supports %s"), "side-band-64k");
1063 use_sideband = 2;
1065 else if (server_supports("side-band")) {
1066 print_verbose(args, _("Server supports %s"), "side-band");
1067 use_sideband = 1;
1069 if (server_supports("allow-tip-sha1-in-want")) {
1070 print_verbose(args, _("Server supports %s"), "allow-tip-sha1-in-want");
1071 allow_unadvertised_object_request |= ALLOW_TIP_SHA1;
1073 if (server_supports("allow-reachable-sha1-in-want")) {
1074 print_verbose(args, _("Server supports %s"), "allow-reachable-sha1-in-want");
1075 allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
1077 if (server_supports("thin-pack"))
1078 print_verbose(args, _("Server supports %s"), "thin-pack");
1079 else
1080 args->use_thin_pack = 0;
1081 if (server_supports("no-progress"))
1082 print_verbose(args, _("Server supports %s"), "no-progress");
1083 else
1084 args->no_progress = 0;
1085 if (server_supports("include-tag"))
1086 print_verbose(args, _("Server supports %s"), "include-tag");
1087 else
1088 args->include_tag = 0;
1089 if (server_supports("ofs-delta"))
1090 print_verbose(args, _("Server supports %s"), "ofs-delta");
1091 else
1092 prefer_ofs_delta = 0;
1094 if (server_supports("filter")) {
1095 server_supports_filtering = 1;
1096 print_verbose(args, _("Server supports %s"), "filter");
1097 } else if (args->filter_options.choice) {
1098 warning("filtering not recognized by server, ignoring");
1101 if (server_supports("deepen-since")) {
1102 print_verbose(args, _("Server supports %s"), "deepen-since");
1103 deepen_since_ok = 1;
1104 } else if (args->deepen_since)
1105 die(_("Server does not support --shallow-since"));
1106 if (server_supports("deepen-not")) {
1107 print_verbose(args, _("Server supports %s"), "deepen-not");
1108 deepen_not_ok = 1;
1109 } else if (args->deepen_not)
1110 die(_("Server does not support --shallow-exclude"));
1111 if (server_supports("deepen-relative"))
1112 print_verbose(args, _("Server supports %s"), "deepen-relative");
1113 else if (args->deepen_relative)
1114 die(_("Server does not support --deepen"));
1115 if (!server_supports_hash(the_hash_algo->name, NULL))
1116 die(_("Server does not support this repository's object format"));
1118 mark_complete_and_common_ref(negotiator, args, &ref);
1119 filter_refs(args, &ref, sought, nr_sought);
1120 if (everything_local(args, &ref)) {
1121 packet_flush(fd[1]);
1122 goto all_done;
1124 if (find_common(negotiator, args, fd, &oid, ref) < 0)
1125 if (!args->keep_pack)
1126 /* When cloning, it is not unusual to have
1127 * no common commit.
1129 warning(_("no common commits"));
1131 if (args->stateless_rpc)
1132 packet_flush(fd[1]);
1133 if (args->deepen)
1134 setup_alternate_shallow(&shallow_lock, &alternate_shallow_file,
1135 NULL);
1136 else if (si->nr_ours || si->nr_theirs) {
1137 if (args->reject_shallow_remote)
1138 die(_("source repository is shallow, reject to clone."));
1139 alternate_shallow_file = setup_temporary_shallow(si->shallow);
1140 } else
1141 alternate_shallow_file = NULL;
1142 if (get_pack(args, fd, pack_lockfiles, NULL, sought, nr_sought,
1143 &fsck_options.gitmodules_found))
1144 die(_("git fetch-pack: fetch failed."));
1145 if (fsck_finish(&fsck_options))
1146 die("fsck failed");
1148 all_done:
1149 if (negotiator)
1150 negotiator->release(negotiator);
1151 return ref;
1154 static void add_shallow_requests(struct strbuf *req_buf,
1155 const struct fetch_pack_args *args)
1157 if (is_repository_shallow(the_repository))
1158 write_shallow_commits(req_buf, 1, NULL);
1159 if (args->depth > 0)
1160 packet_buf_write(req_buf, "deepen %d", args->depth);
1161 if (args->deepen_since) {
1162 timestamp_t max_age = approxidate(args->deepen_since);
1163 packet_buf_write(req_buf, "deepen-since %"PRItime, max_age);
1165 if (args->deepen_not) {
1166 int i;
1167 for (i = 0; i < args->deepen_not->nr; i++) {
1168 struct string_list_item *s = args->deepen_not->items + i;
1169 packet_buf_write(req_buf, "deepen-not %s", s->string);
1172 if (args->deepen_relative)
1173 packet_buf_write(req_buf, "deepen-relative\n");
1176 static void add_wants(const struct ref *wants, struct strbuf *req_buf)
1178 int use_ref_in_want = server_supports_feature("fetch", "ref-in-want", 0);
1180 for ( ; wants ; wants = wants->next) {
1181 const struct object_id *remote = &wants->old_oid;
1182 struct object *o;
1185 * If that object is complete (i.e. it is an ancestor of a
1186 * local ref), we tell them we have it but do not have to
1187 * tell them about its ancestors, which they already know
1188 * about.
1190 * We use lookup_object here because we are only
1191 * interested in the case we *know* the object is
1192 * reachable and we have already scanned it.
1194 if (((o = lookup_object(the_repository, remote)) != NULL) &&
1195 (o->flags & COMPLETE)) {
1196 continue;
1199 if (!use_ref_in_want || wants->exact_oid)
1200 packet_buf_write(req_buf, "want %s\n", oid_to_hex(remote));
1201 else
1202 packet_buf_write(req_buf, "want-ref %s\n", wants->name);
1206 static void add_common(struct strbuf *req_buf, struct oidset *common)
1208 struct oidset_iter iter;
1209 const struct object_id *oid;
1210 oidset_iter_init(common, &iter);
1212 while ((oid = oidset_iter_next(&iter))) {
1213 packet_buf_write(req_buf, "have %s\n", oid_to_hex(oid));
1217 static int add_haves(struct fetch_negotiator *negotiator,
1218 struct strbuf *req_buf,
1219 int *haves_to_send)
1221 int haves_added = 0;
1222 const struct object_id *oid;
1224 while ((oid = negotiator->next(negotiator))) {
1225 packet_buf_write(req_buf, "have %s\n", oid_to_hex(oid));
1226 if (++haves_added >= *haves_to_send)
1227 break;
1230 /* Increase haves to send on next round */
1231 *haves_to_send = next_flush(1, *haves_to_send);
1233 return haves_added;
1236 static void write_fetch_command_and_capabilities(struct strbuf *req_buf,
1237 const struct string_list *server_options)
1239 const char *hash_name;
1241 if (server_supports_v2("fetch", 1))
1242 packet_buf_write(req_buf, "command=fetch");
1243 if (server_supports_v2("agent", 0))
1244 packet_buf_write(req_buf, "agent=%s", git_user_agent_sanitized());
1245 if (advertise_sid && server_supports_v2("session-id", 0))
1246 packet_buf_write(req_buf, "session-id=%s", trace2_session_id());
1247 if (server_options && server_options->nr &&
1248 server_supports_v2("server-option", 1)) {
1249 int i;
1250 for (i = 0; i < server_options->nr; i++)
1251 packet_buf_write(req_buf, "server-option=%s",
1252 server_options->items[i].string);
1255 if (server_feature_v2("object-format", &hash_name)) {
1256 int hash_algo = hash_algo_by_name(hash_name);
1257 if (hash_algo_by_ptr(the_hash_algo) != hash_algo)
1258 die(_("mismatched algorithms: client %s; server %s"),
1259 the_hash_algo->name, hash_name);
1260 packet_buf_write(req_buf, "object-format=%s", the_hash_algo->name);
1261 } else if (hash_algo_by_ptr(the_hash_algo) != GIT_HASH_SHA1) {
1262 die(_("the server does not support algorithm '%s'"),
1263 the_hash_algo->name);
1265 packet_buf_delim(req_buf);
1268 static int send_fetch_request(struct fetch_negotiator *negotiator, int fd_out,
1269 struct fetch_pack_args *args,
1270 const struct ref *wants, struct oidset *common,
1271 int *haves_to_send, int *in_vain,
1272 int sideband_all, int seen_ack)
1274 int haves_added;
1275 int done_sent = 0;
1276 struct strbuf req_buf = STRBUF_INIT;
1278 write_fetch_command_and_capabilities(&req_buf, args->server_options);
1280 if (args->use_thin_pack)
1281 packet_buf_write(&req_buf, "thin-pack");
1282 if (args->no_progress)
1283 packet_buf_write(&req_buf, "no-progress");
1284 if (args->include_tag)
1285 packet_buf_write(&req_buf, "include-tag");
1286 if (prefer_ofs_delta)
1287 packet_buf_write(&req_buf, "ofs-delta");
1288 if (sideband_all)
1289 packet_buf_write(&req_buf, "sideband-all");
1291 /* Add shallow-info and deepen request */
1292 if (server_supports_feature("fetch", "shallow", 0))
1293 add_shallow_requests(&req_buf, args);
1294 else if (is_repository_shallow(the_repository) || args->deepen)
1295 die(_("Server does not support shallow requests"));
1297 /* Add filter */
1298 if (server_supports_feature("fetch", "filter", 0) &&
1299 args->filter_options.choice) {
1300 const char *spec =
1301 expand_list_objects_filter_spec(&args->filter_options);
1302 print_verbose(args, _("Server supports filter"));
1303 packet_buf_write(&req_buf, "filter %s", spec);
1304 } else if (args->filter_options.choice) {
1305 warning("filtering not recognized by server, ignoring");
1308 if (server_supports_feature("fetch", "packfile-uris", 0)) {
1309 int i;
1310 struct strbuf to_send = STRBUF_INIT;
1312 for (i = 0; i < uri_protocols.nr; i++) {
1313 const char *s = uri_protocols.items[i].string;
1315 if (!strcmp(s, "https") || !strcmp(s, "http")) {
1316 if (to_send.len)
1317 strbuf_addch(&to_send, ',');
1318 strbuf_addstr(&to_send, s);
1321 if (to_send.len) {
1322 packet_buf_write(&req_buf, "packfile-uris %s",
1323 to_send.buf);
1324 strbuf_release(&to_send);
1328 /* add wants */
1329 add_wants(wants, &req_buf);
1331 /* Add all of the common commits we've found in previous rounds */
1332 add_common(&req_buf, common);
1334 haves_added = add_haves(negotiator, &req_buf, haves_to_send);
1335 *in_vain += haves_added;
1336 if (!haves_added || (seen_ack && *in_vain >= MAX_IN_VAIN)) {
1337 /* Send Done */
1338 packet_buf_write(&req_buf, "done\n");
1339 done_sent = 1;
1342 /* Send request */
1343 packet_buf_flush(&req_buf);
1344 if (write_in_full(fd_out, req_buf.buf, req_buf.len) < 0)
1345 die_errno(_("unable to write request to remote"));
1347 strbuf_release(&req_buf);
1348 return done_sent;
1352 * Processes a section header in a server's response and checks if it matches
1353 * `section`. If the value of `peek` is 1, the header line will be peeked (and
1354 * not consumed); if 0, the line will be consumed and the function will die if
1355 * the section header doesn't match what was expected.
1357 static int process_section_header(struct packet_reader *reader,
1358 const char *section, int peek)
1360 int ret;
1362 if (packet_reader_peek(reader) != PACKET_READ_NORMAL)
1363 die(_("error reading section header '%s'"), section);
1365 ret = !strcmp(reader->line, section);
1367 if (!peek) {
1368 if (!ret)
1369 die(_("expected '%s', received '%s'"),
1370 section, reader->line);
1371 packet_reader_read(reader);
1374 return ret;
1377 static int process_ack(struct fetch_negotiator *negotiator,
1378 struct packet_reader *reader,
1379 struct object_id *common_oid,
1380 int *received_ready)
1382 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1383 const char *arg;
1385 if (!strcmp(reader->line, "NAK"))
1386 continue;
1388 if (skip_prefix(reader->line, "ACK ", &arg)) {
1389 if (!get_oid_hex(arg, common_oid)) {
1390 struct commit *commit;
1391 commit = lookup_commit(the_repository, common_oid);
1392 if (negotiator)
1393 negotiator->ack(negotiator, commit);
1395 return 1;
1398 if (!strcmp(reader->line, "ready")) {
1399 *received_ready = 1;
1400 continue;
1403 die(_("unexpected acknowledgment line: '%s'"), reader->line);
1406 if (reader->status != PACKET_READ_FLUSH &&
1407 reader->status != PACKET_READ_DELIM)
1408 die(_("error processing acks: %d"), reader->status);
1411 * If an "acknowledgments" section is sent, a packfile is sent if and
1412 * only if "ready" was sent in this section. The other sections
1413 * ("shallow-info" and "wanted-refs") are sent only if a packfile is
1414 * sent. Therefore, a DELIM is expected if "ready" is sent, and a FLUSH
1415 * otherwise.
1417 if (*received_ready && reader->status != PACKET_READ_DELIM)
1419 * TRANSLATORS: The parameter will be 'ready', a protocol
1420 * keyword.
1422 die(_("expected packfile to be sent after '%s'"), "ready");
1423 if (!*received_ready && reader->status != PACKET_READ_FLUSH)
1425 * TRANSLATORS: The parameter will be 'ready', a protocol
1426 * keyword.
1428 die(_("expected no other sections to be sent after no '%s'"), "ready");
1430 return 0;
1433 static void receive_shallow_info(struct fetch_pack_args *args,
1434 struct packet_reader *reader,
1435 struct oid_array *shallows,
1436 struct shallow_info *si)
1438 int unshallow_received = 0;
1440 process_section_header(reader, "shallow-info", 0);
1441 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1442 const char *arg;
1443 struct object_id oid;
1445 if (skip_prefix(reader->line, "shallow ", &arg)) {
1446 if (get_oid_hex(arg, &oid))
1447 die(_("invalid shallow line: %s"), reader->line);
1448 oid_array_append(shallows, &oid);
1449 continue;
1451 if (skip_prefix(reader->line, "unshallow ", &arg)) {
1452 if (get_oid_hex(arg, &oid))
1453 die(_("invalid unshallow line: %s"), reader->line);
1454 if (!lookup_object(the_repository, &oid))
1455 die(_("object not found: %s"), reader->line);
1456 /* make sure that it is parsed as shallow */
1457 if (!parse_object(the_repository, &oid))
1458 die(_("error in object: %s"), reader->line);
1459 if (unregister_shallow(&oid))
1460 die(_("no shallow found: %s"), reader->line);
1461 unshallow_received = 1;
1462 continue;
1464 die(_("expected shallow/unshallow, got %s"), reader->line);
1467 if (reader->status != PACKET_READ_FLUSH &&
1468 reader->status != PACKET_READ_DELIM)
1469 die(_("error processing shallow info: %d"), reader->status);
1471 if (args->deepen || unshallow_received) {
1473 * Treat these as shallow lines caused by our depth settings.
1474 * In v0, these lines cannot cause refs to be rejected; do the
1475 * same.
1477 int i;
1479 for (i = 0; i < shallows->nr; i++)
1480 register_shallow(the_repository, &shallows->oid[i]);
1481 setup_alternate_shallow(&shallow_lock, &alternate_shallow_file,
1482 NULL);
1483 args->deepen = 1;
1484 } else if (shallows->nr) {
1486 * Treat these as shallow lines caused by the remote being
1487 * shallow. In v0, remote refs that reach these objects are
1488 * rejected (unless --update-shallow is set); do the same.
1490 prepare_shallow_info(si, shallows);
1491 if (si->nr_ours || si->nr_theirs) {
1492 if (args->reject_shallow_remote)
1493 die(_("source repository is shallow, reject to clone."));
1494 alternate_shallow_file =
1495 setup_temporary_shallow(si->shallow);
1496 } else
1497 alternate_shallow_file = NULL;
1498 } else {
1499 alternate_shallow_file = NULL;
1503 static int cmp_name_ref(const void *name, const void *ref)
1505 return strcmp(name, (*(struct ref **)ref)->name);
1508 static void receive_wanted_refs(struct packet_reader *reader,
1509 struct ref **sought, int nr_sought)
1511 process_section_header(reader, "wanted-refs", 0);
1512 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1513 struct object_id oid;
1514 const char *end;
1515 struct ref **found;
1517 if (parse_oid_hex(reader->line, &oid, &end) || *end++ != ' ')
1518 die(_("expected wanted-ref, got '%s'"), reader->line);
1520 found = bsearch(end, sought, nr_sought, sizeof(*sought),
1521 cmp_name_ref);
1522 if (!found)
1523 die(_("unexpected wanted-ref: '%s'"), reader->line);
1524 oidcpy(&(*found)->old_oid, &oid);
1527 if (reader->status != PACKET_READ_DELIM)
1528 die(_("error processing wanted refs: %d"), reader->status);
1531 static void receive_packfile_uris(struct packet_reader *reader,
1532 struct string_list *uris)
1534 process_section_header(reader, "packfile-uris", 0);
1535 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1536 if (reader->pktlen < the_hash_algo->hexsz ||
1537 reader->line[the_hash_algo->hexsz] != ' ')
1538 die("expected '<hash> <uri>', got: %s\n", reader->line);
1540 string_list_append(uris, reader->line);
1542 if (reader->status != PACKET_READ_DELIM)
1543 die("expected DELIM");
1546 enum fetch_state {
1547 FETCH_CHECK_LOCAL = 0,
1548 FETCH_SEND_REQUEST,
1549 FETCH_PROCESS_ACKS,
1550 FETCH_GET_PACK,
1551 FETCH_DONE,
1554 static void do_check_stateless_delimiter(int stateless_rpc,
1555 struct packet_reader *reader)
1557 check_stateless_delimiter(stateless_rpc, reader,
1558 _("git fetch-pack: expected response end packet"));
1561 static struct ref *do_fetch_pack_v2(struct fetch_pack_args *args,
1562 int fd[2],
1563 const struct ref *orig_ref,
1564 struct ref **sought, int nr_sought,
1565 struct oid_array *shallows,
1566 struct shallow_info *si,
1567 struct string_list *pack_lockfiles)
1569 struct repository *r = the_repository;
1570 struct ref *ref = copy_ref_list(orig_ref);
1571 enum fetch_state state = FETCH_CHECK_LOCAL;
1572 struct oidset common = OIDSET_INIT;
1573 struct packet_reader reader;
1574 int in_vain = 0, negotiation_started = 0;
1575 int haves_to_send = INITIAL_FLUSH;
1576 struct fetch_negotiator negotiator_alloc;
1577 struct fetch_negotiator *negotiator;
1578 int seen_ack = 0;
1579 struct object_id common_oid;
1580 int received_ready = 0;
1581 struct string_list packfile_uris = STRING_LIST_INIT_DUP;
1582 int i;
1583 struct strvec index_pack_args = STRVEC_INIT;
1585 negotiator = &negotiator_alloc;
1586 fetch_negotiator_init(r, negotiator);
1588 packet_reader_init(&reader, fd[0], NULL, 0,
1589 PACKET_READ_CHOMP_NEWLINE |
1590 PACKET_READ_DIE_ON_ERR_PACKET);
1591 if (git_env_bool("GIT_TEST_SIDEBAND_ALL", 1) &&
1592 server_supports_feature("fetch", "sideband-all", 0)) {
1593 reader.use_sideband = 1;
1594 reader.me = "fetch-pack";
1597 while (state != FETCH_DONE) {
1598 switch (state) {
1599 case FETCH_CHECK_LOCAL:
1600 sort_ref_list(&ref, ref_compare_name);
1601 QSORT(sought, nr_sought, cmp_ref_by_name);
1603 /* v2 supports these by default */
1604 allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
1605 use_sideband = 2;
1606 if (args->depth > 0 || args->deepen_since || args->deepen_not)
1607 args->deepen = 1;
1609 /* Filter 'ref' by 'sought' and those that aren't local */
1610 mark_complete_and_common_ref(negotiator, args, &ref);
1611 filter_refs(args, &ref, sought, nr_sought);
1612 if (everything_local(args, &ref))
1613 state = FETCH_DONE;
1614 else
1615 state = FETCH_SEND_REQUEST;
1617 mark_tips(negotiator, args->negotiation_tips);
1618 for_each_cached_alternate(negotiator,
1619 insert_one_alternate_object);
1620 break;
1621 case FETCH_SEND_REQUEST:
1622 if (!negotiation_started) {
1623 negotiation_started = 1;
1624 trace2_region_enter("fetch-pack",
1625 "negotiation_v2",
1626 the_repository);
1628 if (send_fetch_request(negotiator, fd[1], args, ref,
1629 &common,
1630 &haves_to_send, &in_vain,
1631 reader.use_sideband,
1632 seen_ack))
1633 state = FETCH_GET_PACK;
1634 else
1635 state = FETCH_PROCESS_ACKS;
1636 break;
1637 case FETCH_PROCESS_ACKS:
1638 /* Process ACKs/NAKs */
1639 process_section_header(&reader, "acknowledgments", 0);
1640 while (process_ack(negotiator, &reader, &common_oid,
1641 &received_ready)) {
1642 in_vain = 0;
1643 seen_ack = 1;
1644 oidset_insert(&common, &common_oid);
1646 if (received_ready) {
1648 * Don't check for response delimiter; get_pack() will
1649 * read the rest of this response.
1651 state = FETCH_GET_PACK;
1652 } else {
1653 do_check_stateless_delimiter(args->stateless_rpc, &reader);
1654 state = FETCH_SEND_REQUEST;
1656 break;
1657 case FETCH_GET_PACK:
1658 trace2_region_leave("fetch-pack",
1659 "negotiation_v2",
1660 the_repository);
1661 /* Check for shallow-info section */
1662 if (process_section_header(&reader, "shallow-info", 1))
1663 receive_shallow_info(args, &reader, shallows, si);
1665 if (process_section_header(&reader, "wanted-refs", 1))
1666 receive_wanted_refs(&reader, sought, nr_sought);
1668 /* get the pack(s) */
1669 if (git_env_bool("GIT_TRACE_REDACT", 1))
1670 reader.options |= PACKET_READ_REDACT_URI_PATH;
1671 if (process_section_header(&reader, "packfile-uris", 1))
1672 receive_packfile_uris(&reader, &packfile_uris);
1673 /* We don't expect more URIs. Reset to avoid expensive URI check. */
1674 reader.options &= ~PACKET_READ_REDACT_URI_PATH;
1676 process_section_header(&reader, "packfile", 0);
1679 * this is the final request we'll make of the server;
1680 * do a half-duplex shutdown to indicate that they can
1681 * hang up as soon as the pack is sent.
1683 close(fd[1]);
1684 fd[1] = -1;
1686 if (get_pack(args, fd, pack_lockfiles,
1687 packfile_uris.nr ? &index_pack_args : NULL,
1688 sought, nr_sought, &fsck_options.gitmodules_found))
1689 die(_("git fetch-pack: fetch failed."));
1690 do_check_stateless_delimiter(args->stateless_rpc, &reader);
1692 state = FETCH_DONE;
1693 break;
1694 case FETCH_DONE:
1695 continue;
1699 for (i = 0; i < packfile_uris.nr; i++) {
1700 int j;
1701 struct child_process cmd = CHILD_PROCESS_INIT;
1702 char packname[GIT_MAX_HEXSZ + 1];
1703 const char *uri = packfile_uris.items[i].string +
1704 the_hash_algo->hexsz + 1;
1706 strvec_push(&cmd.args, "http-fetch");
1707 strvec_pushf(&cmd.args, "--packfile=%.*s",
1708 (int) the_hash_algo->hexsz,
1709 packfile_uris.items[i].string);
1710 for (j = 0; j < index_pack_args.nr; j++)
1711 strvec_pushf(&cmd.args, "--index-pack-arg=%s",
1712 index_pack_args.v[j]);
1713 strvec_push(&cmd.args, uri);
1714 cmd.git_cmd = 1;
1715 cmd.no_stdin = 1;
1716 cmd.out = -1;
1717 if (start_command(&cmd))
1718 die("fetch-pack: unable to spawn http-fetch");
1720 if (read_in_full(cmd.out, packname, 5) < 0 ||
1721 memcmp(packname, "keep\t", 5))
1722 die("fetch-pack: expected keep then TAB at start of http-fetch output");
1724 if (read_in_full(cmd.out, packname,
1725 the_hash_algo->hexsz + 1) < 0 ||
1726 packname[the_hash_algo->hexsz] != '\n')
1727 die("fetch-pack: expected hash then LF at end of http-fetch output");
1729 packname[the_hash_algo->hexsz] = '\0';
1731 parse_gitmodules_oids(cmd.out, &fsck_options.gitmodules_found);
1733 close(cmd.out);
1735 if (finish_command(&cmd))
1736 die("fetch-pack: unable to finish http-fetch");
1738 if (memcmp(packfile_uris.items[i].string, packname,
1739 the_hash_algo->hexsz))
1740 die("fetch-pack: pack downloaded from %s does not match expected hash %.*s",
1741 uri, (int) the_hash_algo->hexsz,
1742 packfile_uris.items[i].string);
1744 string_list_append_nodup(pack_lockfiles,
1745 xstrfmt("%s/pack/pack-%s.keep",
1746 get_object_directory(),
1747 packname));
1749 string_list_clear(&packfile_uris, 0);
1750 strvec_clear(&index_pack_args);
1752 if (fsck_finish(&fsck_options))
1753 die("fsck failed");
1755 if (negotiator)
1756 negotiator->release(negotiator);
1758 oidset_clear(&common);
1759 return ref;
1762 static int fetch_pack_config_cb(const char *var, const char *value, void *cb)
1764 if (strcmp(var, "fetch.fsck.skiplist") == 0) {
1765 const char *path;
1767 if (git_config_pathname(&path, var, value))
1768 return 1;
1769 strbuf_addf(&fsck_msg_types, "%cskiplist=%s",
1770 fsck_msg_types.len ? ',' : '=', path);
1771 free((char *)path);
1772 return 0;
1775 if (skip_prefix(var, "fetch.fsck.", &var)) {
1776 if (is_valid_msg_type(var, value))
1777 strbuf_addf(&fsck_msg_types, "%c%s=%s",
1778 fsck_msg_types.len ? ',' : '=', var, value);
1779 else
1780 warning("Skipping unknown msg id '%s'", var);
1781 return 0;
1784 return git_default_config(var, value, cb);
1787 static void fetch_pack_config(void)
1789 git_config_get_int("fetch.unpacklimit", &fetch_unpack_limit);
1790 git_config_get_int("transfer.unpacklimit", &transfer_unpack_limit);
1791 git_config_get_bool("repack.usedeltabaseoffset", &prefer_ofs_delta);
1792 git_config_get_bool("fetch.fsckobjects", &fetch_fsck_objects);
1793 git_config_get_bool("transfer.fsckobjects", &transfer_fsck_objects);
1794 git_config_get_bool("transfer.advertisesid", &advertise_sid);
1795 if (!uri_protocols.nr) {
1796 char *str;
1798 if (!git_config_get_string("fetch.uriprotocols", &str) && str) {
1799 string_list_split(&uri_protocols, str, ',', -1);
1800 free(str);
1804 git_config(fetch_pack_config_cb, NULL);
1807 static void fetch_pack_setup(void)
1809 static int did_setup;
1810 if (did_setup)
1811 return;
1812 fetch_pack_config();
1813 if (0 <= transfer_unpack_limit)
1814 unpack_limit = transfer_unpack_limit;
1815 else if (0 <= fetch_unpack_limit)
1816 unpack_limit = fetch_unpack_limit;
1817 did_setup = 1;
1820 static int remove_duplicates_in_refs(struct ref **ref, int nr)
1822 struct string_list names = STRING_LIST_INIT_NODUP;
1823 int src, dst;
1825 for (src = dst = 0; src < nr; src++) {
1826 struct string_list_item *item;
1827 item = string_list_insert(&names, ref[src]->name);
1828 if (item->util)
1829 continue; /* already have it */
1830 item->util = ref[src];
1831 if (src != dst)
1832 ref[dst] = ref[src];
1833 dst++;
1835 for (src = dst; src < nr; src++)
1836 ref[src] = NULL;
1837 string_list_clear(&names, 0);
1838 return dst;
1841 static void update_shallow(struct fetch_pack_args *args,
1842 struct ref **sought, int nr_sought,
1843 struct shallow_info *si)
1845 struct oid_array ref = OID_ARRAY_INIT;
1846 int *status;
1847 int i;
1849 if (args->deepen && alternate_shallow_file) {
1850 if (*alternate_shallow_file == '\0') { /* --unshallow */
1851 unlink_or_warn(git_path_shallow(the_repository));
1852 rollback_shallow_file(the_repository, &shallow_lock);
1853 } else
1854 commit_shallow_file(the_repository, &shallow_lock);
1855 alternate_shallow_file = NULL;
1856 return;
1859 if (!si->shallow || !si->shallow->nr)
1860 return;
1862 if (args->cloning) {
1864 * remote is shallow, but this is a clone, there are
1865 * no objects in repo to worry about. Accept any
1866 * shallow points that exist in the pack (iow in repo
1867 * after get_pack() and reprepare_packed_git())
1869 struct oid_array extra = OID_ARRAY_INIT;
1870 struct object_id *oid = si->shallow->oid;
1871 for (i = 0; i < si->shallow->nr; i++)
1872 if (has_object_file(&oid[i]))
1873 oid_array_append(&extra, &oid[i]);
1874 if (extra.nr) {
1875 setup_alternate_shallow(&shallow_lock,
1876 &alternate_shallow_file,
1877 &extra);
1878 commit_shallow_file(the_repository, &shallow_lock);
1879 alternate_shallow_file = NULL;
1881 oid_array_clear(&extra);
1882 return;
1885 if (!si->nr_ours && !si->nr_theirs)
1886 return;
1888 remove_nonexistent_theirs_shallow(si);
1889 if (!si->nr_ours && !si->nr_theirs)
1890 return;
1891 for (i = 0; i < nr_sought; i++)
1892 oid_array_append(&ref, &sought[i]->old_oid);
1893 si->ref = &ref;
1895 if (args->update_shallow) {
1897 * remote is also shallow, .git/shallow may be updated
1898 * so all refs can be accepted. Make sure we only add
1899 * shallow roots that are actually reachable from new
1900 * refs.
1902 struct oid_array extra = OID_ARRAY_INIT;
1903 struct object_id *oid = si->shallow->oid;
1904 assign_shallow_commits_to_refs(si, NULL, NULL);
1905 if (!si->nr_ours && !si->nr_theirs) {
1906 oid_array_clear(&ref);
1907 return;
1909 for (i = 0; i < si->nr_ours; i++)
1910 oid_array_append(&extra, &oid[si->ours[i]]);
1911 for (i = 0; i < si->nr_theirs; i++)
1912 oid_array_append(&extra, &oid[si->theirs[i]]);
1913 setup_alternate_shallow(&shallow_lock,
1914 &alternate_shallow_file,
1915 &extra);
1916 commit_shallow_file(the_repository, &shallow_lock);
1917 oid_array_clear(&extra);
1918 oid_array_clear(&ref);
1919 alternate_shallow_file = NULL;
1920 return;
1924 * remote is also shallow, check what ref is safe to update
1925 * without updating .git/shallow
1927 CALLOC_ARRAY(status, nr_sought);
1928 assign_shallow_commits_to_refs(si, NULL, status);
1929 if (si->nr_ours || si->nr_theirs) {
1930 for (i = 0; i < nr_sought; i++)
1931 if (status[i])
1932 sought[i]->status = REF_STATUS_REJECT_SHALLOW;
1934 free(status);
1935 oid_array_clear(&ref);
1938 static const struct object_id *iterate_ref_map(void *cb_data)
1940 struct ref **rm = cb_data;
1941 struct ref *ref = *rm;
1943 if (!ref)
1944 return NULL;
1945 *rm = ref->next;
1946 return &ref->old_oid;
1949 struct ref *fetch_pack(struct fetch_pack_args *args,
1950 int fd[],
1951 const struct ref *ref,
1952 struct ref **sought, int nr_sought,
1953 struct oid_array *shallow,
1954 struct string_list *pack_lockfiles,
1955 enum protocol_version version)
1957 struct ref *ref_cpy;
1958 struct shallow_info si;
1959 struct oid_array shallows_scratch = OID_ARRAY_INIT;
1961 fetch_pack_setup();
1962 if (nr_sought)
1963 nr_sought = remove_duplicates_in_refs(sought, nr_sought);
1965 if (version != protocol_v2 && !ref) {
1966 packet_flush(fd[1]);
1967 die(_("no matching remote head"));
1969 if (version == protocol_v2) {
1970 if (shallow->nr)
1971 BUG("Protocol V2 does not provide shallows at this point in the fetch");
1972 memset(&si, 0, sizeof(si));
1973 ref_cpy = do_fetch_pack_v2(args, fd, ref, sought, nr_sought,
1974 &shallows_scratch, &si,
1975 pack_lockfiles);
1976 } else {
1977 prepare_shallow_info(&si, shallow);
1978 ref_cpy = do_fetch_pack(args, fd, ref, sought, nr_sought,
1979 &si, pack_lockfiles);
1981 reprepare_packed_git(the_repository);
1983 if (!args->cloning && args->deepen) {
1984 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1985 struct ref *iterator = ref_cpy;
1986 opt.shallow_file = alternate_shallow_file;
1987 if (args->deepen)
1988 opt.is_deepening_fetch = 1;
1989 if (check_connected(iterate_ref_map, &iterator, &opt)) {
1990 error(_("remote did not send all necessary objects"));
1991 free_refs(ref_cpy);
1992 ref_cpy = NULL;
1993 rollback_shallow_file(the_repository, &shallow_lock);
1994 goto cleanup;
1996 args->connectivity_checked = 1;
1999 update_shallow(args, sought, nr_sought, &si);
2000 cleanup:
2001 clear_shallow_info(&si);
2002 oid_array_clear(&shallows_scratch);
2003 return ref_cpy;
2006 static int add_to_object_array(const struct object_id *oid, void *data)
2008 struct object_array *a = data;
2010 add_object_array(lookup_object(the_repository, oid), "", a);
2011 return 0;
2014 static void clear_common_flag(struct oidset *s)
2016 struct oidset_iter iter;
2017 const struct object_id *oid;
2018 oidset_iter_init(s, &iter);
2020 while ((oid = oidset_iter_next(&iter))) {
2021 struct object *obj = lookup_object(the_repository, oid);
2022 obj->flags &= ~COMMON;
2026 void negotiate_using_fetch(const struct oid_array *negotiation_tips,
2027 const struct string_list *server_options,
2028 int stateless_rpc,
2029 int fd[],
2030 struct oidset *acked_commits)
2032 struct fetch_negotiator negotiator;
2033 struct packet_reader reader;
2034 struct object_array nt_object_array = OBJECT_ARRAY_INIT;
2035 struct strbuf req_buf = STRBUF_INIT;
2036 int haves_to_send = INITIAL_FLUSH;
2037 int in_vain = 0;
2038 int seen_ack = 0;
2039 int last_iteration = 0;
2040 timestamp_t min_generation = GENERATION_NUMBER_INFINITY;
2042 fetch_negotiator_init(the_repository, &negotiator);
2043 mark_tips(&negotiator, negotiation_tips);
2045 packet_reader_init(&reader, fd[0], NULL, 0,
2046 PACKET_READ_CHOMP_NEWLINE |
2047 PACKET_READ_DIE_ON_ERR_PACKET);
2049 oid_array_for_each((struct oid_array *) negotiation_tips,
2050 add_to_object_array,
2051 &nt_object_array);
2053 while (!last_iteration) {
2054 int haves_added;
2055 struct object_id common_oid;
2056 int received_ready = 0;
2058 strbuf_reset(&req_buf);
2059 write_fetch_command_and_capabilities(&req_buf, server_options);
2061 packet_buf_write(&req_buf, "wait-for-done");
2063 haves_added = add_haves(&negotiator, &req_buf, &haves_to_send);
2064 in_vain += haves_added;
2065 if (!haves_added || (seen_ack && in_vain >= MAX_IN_VAIN))
2066 last_iteration = 1;
2068 /* Send request */
2069 packet_buf_flush(&req_buf);
2070 if (write_in_full(fd[1], req_buf.buf, req_buf.len) < 0)
2071 die_errno(_("unable to write request to remote"));
2073 /* Process ACKs/NAKs */
2074 process_section_header(&reader, "acknowledgments", 0);
2075 while (process_ack(&negotiator, &reader, &common_oid,
2076 &received_ready)) {
2077 struct commit *commit = lookup_commit(the_repository,
2078 &common_oid);
2079 if (commit) {
2080 timestamp_t generation;
2082 parse_commit_or_die(commit);
2083 commit->object.flags |= COMMON;
2084 generation = commit_graph_generation(commit);
2085 if (generation < min_generation)
2086 min_generation = generation;
2088 in_vain = 0;
2089 seen_ack = 1;
2090 oidset_insert(acked_commits, &common_oid);
2092 if (received_ready)
2093 die(_("unexpected 'ready' from remote"));
2094 else
2095 do_check_stateless_delimiter(stateless_rpc, &reader);
2096 if (can_all_from_reach_with_flag(&nt_object_array, COMMON,
2097 REACH_SCRATCH, 0,
2098 min_generation))
2099 last_iteration = 1;
2101 clear_common_flag(acked_commits);
2102 strbuf_release(&req_buf);
2105 int report_unmatched_refs(struct ref **sought, int nr_sought)
2107 int i, ret = 0;
2109 for (i = 0; i < nr_sought; i++) {
2110 if (!sought[i])
2111 continue;
2112 switch (sought[i]->match_status) {
2113 case REF_MATCHED:
2114 continue;
2115 case REF_NOT_MATCHED:
2116 error(_("no such remote ref %s"), sought[i]->name);
2117 break;
2118 case REF_UNADVERTISED_NOT_ALLOWED:
2119 error(_("Server does not allow request for unadvertised object %s"),
2120 sought[i]->name);
2121 break;
2123 ret = 1;
2125 return ret;