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