Documentation/technical: describe bitmap lookup table extension
[git/debian.git] / fetch-pack.c
blobd35be4177b107768d6af30c5260f16ddc8cbb5a0
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"
29 #include "mergesort.h"
31 static int transfer_unpack_limit = -1;
32 static int fetch_unpack_limit = -1;
33 static int unpack_limit = 100;
34 static int prefer_ofs_delta = 1;
35 static int no_done;
36 static int deepen_since_ok;
37 static int deepen_not_ok;
38 static int fetch_fsck_objects = -1;
39 static int transfer_fsck_objects = -1;
40 static int agent_supported;
41 static int server_supports_filtering;
42 static int advertise_sid;
43 static struct shallow_lock shallow_lock;
44 static const char *alternate_shallow_file;
45 static struct fsck_options fsck_options = FSCK_OPTIONS_MISSING_GITMODULES;
46 static struct strbuf fsck_msg_types = STRBUF_INIT;
47 static struct string_list uri_protocols = STRING_LIST_INIT_DUP;
49 /* Remember to update object flag allocation in object.h */
50 #define COMPLETE (1U << 0)
51 #define ALTERNATE (1U << 1)
52 #define COMMON (1U << 6)
53 #define REACH_SCRATCH (1U << 7)
56 * After sending this many "have"s if we do not get any new ACK , we
57 * give up traversing our history.
59 #define MAX_IN_VAIN 256
61 static int multi_ack, use_sideband;
62 /* Allow specifying sha1 if it is a ref tip. */
63 #define ALLOW_TIP_SHA1 01
64 /* Allow request of a sha1 if it is reachable from a ref (possibly hidden ref). */
65 #define ALLOW_REACHABLE_SHA1 02
66 static unsigned int allow_unadvertised_object_request;
68 __attribute__((format (printf, 2, 3)))
69 static inline void print_verbose(const struct fetch_pack_args *args,
70 const char *fmt, ...)
72 va_list params;
74 if (!args->verbose)
75 return;
77 va_start(params, fmt);
78 vfprintf(stderr, fmt, params);
79 va_end(params);
80 fputc('\n', stderr);
83 struct alternate_object_cache {
84 struct object **items;
85 size_t nr, alloc;
88 static void cache_one_alternate(const struct object_id *oid,
89 void *vcache)
91 struct alternate_object_cache *cache = vcache;
92 struct object *obj = parse_object(the_repository, oid);
94 if (!obj || (obj->flags & ALTERNATE))
95 return;
97 obj->flags |= ALTERNATE;
98 ALLOC_GROW(cache->items, cache->nr + 1, cache->alloc);
99 cache->items[cache->nr++] = obj;
102 static void for_each_cached_alternate(struct fetch_negotiator *negotiator,
103 void (*cb)(struct fetch_negotiator *,
104 struct object *))
106 static int initialized;
107 static struct alternate_object_cache cache;
108 size_t i;
110 if (!initialized) {
111 for_each_alternate_ref(cache_one_alternate, &cache);
112 initialized = 1;
115 for (i = 0; i < cache.nr; i++)
116 cb(negotiator, cache.items[i]);
119 static struct commit *deref_without_lazy_fetch_extended(const struct object_id *oid,
120 int mark_tags_complete,
121 enum object_type *type,
122 unsigned int oi_flags)
124 struct object_info info = { .typep = type };
125 struct commit *commit;
127 commit = lookup_commit_in_graph(the_repository, oid);
128 if (commit)
129 return commit;
131 while (1) {
132 if (oid_object_info_extended(the_repository, oid, &info,
133 oi_flags))
134 return NULL;
135 if (*type == OBJ_TAG) {
136 struct tag *tag = (struct tag *)
137 parse_object(the_repository, oid);
139 if (!tag->tagged)
140 return NULL;
141 if (mark_tags_complete)
142 tag->object.flags |= COMPLETE;
143 oid = &tag->tagged->oid;
144 } else {
145 break;
149 if (*type == OBJ_COMMIT) {
150 struct commit *commit = lookup_commit(the_repository, oid);
151 if (!commit || repo_parse_commit(the_repository, commit))
152 return NULL;
153 return commit;
156 return NULL;
160 static struct commit *deref_without_lazy_fetch(const struct object_id *oid,
161 int mark_tags_complete)
163 enum object_type type;
164 unsigned flags = OBJECT_INFO_SKIP_FETCH_OBJECT | OBJECT_INFO_QUICK;
165 return deref_without_lazy_fetch_extended(oid, mark_tags_complete,
166 &type, flags);
169 static int rev_list_insert_ref(struct fetch_negotiator *negotiator,
170 const struct object_id *oid)
172 struct commit *c = deref_without_lazy_fetch(oid, 0);
174 if (c)
175 negotiator->add_tip(negotiator, c);
176 return 0;
179 static int rev_list_insert_ref_oid(const char *refname, const struct object_id *oid,
180 int flag, void *cb_data)
182 return rev_list_insert_ref(cb_data, oid);
185 enum ack_type {
186 NAK = 0,
187 ACK,
188 ACK_continue,
189 ACK_common,
190 ACK_ready
193 static void consume_shallow_list(struct fetch_pack_args *args,
194 struct packet_reader *reader)
196 if (args->stateless_rpc && args->deepen) {
197 /* If we sent a depth we will get back "duplicate"
198 * shallow and unshallow commands every time there
199 * is a block of have lines exchanged.
201 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
202 if (starts_with(reader->line, "shallow "))
203 continue;
204 if (starts_with(reader->line, "unshallow "))
205 continue;
206 die(_("git fetch-pack: expected shallow list"));
208 if (reader->status != PACKET_READ_FLUSH)
209 die(_("git fetch-pack: expected a flush packet after shallow list"));
213 static enum ack_type get_ack(struct packet_reader *reader,
214 struct object_id *result_oid)
216 int len;
217 const char *arg;
219 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
220 die(_("git fetch-pack: expected ACK/NAK, got a flush packet"));
221 len = reader->pktlen;
223 if (!strcmp(reader->line, "NAK"))
224 return NAK;
225 if (skip_prefix(reader->line, "ACK ", &arg)) {
226 const char *p;
227 if (!parse_oid_hex(arg, result_oid, &p)) {
228 len -= p - reader->line;
229 if (len < 1)
230 return ACK;
231 if (strstr(p, "continue"))
232 return ACK_continue;
233 if (strstr(p, "common"))
234 return ACK_common;
235 if (strstr(p, "ready"))
236 return ACK_ready;
237 return ACK;
240 die(_("git fetch-pack: expected ACK/NAK, got '%s'"), reader->line);
243 static void send_request(struct fetch_pack_args *args,
244 int fd, struct strbuf *buf)
246 if (args->stateless_rpc) {
247 send_sideband(fd, -1, buf->buf, buf->len, LARGE_PACKET_MAX);
248 packet_flush(fd);
249 } else {
250 if (write_in_full(fd, buf->buf, buf->len) < 0)
251 die_errno(_("unable to write to remote"));
255 static void insert_one_alternate_object(struct fetch_negotiator *negotiator,
256 struct object *obj)
258 rev_list_insert_ref(negotiator, &obj->oid);
261 #define INITIAL_FLUSH 16
262 #define PIPESAFE_FLUSH 32
263 #define LARGE_FLUSH 16384
265 static int next_flush(int stateless_rpc, int count)
267 if (stateless_rpc) {
268 if (count < LARGE_FLUSH)
269 count <<= 1;
270 else
271 count = count * 11 / 10;
272 } else {
273 if (count < PIPESAFE_FLUSH)
274 count <<= 1;
275 else
276 count += PIPESAFE_FLUSH;
278 return count;
281 static void mark_tips(struct fetch_negotiator *negotiator,
282 const struct oid_array *negotiation_tips)
284 int i;
286 if (!negotiation_tips) {
287 for_each_rawref(rev_list_insert_ref_oid, negotiator);
288 return;
291 for (i = 0; i < negotiation_tips->nr; i++)
292 rev_list_insert_ref(negotiator, &negotiation_tips->oid[i]);
293 return;
296 static void send_filter(struct fetch_pack_args *args,
297 struct strbuf *req_buf,
298 int server_supports_filter)
300 if (args->filter_options.choice) {
301 const char *spec =
302 expand_list_objects_filter_spec(&args->filter_options);
303 if (server_supports_filter) {
304 print_verbose(args, _("Server supports filter"));
305 packet_buf_write(req_buf, "filter %s", spec);
306 trace2_data_string("fetch", the_repository,
307 "filter/effective", spec);
308 } else {
309 warning("filtering not recognized by server, ignoring");
310 trace2_data_string("fetch", the_repository,
311 "filter/unsupported", spec);
313 } else {
314 trace2_data_string("fetch", the_repository,
315 "filter/none", "");
319 static int find_common(struct fetch_negotiator *negotiator,
320 struct fetch_pack_args *args,
321 int fd[2], struct object_id *result_oid,
322 struct ref *refs)
324 int fetching;
325 int count = 0, flushes = 0, flush_at = INITIAL_FLUSH, retval;
326 const struct object_id *oid;
327 unsigned in_vain = 0;
328 int got_continue = 0;
329 int got_ready = 0;
330 struct strbuf req_buf = STRBUF_INIT;
331 size_t state_len = 0;
332 struct packet_reader reader;
334 if (args->stateless_rpc && multi_ack == 1)
335 die(_("the option '%s' requires '%s'"), "--stateless-rpc", "multi_ack_detailed");
337 packet_reader_init(&reader, fd[0], NULL, 0,
338 PACKET_READ_CHOMP_NEWLINE |
339 PACKET_READ_DIE_ON_ERR_PACKET);
341 mark_tips(negotiator, args->negotiation_tips);
342 for_each_cached_alternate(negotiator, insert_one_alternate_object);
344 fetching = 0;
345 for ( ; refs ; refs = refs->next) {
346 struct object_id *remote = &refs->old_oid;
347 const char *remote_hex;
348 struct object *o;
350 if (!args->refetch) {
352 * If that object is complete (i.e. it is an ancestor of a
353 * local ref), we tell them we have it but do not have to
354 * tell them about its ancestors, which they already know
355 * about.
357 * We use lookup_object here because we are only
358 * interested in the case we *know* the object is
359 * reachable and we have already scanned it.
361 if (((o = lookup_object(the_repository, remote)) != NULL) &&
362 (o->flags & COMPLETE)) {
363 continue;
367 remote_hex = oid_to_hex(remote);
368 if (!fetching) {
369 struct strbuf c = STRBUF_INIT;
370 if (multi_ack == 2) strbuf_addstr(&c, " multi_ack_detailed");
371 if (multi_ack == 1) strbuf_addstr(&c, " multi_ack");
372 if (no_done) strbuf_addstr(&c, " no-done");
373 if (use_sideband == 2) strbuf_addstr(&c, " side-band-64k");
374 if (use_sideband == 1) strbuf_addstr(&c, " side-band");
375 if (args->deepen_relative) strbuf_addstr(&c, " deepen-relative");
376 if (args->use_thin_pack) strbuf_addstr(&c, " thin-pack");
377 if (args->no_progress) strbuf_addstr(&c, " no-progress");
378 if (args->include_tag) strbuf_addstr(&c, " include-tag");
379 if (prefer_ofs_delta) strbuf_addstr(&c, " ofs-delta");
380 if (deepen_since_ok) strbuf_addstr(&c, " deepen-since");
381 if (deepen_not_ok) strbuf_addstr(&c, " deepen-not");
382 if (agent_supported) strbuf_addf(&c, " agent=%s",
383 git_user_agent_sanitized());
384 if (advertise_sid)
385 strbuf_addf(&c, " session-id=%s", trace2_session_id());
386 if (args->filter_options.choice)
387 strbuf_addstr(&c, " filter");
388 packet_buf_write(&req_buf, "want %s%s\n", remote_hex, c.buf);
389 strbuf_release(&c);
390 } else
391 packet_buf_write(&req_buf, "want %s\n", remote_hex);
392 fetching++;
395 if (!fetching) {
396 strbuf_release(&req_buf);
397 packet_flush(fd[1]);
398 return 1;
401 if (is_repository_shallow(the_repository))
402 write_shallow_commits(&req_buf, 1, NULL);
403 if (args->depth > 0)
404 packet_buf_write(&req_buf, "deepen %d", args->depth);
405 if (args->deepen_since) {
406 timestamp_t max_age = approxidate(args->deepen_since);
407 packet_buf_write(&req_buf, "deepen-since %"PRItime, max_age);
409 if (args->deepen_not) {
410 int i;
411 for (i = 0; i < args->deepen_not->nr; i++) {
412 struct string_list_item *s = args->deepen_not->items + i;
413 packet_buf_write(&req_buf, "deepen-not %s", s->string);
416 send_filter(args, &req_buf, server_supports_filtering);
417 packet_buf_flush(&req_buf);
418 state_len = req_buf.len;
420 if (args->deepen) {
421 const char *arg;
422 struct object_id oid;
424 send_request(args, fd[1], &req_buf);
425 while (packet_reader_read(&reader) == PACKET_READ_NORMAL) {
426 if (skip_prefix(reader.line, "shallow ", &arg)) {
427 if (get_oid_hex(arg, &oid))
428 die(_("invalid shallow line: %s"), reader.line);
429 register_shallow(the_repository, &oid);
430 continue;
432 if (skip_prefix(reader.line, "unshallow ", &arg)) {
433 if (get_oid_hex(arg, &oid))
434 die(_("invalid unshallow line: %s"), reader.line);
435 if (!lookup_object(the_repository, &oid))
436 die(_("object not found: %s"), reader.line);
437 /* make sure that it is parsed as shallow */
438 if (!parse_object(the_repository, &oid))
439 die(_("error in object: %s"), reader.line);
440 if (unregister_shallow(&oid))
441 die(_("no shallow found: %s"), reader.line);
442 continue;
444 die(_("expected shallow/unshallow, got %s"), reader.line);
446 } else if (!args->stateless_rpc)
447 send_request(args, fd[1], &req_buf);
449 if (!args->stateless_rpc) {
450 /* If we aren't using the stateless-rpc interface
451 * we don't need to retain the headers.
453 strbuf_setlen(&req_buf, 0);
454 state_len = 0;
457 trace2_region_enter("fetch-pack", "negotiation_v0_v1", the_repository);
458 flushes = 0;
459 retval = -1;
460 while ((oid = negotiator->next(negotiator))) {
461 packet_buf_write(&req_buf, "have %s\n", oid_to_hex(oid));
462 print_verbose(args, "have %s", oid_to_hex(oid));
463 in_vain++;
464 if (flush_at <= ++count) {
465 int ack;
467 packet_buf_flush(&req_buf);
468 send_request(args, fd[1], &req_buf);
469 strbuf_setlen(&req_buf, state_len);
470 flushes++;
471 flush_at = next_flush(args->stateless_rpc, count);
474 * We keep one window "ahead" of the other side, and
475 * will wait for an ACK only on the next one
477 if (!args->stateless_rpc && count == INITIAL_FLUSH)
478 continue;
480 consume_shallow_list(args, &reader);
481 do {
482 ack = get_ack(&reader, result_oid);
483 if (ack)
484 print_verbose(args, _("got %s %d %s"), "ack",
485 ack, oid_to_hex(result_oid));
486 switch (ack) {
487 case ACK:
488 flushes = 0;
489 multi_ack = 0;
490 retval = 0;
491 goto done;
492 case ACK_common:
493 case ACK_ready:
494 case ACK_continue: {
495 struct commit *commit =
496 lookup_commit(the_repository,
497 result_oid);
498 int was_common;
500 if (!commit)
501 die(_("invalid commit %s"), oid_to_hex(result_oid));
502 was_common = negotiator->ack(negotiator, commit);
503 if (args->stateless_rpc
504 && ack == ACK_common
505 && !was_common) {
506 /* We need to replay the have for this object
507 * on the next RPC request so the peer knows
508 * it is in common with us.
510 const char *hex = oid_to_hex(result_oid);
511 packet_buf_write(&req_buf, "have %s\n", hex);
512 state_len = req_buf.len;
514 * Reset in_vain because an ack
515 * for this commit has not been
516 * seen.
518 in_vain = 0;
519 } else if (!args->stateless_rpc
520 || ack != ACK_common)
521 in_vain = 0;
522 retval = 0;
523 got_continue = 1;
524 if (ack == ACK_ready)
525 got_ready = 1;
526 break;
529 } while (ack);
530 flushes--;
531 if (got_continue && MAX_IN_VAIN < in_vain) {
532 print_verbose(args, _("giving up"));
533 break; /* give up */
535 if (got_ready)
536 break;
539 done:
540 trace2_region_leave("fetch-pack", "negotiation_v0_v1", the_repository);
541 if (!got_ready || !no_done) {
542 packet_buf_write(&req_buf, "done\n");
543 send_request(args, fd[1], &req_buf);
545 print_verbose(args, _("done"));
546 if (retval != 0) {
547 multi_ack = 0;
548 flushes++;
550 strbuf_release(&req_buf);
552 if (!got_ready || !no_done)
553 consume_shallow_list(args, &reader);
554 while (flushes || multi_ack) {
555 int ack = get_ack(&reader, result_oid);
556 if (ack) {
557 print_verbose(args, _("got %s (%d) %s"), "ack",
558 ack, oid_to_hex(result_oid));
559 if (ack == ACK)
560 return 0;
561 multi_ack = 1;
562 continue;
564 flushes--;
566 /* it is no error to fetch into a completely empty repo */
567 return count ? retval : 0;
570 static struct commit_list *complete;
572 static int mark_complete(const struct object_id *oid)
574 struct commit *commit = deref_without_lazy_fetch(oid, 1);
576 if (commit && !(commit->object.flags & COMPLETE)) {
577 commit->object.flags |= COMPLETE;
578 commit_list_insert(commit, &complete);
580 return 0;
583 static int mark_complete_oid(const char *refname, const struct object_id *oid,
584 int flag, void *cb_data)
586 return mark_complete(oid);
589 static void mark_recent_complete_commits(struct fetch_pack_args *args,
590 timestamp_t cutoff)
592 while (complete && cutoff <= complete->item->date) {
593 print_verbose(args, _("Marking %s as complete"),
594 oid_to_hex(&complete->item->object.oid));
595 pop_most_recent_commit(&complete, COMPLETE);
599 static void add_refs_to_oidset(struct oidset *oids, struct ref *refs)
601 for (; refs; refs = refs->next)
602 oidset_insert(oids, &refs->old_oid);
605 static int is_unmatched_ref(const struct ref *ref)
607 struct object_id oid;
608 const char *p;
609 return ref->match_status == REF_NOT_MATCHED &&
610 !parse_oid_hex(ref->name, &oid, &p) &&
611 *p == '\0' &&
612 oideq(&oid, &ref->old_oid);
615 static void filter_refs(struct fetch_pack_args *args,
616 struct ref **refs,
617 struct ref **sought, int nr_sought)
619 struct ref *newlist = NULL;
620 struct ref **newtail = &newlist;
621 struct ref *unmatched = NULL;
622 struct ref *ref, *next;
623 struct oidset tip_oids = OIDSET_INIT;
624 int i;
625 int strict = !(allow_unadvertised_object_request &
626 (ALLOW_TIP_SHA1 | ALLOW_REACHABLE_SHA1));
628 i = 0;
629 for (ref = *refs; ref; ref = next) {
630 int keep = 0;
631 next = ref->next;
633 if (starts_with(ref->name, "refs/") &&
634 check_refname_format(ref->name, 0)) {
636 * trash or a peeled value; do not even add it to
637 * unmatched list
639 free_one_ref(ref);
640 continue;
641 } else {
642 while (i < nr_sought) {
643 int cmp = strcmp(ref->name, sought[i]->name);
644 if (cmp < 0)
645 break; /* definitely do not have it */
646 else if (cmp == 0) {
647 keep = 1; /* definitely have it */
648 sought[i]->match_status = REF_MATCHED;
650 i++;
653 if (!keep && args->fetch_all &&
654 (!args->deepen || !starts_with(ref->name, "refs/tags/")))
655 keep = 1;
658 if (keep) {
659 *newtail = ref;
660 ref->next = NULL;
661 newtail = &ref->next;
662 } else {
663 ref->next = unmatched;
664 unmatched = ref;
668 if (strict) {
669 for (i = 0; i < nr_sought; i++) {
670 ref = sought[i];
671 if (!is_unmatched_ref(ref))
672 continue;
674 add_refs_to_oidset(&tip_oids, unmatched);
675 add_refs_to_oidset(&tip_oids, newlist);
676 break;
680 /* Append unmatched requests to the list */
681 for (i = 0; i < nr_sought; i++) {
682 ref = sought[i];
683 if (!is_unmatched_ref(ref))
684 continue;
686 if (!strict || oidset_contains(&tip_oids, &ref->old_oid)) {
687 ref->match_status = REF_MATCHED;
688 *newtail = copy_ref(ref);
689 newtail = &(*newtail)->next;
690 } else {
691 ref->match_status = REF_UNADVERTISED_NOT_ALLOWED;
695 oidset_clear(&tip_oids);
696 free_refs(unmatched);
698 *refs = newlist;
701 static void mark_alternate_complete(struct fetch_negotiator *unused,
702 struct object *obj)
704 mark_complete(&obj->oid);
707 struct loose_object_iter {
708 struct oidset *loose_object_set;
709 struct ref *refs;
713 * Mark recent commits available locally and reachable from a local ref as
714 * COMPLETE.
716 * The cutoff time for recency is determined by this heuristic: it is the
717 * earliest commit time of the objects in refs that are commits and that we know
718 * the commit time of.
720 static void mark_complete_and_common_ref(struct fetch_negotiator *negotiator,
721 struct fetch_pack_args *args,
722 struct ref **refs)
724 struct ref *ref;
725 int old_save_commit_buffer = save_commit_buffer;
726 timestamp_t cutoff = 0;
728 if (args->refetch)
729 return;
731 save_commit_buffer = 0;
733 trace2_region_enter("fetch-pack", "parse_remote_refs_and_find_cutoff", NULL);
734 for (ref = *refs; ref; ref = ref->next) {
735 struct commit *commit;
737 commit = lookup_commit_in_graph(the_repository, &ref->old_oid);
738 if (!commit) {
739 struct object *o;
741 if (!has_object_file_with_flags(&ref->old_oid,
742 OBJECT_INFO_QUICK |
743 OBJECT_INFO_SKIP_FETCH_OBJECT))
744 continue;
745 o = parse_object(the_repository, &ref->old_oid);
746 if (!o || o->type != OBJ_COMMIT)
747 continue;
749 commit = (struct commit *)o;
753 * We already have it -- which may mean that we were
754 * in sync with the other side at some time after
755 * that (it is OK if we guess wrong here).
757 if (!cutoff || cutoff < commit->date)
758 cutoff = commit->date;
760 trace2_region_leave("fetch-pack", "parse_remote_refs_and_find_cutoff", NULL);
763 * This block marks all local refs as COMPLETE, and then recursively marks all
764 * parents of those refs as COMPLETE.
766 trace2_region_enter("fetch-pack", "mark_complete_local_refs", NULL);
767 if (!args->deepen) {
768 for_each_rawref(mark_complete_oid, NULL);
769 for_each_cached_alternate(NULL, mark_alternate_complete);
770 commit_list_sort_by_date(&complete);
771 if (cutoff)
772 mark_recent_complete_commits(args, cutoff);
774 trace2_region_leave("fetch-pack", "mark_complete_local_refs", NULL);
777 * Mark all complete remote refs as common refs.
778 * Don't mark them common yet; the server has to be told so first.
780 trace2_region_enter("fetch-pack", "mark_common_remote_refs", NULL);
781 for (ref = *refs; ref; ref = ref->next) {
782 struct commit *c = deref_without_lazy_fetch(&ref->old_oid, 0);
784 if (!c || !(c->object.flags & COMPLETE))
785 continue;
787 negotiator->known_common(negotiator, c);
789 trace2_region_leave("fetch-pack", "mark_common_remote_refs", NULL);
791 save_commit_buffer = old_save_commit_buffer;
795 * Returns 1 if every object pointed to by the given remote refs is available
796 * locally and reachable from a local ref, and 0 otherwise.
798 static int everything_local(struct fetch_pack_args *args,
799 struct ref **refs)
801 struct ref *ref;
802 int retval;
804 for (retval = 1, ref = *refs; ref ; ref = ref->next) {
805 const struct object_id *remote = &ref->old_oid;
806 struct object *o;
808 o = lookup_object(the_repository, remote);
809 if (!o || !(o->flags & COMPLETE)) {
810 retval = 0;
811 print_verbose(args, "want %s (%s)", oid_to_hex(remote),
812 ref->name);
813 continue;
815 print_verbose(args, _("already have %s (%s)"), oid_to_hex(remote),
816 ref->name);
819 return retval;
822 static int sideband_demux(int in, int out, void *data)
824 int *xd = data;
825 int ret;
827 ret = recv_sideband("fetch-pack", xd[0], out);
828 close(out);
829 return ret;
832 static void create_promisor_file(const char *keep_name,
833 struct ref **sought, int nr_sought)
835 struct strbuf promisor_name = STRBUF_INIT;
836 int suffix_stripped;
838 strbuf_addstr(&promisor_name, keep_name);
839 suffix_stripped = strbuf_strip_suffix(&promisor_name, ".keep");
840 if (!suffix_stripped)
841 BUG("name of pack lockfile should end with .keep (was '%s')",
842 keep_name);
843 strbuf_addstr(&promisor_name, ".promisor");
845 write_promisor_file(promisor_name.buf, sought, nr_sought);
847 strbuf_release(&promisor_name);
850 static void parse_gitmodules_oids(int fd, struct oidset *gitmodules_oids)
852 int len = the_hash_algo->hexsz + 1; /* hash + NL */
854 do {
855 char hex_hash[GIT_MAX_HEXSZ + 1];
856 int read_len = read_in_full(fd, hex_hash, len);
857 struct object_id oid;
858 const char *end;
860 if (!read_len)
861 return;
862 if (read_len != len)
863 die("invalid length read %d", read_len);
864 if (parse_oid_hex(hex_hash, &oid, &end) || *end != '\n')
865 die("invalid hash");
866 oidset_insert(gitmodules_oids, &oid);
867 } while (1);
870 static void add_index_pack_keep_option(struct strvec *args)
872 char hostname[HOST_NAME_MAX + 1];
874 if (xgethostname(hostname, sizeof(hostname)))
875 xsnprintf(hostname, sizeof(hostname), "localhost");
876 strvec_pushf(args, "--keep=fetch-pack %"PRIuMAX " on %s",
877 (uintmax_t)getpid(), hostname);
881 * If packfile URIs were provided, pass a non-NULL pointer to index_pack_args.
882 * The strings to pass as the --index-pack-arg arguments to http-fetch will be
883 * stored there. (It must be freed by the caller.)
885 static int get_pack(struct fetch_pack_args *args,
886 int xd[2], struct string_list *pack_lockfiles,
887 struct strvec *index_pack_args,
888 struct ref **sought, int nr_sought,
889 struct oidset *gitmodules_oids)
891 struct async demux;
892 int do_keep = args->keep_pack;
893 const char *cmd_name;
894 struct pack_header header;
895 int pass_header = 0;
896 struct child_process cmd = CHILD_PROCESS_INIT;
897 int fsck_objects = 0;
898 int ret;
900 memset(&demux, 0, sizeof(demux));
901 if (use_sideband) {
902 /* xd[] is talking with upload-pack; subprocess reads from
903 * xd[0], spits out band#2 to stderr, and feeds us band#1
904 * through demux->out.
906 demux.proc = sideband_demux;
907 demux.data = xd;
908 demux.out = -1;
909 demux.isolate_sigpipe = 1;
910 if (start_async(&demux))
911 die(_("fetch-pack: unable to fork off sideband demultiplexer"));
913 else
914 demux.out = xd[0];
916 if (!args->keep_pack && unpack_limit && !index_pack_args) {
918 if (read_pack_header(demux.out, &header))
919 die(_("protocol error: bad pack header"));
920 pass_header = 1;
921 if (ntohl(header.hdr_entries) < unpack_limit)
922 do_keep = 0;
923 else
924 do_keep = 1;
927 if (alternate_shallow_file) {
928 strvec_push(&cmd.args, "--shallow-file");
929 strvec_push(&cmd.args, alternate_shallow_file);
932 if (fetch_fsck_objects >= 0
933 ? fetch_fsck_objects
934 : transfer_fsck_objects >= 0
935 ? transfer_fsck_objects
936 : 0)
937 fsck_objects = 1;
939 if (do_keep || args->from_promisor || index_pack_args || fsck_objects) {
940 if (pack_lockfiles || fsck_objects)
941 cmd.out = -1;
942 cmd_name = "index-pack";
943 strvec_push(&cmd.args, cmd_name);
944 strvec_push(&cmd.args, "--stdin");
945 if (!args->quiet && !args->no_progress)
946 strvec_push(&cmd.args, "-v");
947 if (args->use_thin_pack)
948 strvec_push(&cmd.args, "--fix-thin");
949 if ((do_keep || index_pack_args) && (args->lock_pack || unpack_limit))
950 add_index_pack_keep_option(&cmd.args);
951 if (!index_pack_args && args->check_self_contained_and_connected)
952 strvec_push(&cmd.args, "--check-self-contained-and-connected");
953 else
955 * We cannot perform any connectivity checks because
956 * not all packs have been downloaded; let the caller
957 * have this responsibility.
959 args->check_self_contained_and_connected = 0;
961 if (args->from_promisor)
963 * create_promisor_file() may be called afterwards but
964 * we still need index-pack to know that this is a
965 * promisor pack. For example, if transfer.fsckobjects
966 * is true, index-pack needs to know that .gitmodules
967 * is a promisor object (so that it won't complain if
968 * it is missing).
970 strvec_push(&cmd.args, "--promisor");
972 else {
973 cmd_name = "unpack-objects";
974 strvec_push(&cmd.args, cmd_name);
975 if (args->quiet || args->no_progress)
976 strvec_push(&cmd.args, "-q");
977 args->check_self_contained_and_connected = 0;
980 if (pass_header)
981 strvec_pushf(&cmd.args, "--pack_header=%"PRIu32",%"PRIu32,
982 ntohl(header.hdr_version),
983 ntohl(header.hdr_entries));
984 if (fsck_objects) {
985 if (args->from_promisor || index_pack_args)
987 * We cannot use --strict in index-pack because it
988 * checks both broken objects and links, but we only
989 * want to check for broken objects.
991 strvec_push(&cmd.args, "--fsck-objects");
992 else
993 strvec_pushf(&cmd.args, "--strict%s",
994 fsck_msg_types.buf);
997 if (index_pack_args) {
998 int i;
1000 for (i = 0; i < cmd.args.nr; i++)
1001 strvec_push(index_pack_args, cmd.args.v[i]);
1004 sigchain_push(SIGPIPE, SIG_IGN);
1006 cmd.in = demux.out;
1007 cmd.git_cmd = 1;
1008 if (start_command(&cmd))
1009 die(_("fetch-pack: unable to fork off %s"), cmd_name);
1010 if (do_keep && (pack_lockfiles || fsck_objects)) {
1011 int is_well_formed;
1012 char *pack_lockfile = index_pack_lockfile(cmd.out, &is_well_formed);
1014 if (!is_well_formed)
1015 die(_("fetch-pack: invalid index-pack output"));
1016 if (pack_lockfile)
1017 string_list_append_nodup(pack_lockfiles, pack_lockfile);
1018 parse_gitmodules_oids(cmd.out, gitmodules_oids);
1019 close(cmd.out);
1022 if (!use_sideband)
1023 /* Closed by start_command() */
1024 xd[0] = -1;
1026 ret = finish_command(&cmd);
1027 if (!ret || (args->check_self_contained_and_connected && ret == 1))
1028 args->self_contained_and_connected =
1029 args->check_self_contained_and_connected &&
1030 ret == 0;
1031 else
1032 die(_("%s failed"), cmd_name);
1033 if (use_sideband && finish_async(&demux))
1034 die(_("error in sideband demultiplexer"));
1036 sigchain_pop(SIGPIPE);
1039 * Now that index-pack has succeeded, write the promisor file using the
1040 * obtained .keep filename if necessary
1042 if (do_keep && pack_lockfiles && pack_lockfiles->nr && args->from_promisor)
1043 create_promisor_file(pack_lockfiles->items[0].string, sought, nr_sought);
1045 return 0;
1048 static int ref_compare_name(const struct ref *a, const struct ref *b)
1050 return strcmp(a->name, b->name);
1053 DEFINE_LIST_SORT(static, sort_ref_list, struct ref, next);
1055 static int cmp_ref_by_name(const void *a_, const void *b_)
1057 const struct ref *a = *((const struct ref **)a_);
1058 const struct ref *b = *((const struct ref **)b_);
1059 return strcmp(a->name, b->name);
1062 static struct ref *do_fetch_pack(struct fetch_pack_args *args,
1063 int fd[2],
1064 const struct ref *orig_ref,
1065 struct ref **sought, int nr_sought,
1066 struct shallow_info *si,
1067 struct string_list *pack_lockfiles)
1069 struct repository *r = the_repository;
1070 struct ref *ref = copy_ref_list(orig_ref);
1071 struct object_id oid;
1072 const char *agent_feature;
1073 int agent_len;
1074 struct fetch_negotiator negotiator_alloc;
1075 struct fetch_negotiator *negotiator;
1077 negotiator = &negotiator_alloc;
1078 if (args->refetch) {
1079 fetch_negotiator_init_noop(negotiator);
1080 } else {
1081 fetch_negotiator_init(r, negotiator);
1084 sort_ref_list(&ref, ref_compare_name);
1085 QSORT(sought, nr_sought, cmp_ref_by_name);
1087 if ((agent_feature = server_feature_value("agent", &agent_len))) {
1088 agent_supported = 1;
1089 if (agent_len)
1090 print_verbose(args, _("Server version is %.*s"),
1091 agent_len, agent_feature);
1094 if (!server_supports("session-id"))
1095 advertise_sid = 0;
1097 if (server_supports("shallow"))
1098 print_verbose(args, _("Server supports %s"), "shallow");
1099 else if (args->depth > 0 || is_repository_shallow(r))
1100 die(_("Server does not support shallow clients"));
1101 if (args->depth > 0 || args->deepen_since || args->deepen_not)
1102 args->deepen = 1;
1103 if (server_supports("multi_ack_detailed")) {
1104 print_verbose(args, _("Server supports %s"), "multi_ack_detailed");
1105 multi_ack = 2;
1106 if (server_supports("no-done")) {
1107 print_verbose(args, _("Server supports %s"), "no-done");
1108 if (args->stateless_rpc)
1109 no_done = 1;
1112 else if (server_supports("multi_ack")) {
1113 print_verbose(args, _("Server supports %s"), "multi_ack");
1114 multi_ack = 1;
1116 if (server_supports("side-band-64k")) {
1117 print_verbose(args, _("Server supports %s"), "side-band-64k");
1118 use_sideband = 2;
1120 else if (server_supports("side-band")) {
1121 print_verbose(args, _("Server supports %s"), "side-band");
1122 use_sideband = 1;
1124 if (server_supports("allow-tip-sha1-in-want")) {
1125 print_verbose(args, _("Server supports %s"), "allow-tip-sha1-in-want");
1126 allow_unadvertised_object_request |= ALLOW_TIP_SHA1;
1128 if (server_supports("allow-reachable-sha1-in-want")) {
1129 print_verbose(args, _("Server supports %s"), "allow-reachable-sha1-in-want");
1130 allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
1132 if (server_supports("thin-pack"))
1133 print_verbose(args, _("Server supports %s"), "thin-pack");
1134 else
1135 args->use_thin_pack = 0;
1136 if (server_supports("no-progress"))
1137 print_verbose(args, _("Server supports %s"), "no-progress");
1138 else
1139 args->no_progress = 0;
1140 if (server_supports("include-tag"))
1141 print_verbose(args, _("Server supports %s"), "include-tag");
1142 else
1143 args->include_tag = 0;
1144 if (server_supports("ofs-delta"))
1145 print_verbose(args, _("Server supports %s"), "ofs-delta");
1146 else
1147 prefer_ofs_delta = 0;
1149 if (server_supports("filter")) {
1150 server_supports_filtering = 1;
1151 print_verbose(args, _("Server supports %s"), "filter");
1152 } else if (args->filter_options.choice) {
1153 warning("filtering not recognized by server, ignoring");
1156 if (server_supports("deepen-since")) {
1157 print_verbose(args, _("Server supports %s"), "deepen-since");
1158 deepen_since_ok = 1;
1159 } else if (args->deepen_since)
1160 die(_("Server does not support --shallow-since"));
1161 if (server_supports("deepen-not")) {
1162 print_verbose(args, _("Server supports %s"), "deepen-not");
1163 deepen_not_ok = 1;
1164 } else if (args->deepen_not)
1165 die(_("Server does not support --shallow-exclude"));
1166 if (server_supports("deepen-relative"))
1167 print_verbose(args, _("Server supports %s"), "deepen-relative");
1168 else if (args->deepen_relative)
1169 die(_("Server does not support --deepen"));
1170 if (!server_supports_hash(the_hash_algo->name, NULL))
1171 die(_("Server does not support this repository's object format"));
1173 mark_complete_and_common_ref(negotiator, args, &ref);
1174 filter_refs(args, &ref, sought, nr_sought);
1175 if (!args->refetch && everything_local(args, &ref)) {
1176 packet_flush(fd[1]);
1177 goto all_done;
1179 if (find_common(negotiator, args, fd, &oid, ref) < 0)
1180 if (!args->keep_pack)
1181 /* When cloning, it is not unusual to have
1182 * no common commit.
1184 warning(_("no common commits"));
1186 if (args->stateless_rpc)
1187 packet_flush(fd[1]);
1188 if (args->deepen)
1189 setup_alternate_shallow(&shallow_lock, &alternate_shallow_file,
1190 NULL);
1191 else if (si->nr_ours || si->nr_theirs) {
1192 if (args->reject_shallow_remote)
1193 die(_("source repository is shallow, reject to clone."));
1194 alternate_shallow_file = setup_temporary_shallow(si->shallow);
1195 } else
1196 alternate_shallow_file = NULL;
1197 if (get_pack(args, fd, pack_lockfiles, NULL, sought, nr_sought,
1198 &fsck_options.gitmodules_found))
1199 die(_("git fetch-pack: fetch failed."));
1200 if (fsck_finish(&fsck_options))
1201 die("fsck failed");
1203 all_done:
1204 if (negotiator)
1205 negotiator->release(negotiator);
1206 return ref;
1209 static void add_shallow_requests(struct strbuf *req_buf,
1210 const struct fetch_pack_args *args)
1212 if (is_repository_shallow(the_repository))
1213 write_shallow_commits(req_buf, 1, NULL);
1214 if (args->depth > 0)
1215 packet_buf_write(req_buf, "deepen %d", args->depth);
1216 if (args->deepen_since) {
1217 timestamp_t max_age = approxidate(args->deepen_since);
1218 packet_buf_write(req_buf, "deepen-since %"PRItime, max_age);
1220 if (args->deepen_not) {
1221 int i;
1222 for (i = 0; i < args->deepen_not->nr; i++) {
1223 struct string_list_item *s = args->deepen_not->items + i;
1224 packet_buf_write(req_buf, "deepen-not %s", s->string);
1227 if (args->deepen_relative)
1228 packet_buf_write(req_buf, "deepen-relative\n");
1231 static void add_wants(const struct ref *wants, struct strbuf *req_buf)
1233 int use_ref_in_want = server_supports_feature("fetch", "ref-in-want", 0);
1235 for ( ; wants ; wants = wants->next) {
1236 const struct object_id *remote = &wants->old_oid;
1237 struct object *o;
1240 * If that object is complete (i.e. it is an ancestor of a
1241 * local ref), we tell them we have it but do not have to
1242 * tell them about its ancestors, which they already know
1243 * about.
1245 * We use lookup_object here because we are only
1246 * interested in the case we *know* the object is
1247 * reachable and we have already scanned it.
1249 if (((o = lookup_object(the_repository, remote)) != NULL) &&
1250 (o->flags & COMPLETE)) {
1251 continue;
1254 if (!use_ref_in_want || wants->exact_oid)
1255 packet_buf_write(req_buf, "want %s\n", oid_to_hex(remote));
1256 else
1257 packet_buf_write(req_buf, "want-ref %s\n", wants->name);
1261 static void add_common(struct strbuf *req_buf, struct oidset *common)
1263 struct oidset_iter iter;
1264 const struct object_id *oid;
1265 oidset_iter_init(common, &iter);
1267 while ((oid = oidset_iter_next(&iter))) {
1268 packet_buf_write(req_buf, "have %s\n", oid_to_hex(oid));
1272 static int add_haves(struct fetch_negotiator *negotiator,
1273 struct strbuf *req_buf,
1274 int *haves_to_send)
1276 int haves_added = 0;
1277 const struct object_id *oid;
1279 while ((oid = negotiator->next(negotiator))) {
1280 packet_buf_write(req_buf, "have %s\n", oid_to_hex(oid));
1281 if (++haves_added >= *haves_to_send)
1282 break;
1285 /* Increase haves to send on next round */
1286 *haves_to_send = next_flush(1, *haves_to_send);
1288 return haves_added;
1291 static void write_fetch_command_and_capabilities(struct strbuf *req_buf,
1292 const struct string_list *server_options)
1294 const char *hash_name;
1296 if (server_supports_v2("fetch", 1))
1297 packet_buf_write(req_buf, "command=fetch");
1298 if (server_supports_v2("agent", 0))
1299 packet_buf_write(req_buf, "agent=%s", git_user_agent_sanitized());
1300 if (advertise_sid && server_supports_v2("session-id", 0))
1301 packet_buf_write(req_buf, "session-id=%s", trace2_session_id());
1302 if (server_options && server_options->nr &&
1303 server_supports_v2("server-option", 1)) {
1304 int i;
1305 for (i = 0; i < server_options->nr; i++)
1306 packet_buf_write(req_buf, "server-option=%s",
1307 server_options->items[i].string);
1310 if (server_feature_v2("object-format", &hash_name)) {
1311 int hash_algo = hash_algo_by_name(hash_name);
1312 if (hash_algo_by_ptr(the_hash_algo) != hash_algo)
1313 die(_("mismatched algorithms: client %s; server %s"),
1314 the_hash_algo->name, hash_name);
1315 packet_buf_write(req_buf, "object-format=%s", the_hash_algo->name);
1316 } else if (hash_algo_by_ptr(the_hash_algo) != GIT_HASH_SHA1) {
1317 die(_("the server does not support algorithm '%s'"),
1318 the_hash_algo->name);
1320 packet_buf_delim(req_buf);
1323 static int send_fetch_request(struct fetch_negotiator *negotiator, int fd_out,
1324 struct fetch_pack_args *args,
1325 const struct ref *wants, struct oidset *common,
1326 int *haves_to_send, int *in_vain,
1327 int sideband_all, int seen_ack)
1329 int haves_added;
1330 int done_sent = 0;
1331 struct strbuf req_buf = STRBUF_INIT;
1333 write_fetch_command_and_capabilities(&req_buf, args->server_options);
1335 if (args->use_thin_pack)
1336 packet_buf_write(&req_buf, "thin-pack");
1337 if (args->no_progress)
1338 packet_buf_write(&req_buf, "no-progress");
1339 if (args->include_tag)
1340 packet_buf_write(&req_buf, "include-tag");
1341 if (prefer_ofs_delta)
1342 packet_buf_write(&req_buf, "ofs-delta");
1343 if (sideband_all)
1344 packet_buf_write(&req_buf, "sideband-all");
1346 /* Add shallow-info and deepen request */
1347 if (server_supports_feature("fetch", "shallow", 0))
1348 add_shallow_requests(&req_buf, args);
1349 else if (is_repository_shallow(the_repository) || args->deepen)
1350 die(_("Server does not support shallow requests"));
1352 /* Add filter */
1353 send_filter(args, &req_buf,
1354 server_supports_feature("fetch", "filter", 0));
1356 if (server_supports_feature("fetch", "packfile-uris", 0)) {
1357 int i;
1358 struct strbuf to_send = STRBUF_INIT;
1360 for (i = 0; i < uri_protocols.nr; i++) {
1361 const char *s = uri_protocols.items[i].string;
1363 if (!strcmp(s, "https") || !strcmp(s, "http")) {
1364 if (to_send.len)
1365 strbuf_addch(&to_send, ',');
1366 strbuf_addstr(&to_send, s);
1369 if (to_send.len) {
1370 packet_buf_write(&req_buf, "packfile-uris %s",
1371 to_send.buf);
1372 strbuf_release(&to_send);
1376 /* add wants */
1377 add_wants(wants, &req_buf);
1379 /* Add all of the common commits we've found in previous rounds */
1380 add_common(&req_buf, common);
1382 haves_added = add_haves(negotiator, &req_buf, haves_to_send);
1383 *in_vain += haves_added;
1384 if (!haves_added || (seen_ack && *in_vain >= MAX_IN_VAIN)) {
1385 /* Send Done */
1386 packet_buf_write(&req_buf, "done\n");
1387 done_sent = 1;
1390 /* Send request */
1391 packet_buf_flush(&req_buf);
1392 if (write_in_full(fd_out, req_buf.buf, req_buf.len) < 0)
1393 die_errno(_("unable to write request to remote"));
1395 strbuf_release(&req_buf);
1396 return done_sent;
1400 * Processes a section header in a server's response and checks if it matches
1401 * `section`. If the value of `peek` is 1, the header line will be peeked (and
1402 * not consumed); if 0, the line will be consumed and the function will die if
1403 * the section header doesn't match what was expected.
1405 static int process_section_header(struct packet_reader *reader,
1406 const char *section, int peek)
1408 int ret = 0;
1410 if (packet_reader_peek(reader) == PACKET_READ_NORMAL &&
1411 !strcmp(reader->line, section))
1412 ret = 1;
1414 if (!peek) {
1415 if (!ret) {
1416 if (reader->line)
1417 die(_("expected '%s', received '%s'"),
1418 section, reader->line);
1419 else
1420 die(_("expected '%s'"), section);
1422 packet_reader_read(reader);
1425 return ret;
1428 static int process_ack(struct fetch_negotiator *negotiator,
1429 struct packet_reader *reader,
1430 struct object_id *common_oid,
1431 int *received_ready)
1433 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1434 const char *arg;
1436 if (!strcmp(reader->line, "NAK"))
1437 continue;
1439 if (skip_prefix(reader->line, "ACK ", &arg)) {
1440 if (!get_oid_hex(arg, common_oid)) {
1441 struct commit *commit;
1442 commit = lookup_commit(the_repository, common_oid);
1443 if (negotiator)
1444 negotiator->ack(negotiator, commit);
1446 return 1;
1449 if (!strcmp(reader->line, "ready")) {
1450 *received_ready = 1;
1451 continue;
1454 die(_("unexpected acknowledgment line: '%s'"), reader->line);
1457 if (reader->status != PACKET_READ_FLUSH &&
1458 reader->status != PACKET_READ_DELIM)
1459 die(_("error processing acks: %d"), reader->status);
1462 * If an "acknowledgments" section is sent, a packfile is sent if and
1463 * only if "ready" was sent in this section. The other sections
1464 * ("shallow-info" and "wanted-refs") are sent only if a packfile is
1465 * sent. Therefore, a DELIM is expected if "ready" is sent, and a FLUSH
1466 * otherwise.
1468 if (*received_ready && reader->status != PACKET_READ_DELIM)
1470 * TRANSLATORS: The parameter will be 'ready', a protocol
1471 * keyword.
1473 die(_("expected packfile to be sent after '%s'"), "ready");
1474 if (!*received_ready && reader->status != PACKET_READ_FLUSH)
1476 * TRANSLATORS: The parameter will be 'ready', a protocol
1477 * keyword.
1479 die(_("expected no other sections to be sent after no '%s'"), "ready");
1481 return 0;
1484 static void receive_shallow_info(struct fetch_pack_args *args,
1485 struct packet_reader *reader,
1486 struct oid_array *shallows,
1487 struct shallow_info *si)
1489 int unshallow_received = 0;
1491 process_section_header(reader, "shallow-info", 0);
1492 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1493 const char *arg;
1494 struct object_id oid;
1496 if (skip_prefix(reader->line, "shallow ", &arg)) {
1497 if (get_oid_hex(arg, &oid))
1498 die(_("invalid shallow line: %s"), reader->line);
1499 oid_array_append(shallows, &oid);
1500 continue;
1502 if (skip_prefix(reader->line, "unshallow ", &arg)) {
1503 if (get_oid_hex(arg, &oid))
1504 die(_("invalid unshallow line: %s"), reader->line);
1505 if (!lookup_object(the_repository, &oid))
1506 die(_("object not found: %s"), reader->line);
1507 /* make sure that it is parsed as shallow */
1508 if (!parse_object(the_repository, &oid))
1509 die(_("error in object: %s"), reader->line);
1510 if (unregister_shallow(&oid))
1511 die(_("no shallow found: %s"), reader->line);
1512 unshallow_received = 1;
1513 continue;
1515 die(_("expected shallow/unshallow, got %s"), reader->line);
1518 if (reader->status != PACKET_READ_FLUSH &&
1519 reader->status != PACKET_READ_DELIM)
1520 die(_("error processing shallow info: %d"), reader->status);
1522 if (args->deepen || unshallow_received) {
1524 * Treat these as shallow lines caused by our depth settings.
1525 * In v0, these lines cannot cause refs to be rejected; do the
1526 * same.
1528 int i;
1530 for (i = 0; i < shallows->nr; i++)
1531 register_shallow(the_repository, &shallows->oid[i]);
1532 setup_alternate_shallow(&shallow_lock, &alternate_shallow_file,
1533 NULL);
1534 args->deepen = 1;
1535 } else if (shallows->nr) {
1537 * Treat these as shallow lines caused by the remote being
1538 * shallow. In v0, remote refs that reach these objects are
1539 * rejected (unless --update-shallow is set); do the same.
1541 prepare_shallow_info(si, shallows);
1542 if (si->nr_ours || si->nr_theirs) {
1543 if (args->reject_shallow_remote)
1544 die(_("source repository is shallow, reject to clone."));
1545 alternate_shallow_file =
1546 setup_temporary_shallow(si->shallow);
1547 } else
1548 alternate_shallow_file = NULL;
1549 } else {
1550 alternate_shallow_file = NULL;
1554 static int cmp_name_ref(const void *name, const void *ref)
1556 return strcmp(name, (*(struct ref **)ref)->name);
1559 static void receive_wanted_refs(struct packet_reader *reader,
1560 struct ref **sought, int nr_sought)
1562 process_section_header(reader, "wanted-refs", 0);
1563 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1564 struct object_id oid;
1565 const char *end;
1566 struct ref **found;
1568 if (parse_oid_hex(reader->line, &oid, &end) || *end++ != ' ')
1569 die(_("expected wanted-ref, got '%s'"), reader->line);
1571 found = bsearch(end, sought, nr_sought, sizeof(*sought),
1572 cmp_name_ref);
1573 if (!found)
1574 die(_("unexpected wanted-ref: '%s'"), reader->line);
1575 oidcpy(&(*found)->old_oid, &oid);
1578 if (reader->status != PACKET_READ_DELIM)
1579 die(_("error processing wanted refs: %d"), reader->status);
1582 static void receive_packfile_uris(struct packet_reader *reader,
1583 struct string_list *uris)
1585 process_section_header(reader, "packfile-uris", 0);
1586 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1587 if (reader->pktlen < the_hash_algo->hexsz ||
1588 reader->line[the_hash_algo->hexsz] != ' ')
1589 die("expected '<hash> <uri>', got: %s\n", reader->line);
1591 string_list_append(uris, reader->line);
1593 if (reader->status != PACKET_READ_DELIM)
1594 die("expected DELIM");
1597 enum fetch_state {
1598 FETCH_CHECK_LOCAL = 0,
1599 FETCH_SEND_REQUEST,
1600 FETCH_PROCESS_ACKS,
1601 FETCH_GET_PACK,
1602 FETCH_DONE,
1605 static void do_check_stateless_delimiter(int stateless_rpc,
1606 struct packet_reader *reader)
1608 check_stateless_delimiter(stateless_rpc, reader,
1609 _("git fetch-pack: expected response end packet"));
1612 static struct ref *do_fetch_pack_v2(struct fetch_pack_args *args,
1613 int fd[2],
1614 const struct ref *orig_ref,
1615 struct ref **sought, int nr_sought,
1616 struct oid_array *shallows,
1617 struct shallow_info *si,
1618 struct string_list *pack_lockfiles)
1620 struct repository *r = the_repository;
1621 struct ref *ref = copy_ref_list(orig_ref);
1622 enum fetch_state state = FETCH_CHECK_LOCAL;
1623 struct oidset common = OIDSET_INIT;
1624 struct packet_reader reader;
1625 int in_vain = 0, negotiation_started = 0;
1626 int haves_to_send = INITIAL_FLUSH;
1627 struct fetch_negotiator negotiator_alloc;
1628 struct fetch_negotiator *negotiator;
1629 int seen_ack = 0;
1630 struct object_id common_oid;
1631 int received_ready = 0;
1632 struct string_list packfile_uris = STRING_LIST_INIT_DUP;
1633 int i;
1634 struct strvec index_pack_args = STRVEC_INIT;
1636 negotiator = &negotiator_alloc;
1637 if (args->refetch)
1638 fetch_negotiator_init_noop(negotiator);
1639 else
1640 fetch_negotiator_init(r, negotiator);
1642 packet_reader_init(&reader, fd[0], NULL, 0,
1643 PACKET_READ_CHOMP_NEWLINE |
1644 PACKET_READ_DIE_ON_ERR_PACKET);
1645 if (git_env_bool("GIT_TEST_SIDEBAND_ALL", 1) &&
1646 server_supports_feature("fetch", "sideband-all", 0)) {
1647 reader.use_sideband = 1;
1648 reader.me = "fetch-pack";
1651 while (state != FETCH_DONE) {
1652 switch (state) {
1653 case FETCH_CHECK_LOCAL:
1654 sort_ref_list(&ref, ref_compare_name);
1655 QSORT(sought, nr_sought, cmp_ref_by_name);
1657 /* v2 supports these by default */
1658 allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
1659 use_sideband = 2;
1660 if (args->depth > 0 || args->deepen_since || args->deepen_not)
1661 args->deepen = 1;
1663 /* Filter 'ref' by 'sought' and those that aren't local */
1664 mark_complete_and_common_ref(negotiator, args, &ref);
1665 filter_refs(args, &ref, sought, nr_sought);
1666 if (!args->refetch && everything_local(args, &ref))
1667 state = FETCH_DONE;
1668 else
1669 state = FETCH_SEND_REQUEST;
1671 mark_tips(negotiator, args->negotiation_tips);
1672 for_each_cached_alternate(negotiator,
1673 insert_one_alternate_object);
1674 break;
1675 case FETCH_SEND_REQUEST:
1676 if (!negotiation_started) {
1677 negotiation_started = 1;
1678 trace2_region_enter("fetch-pack",
1679 "negotiation_v2",
1680 the_repository);
1682 if (send_fetch_request(negotiator, fd[1], args, ref,
1683 &common,
1684 &haves_to_send, &in_vain,
1685 reader.use_sideband,
1686 seen_ack))
1687 state = FETCH_GET_PACK;
1688 else
1689 state = FETCH_PROCESS_ACKS;
1690 break;
1691 case FETCH_PROCESS_ACKS:
1692 /* Process ACKs/NAKs */
1693 process_section_header(&reader, "acknowledgments", 0);
1694 while (process_ack(negotiator, &reader, &common_oid,
1695 &received_ready)) {
1696 in_vain = 0;
1697 seen_ack = 1;
1698 oidset_insert(&common, &common_oid);
1700 if (received_ready) {
1702 * Don't check for response delimiter; get_pack() will
1703 * read the rest of this response.
1705 state = FETCH_GET_PACK;
1706 } else {
1707 do_check_stateless_delimiter(args->stateless_rpc, &reader);
1708 state = FETCH_SEND_REQUEST;
1710 break;
1711 case FETCH_GET_PACK:
1712 trace2_region_leave("fetch-pack",
1713 "negotiation_v2",
1714 the_repository);
1715 /* Check for shallow-info section */
1716 if (process_section_header(&reader, "shallow-info", 1))
1717 receive_shallow_info(args, &reader, shallows, si);
1719 if (process_section_header(&reader, "wanted-refs", 1))
1720 receive_wanted_refs(&reader, sought, nr_sought);
1722 /* get the pack(s) */
1723 if (git_env_bool("GIT_TRACE_REDACT", 1))
1724 reader.options |= PACKET_READ_REDACT_URI_PATH;
1725 if (process_section_header(&reader, "packfile-uris", 1))
1726 receive_packfile_uris(&reader, &packfile_uris);
1727 /* We don't expect more URIs. Reset to avoid expensive URI check. */
1728 reader.options &= ~PACKET_READ_REDACT_URI_PATH;
1730 process_section_header(&reader, "packfile", 0);
1733 * this is the final request we'll make of the server;
1734 * do a half-duplex shutdown to indicate that they can
1735 * hang up as soon as the pack is sent.
1737 close(fd[1]);
1738 fd[1] = -1;
1740 if (get_pack(args, fd, pack_lockfiles,
1741 packfile_uris.nr ? &index_pack_args : NULL,
1742 sought, nr_sought, &fsck_options.gitmodules_found))
1743 die(_("git fetch-pack: fetch failed."));
1744 do_check_stateless_delimiter(args->stateless_rpc, &reader);
1746 state = FETCH_DONE;
1747 break;
1748 case FETCH_DONE:
1749 continue;
1753 for (i = 0; i < packfile_uris.nr; i++) {
1754 int j;
1755 struct child_process cmd = CHILD_PROCESS_INIT;
1756 char packname[GIT_MAX_HEXSZ + 1];
1757 const char *uri = packfile_uris.items[i].string +
1758 the_hash_algo->hexsz + 1;
1760 strvec_push(&cmd.args, "http-fetch");
1761 strvec_pushf(&cmd.args, "--packfile=%.*s",
1762 (int) the_hash_algo->hexsz,
1763 packfile_uris.items[i].string);
1764 for (j = 0; j < index_pack_args.nr; j++)
1765 strvec_pushf(&cmd.args, "--index-pack-arg=%s",
1766 index_pack_args.v[j]);
1767 strvec_push(&cmd.args, uri);
1768 cmd.git_cmd = 1;
1769 cmd.no_stdin = 1;
1770 cmd.out = -1;
1771 if (start_command(&cmd))
1772 die("fetch-pack: unable to spawn http-fetch");
1774 if (read_in_full(cmd.out, packname, 5) < 0 ||
1775 memcmp(packname, "keep\t", 5))
1776 die("fetch-pack: expected keep then TAB at start of http-fetch output");
1778 if (read_in_full(cmd.out, packname,
1779 the_hash_algo->hexsz + 1) < 0 ||
1780 packname[the_hash_algo->hexsz] != '\n')
1781 die("fetch-pack: expected hash then LF at end of http-fetch output");
1783 packname[the_hash_algo->hexsz] = '\0';
1785 parse_gitmodules_oids(cmd.out, &fsck_options.gitmodules_found);
1787 close(cmd.out);
1789 if (finish_command(&cmd))
1790 die("fetch-pack: unable to finish http-fetch");
1792 if (memcmp(packfile_uris.items[i].string, packname,
1793 the_hash_algo->hexsz))
1794 die("fetch-pack: pack downloaded from %s does not match expected hash %.*s",
1795 uri, (int) the_hash_algo->hexsz,
1796 packfile_uris.items[i].string);
1798 string_list_append_nodup(pack_lockfiles,
1799 xstrfmt("%s/pack/pack-%s.keep",
1800 get_object_directory(),
1801 packname));
1803 string_list_clear(&packfile_uris, 0);
1804 strvec_clear(&index_pack_args);
1806 if (fsck_finish(&fsck_options))
1807 die("fsck failed");
1809 if (negotiator)
1810 negotiator->release(negotiator);
1812 oidset_clear(&common);
1813 return ref;
1816 static int fetch_pack_config_cb(const char *var, const char *value, void *cb)
1818 if (strcmp(var, "fetch.fsck.skiplist") == 0) {
1819 const char *path;
1821 if (git_config_pathname(&path, var, value))
1822 return 1;
1823 strbuf_addf(&fsck_msg_types, "%cskiplist=%s",
1824 fsck_msg_types.len ? ',' : '=', path);
1825 free((char *)path);
1826 return 0;
1829 if (skip_prefix(var, "fetch.fsck.", &var)) {
1830 if (is_valid_msg_type(var, value))
1831 strbuf_addf(&fsck_msg_types, "%c%s=%s",
1832 fsck_msg_types.len ? ',' : '=', var, value);
1833 else
1834 warning("Skipping unknown msg id '%s'", var);
1835 return 0;
1838 return git_default_config(var, value, cb);
1841 static void fetch_pack_config(void)
1843 git_config_get_int("fetch.unpacklimit", &fetch_unpack_limit);
1844 git_config_get_int("transfer.unpacklimit", &transfer_unpack_limit);
1845 git_config_get_bool("repack.usedeltabaseoffset", &prefer_ofs_delta);
1846 git_config_get_bool("fetch.fsckobjects", &fetch_fsck_objects);
1847 git_config_get_bool("transfer.fsckobjects", &transfer_fsck_objects);
1848 git_config_get_bool("transfer.advertisesid", &advertise_sid);
1849 if (!uri_protocols.nr) {
1850 char *str;
1852 if (!git_config_get_string("fetch.uriprotocols", &str) && str) {
1853 string_list_split(&uri_protocols, str, ',', -1);
1854 free(str);
1858 git_config(fetch_pack_config_cb, NULL);
1861 static void fetch_pack_setup(void)
1863 static int did_setup;
1864 if (did_setup)
1865 return;
1866 fetch_pack_config();
1867 if (0 <= transfer_unpack_limit)
1868 unpack_limit = transfer_unpack_limit;
1869 else if (0 <= fetch_unpack_limit)
1870 unpack_limit = fetch_unpack_limit;
1871 did_setup = 1;
1874 static int remove_duplicates_in_refs(struct ref **ref, int nr)
1876 struct string_list names = STRING_LIST_INIT_NODUP;
1877 int src, dst;
1879 for (src = dst = 0; src < nr; src++) {
1880 struct string_list_item *item;
1881 item = string_list_insert(&names, ref[src]->name);
1882 if (item->util)
1883 continue; /* already have it */
1884 item->util = ref[src];
1885 if (src != dst)
1886 ref[dst] = ref[src];
1887 dst++;
1889 for (src = dst; src < nr; src++)
1890 ref[src] = NULL;
1891 string_list_clear(&names, 0);
1892 return dst;
1895 static void update_shallow(struct fetch_pack_args *args,
1896 struct ref **sought, int nr_sought,
1897 struct shallow_info *si)
1899 struct oid_array ref = OID_ARRAY_INIT;
1900 int *status;
1901 int i;
1903 if (args->deepen && alternate_shallow_file) {
1904 if (*alternate_shallow_file == '\0') { /* --unshallow */
1905 unlink_or_warn(git_path_shallow(the_repository));
1906 rollback_shallow_file(the_repository, &shallow_lock);
1907 } else
1908 commit_shallow_file(the_repository, &shallow_lock);
1909 alternate_shallow_file = NULL;
1910 return;
1913 if (!si->shallow || !si->shallow->nr)
1914 return;
1916 if (args->cloning) {
1918 * remote is shallow, but this is a clone, there are
1919 * no objects in repo to worry about. Accept any
1920 * shallow points that exist in the pack (iow in repo
1921 * after get_pack() and reprepare_packed_git())
1923 struct oid_array extra = OID_ARRAY_INIT;
1924 struct object_id *oid = si->shallow->oid;
1925 for (i = 0; i < si->shallow->nr; i++)
1926 if (has_object_file(&oid[i]))
1927 oid_array_append(&extra, &oid[i]);
1928 if (extra.nr) {
1929 setup_alternate_shallow(&shallow_lock,
1930 &alternate_shallow_file,
1931 &extra);
1932 commit_shallow_file(the_repository, &shallow_lock);
1933 alternate_shallow_file = NULL;
1935 oid_array_clear(&extra);
1936 return;
1939 if (!si->nr_ours && !si->nr_theirs)
1940 return;
1942 remove_nonexistent_theirs_shallow(si);
1943 if (!si->nr_ours && !si->nr_theirs)
1944 return;
1945 for (i = 0; i < nr_sought; i++)
1946 oid_array_append(&ref, &sought[i]->old_oid);
1947 si->ref = &ref;
1949 if (args->update_shallow) {
1951 * remote is also shallow, .git/shallow may be updated
1952 * so all refs can be accepted. Make sure we only add
1953 * shallow roots that are actually reachable from new
1954 * refs.
1956 struct oid_array extra = OID_ARRAY_INIT;
1957 struct object_id *oid = si->shallow->oid;
1958 assign_shallow_commits_to_refs(si, NULL, NULL);
1959 if (!si->nr_ours && !si->nr_theirs) {
1960 oid_array_clear(&ref);
1961 return;
1963 for (i = 0; i < si->nr_ours; i++)
1964 oid_array_append(&extra, &oid[si->ours[i]]);
1965 for (i = 0; i < si->nr_theirs; i++)
1966 oid_array_append(&extra, &oid[si->theirs[i]]);
1967 setup_alternate_shallow(&shallow_lock,
1968 &alternate_shallow_file,
1969 &extra);
1970 commit_shallow_file(the_repository, &shallow_lock);
1971 oid_array_clear(&extra);
1972 oid_array_clear(&ref);
1973 alternate_shallow_file = NULL;
1974 return;
1978 * remote is also shallow, check what ref is safe to update
1979 * without updating .git/shallow
1981 CALLOC_ARRAY(status, nr_sought);
1982 assign_shallow_commits_to_refs(si, NULL, status);
1983 if (si->nr_ours || si->nr_theirs) {
1984 for (i = 0; i < nr_sought; i++)
1985 if (status[i])
1986 sought[i]->status = REF_STATUS_REJECT_SHALLOW;
1988 free(status);
1989 oid_array_clear(&ref);
1992 static const struct object_id *iterate_ref_map(void *cb_data)
1994 struct ref **rm = cb_data;
1995 struct ref *ref = *rm;
1997 if (!ref)
1998 return NULL;
1999 *rm = ref->next;
2000 return &ref->old_oid;
2003 struct ref *fetch_pack(struct fetch_pack_args *args,
2004 int fd[],
2005 const struct ref *ref,
2006 struct ref **sought, int nr_sought,
2007 struct oid_array *shallow,
2008 struct string_list *pack_lockfiles,
2009 enum protocol_version version)
2011 struct ref *ref_cpy;
2012 struct shallow_info si;
2013 struct oid_array shallows_scratch = OID_ARRAY_INIT;
2015 fetch_pack_setup();
2016 if (nr_sought)
2017 nr_sought = remove_duplicates_in_refs(sought, nr_sought);
2019 if (version != protocol_v2 && !ref) {
2020 packet_flush(fd[1]);
2021 die(_("no matching remote head"));
2023 if (version == protocol_v2) {
2024 if (shallow->nr)
2025 BUG("Protocol V2 does not provide shallows at this point in the fetch");
2026 memset(&si, 0, sizeof(si));
2027 ref_cpy = do_fetch_pack_v2(args, fd, ref, sought, nr_sought,
2028 &shallows_scratch, &si,
2029 pack_lockfiles);
2030 } else {
2031 prepare_shallow_info(&si, shallow);
2032 ref_cpy = do_fetch_pack(args, fd, ref, sought, nr_sought,
2033 &si, pack_lockfiles);
2035 reprepare_packed_git(the_repository);
2037 if (!args->cloning && args->deepen) {
2038 struct check_connected_options opt = CHECK_CONNECTED_INIT;
2039 struct ref *iterator = ref_cpy;
2040 opt.shallow_file = alternate_shallow_file;
2041 if (args->deepen)
2042 opt.is_deepening_fetch = 1;
2043 if (check_connected(iterate_ref_map, &iterator, &opt)) {
2044 error(_("remote did not send all necessary objects"));
2045 free_refs(ref_cpy);
2046 ref_cpy = NULL;
2047 rollback_shallow_file(the_repository, &shallow_lock);
2048 goto cleanup;
2050 args->connectivity_checked = 1;
2053 update_shallow(args, sought, nr_sought, &si);
2054 cleanup:
2055 clear_shallow_info(&si);
2056 oid_array_clear(&shallows_scratch);
2057 return ref_cpy;
2060 static int add_to_object_array(const struct object_id *oid, void *data)
2062 struct object_array *a = data;
2064 add_object_array(lookup_object(the_repository, oid), "", a);
2065 return 0;
2068 static void clear_common_flag(struct oidset *s)
2070 struct oidset_iter iter;
2071 const struct object_id *oid;
2072 oidset_iter_init(s, &iter);
2074 while ((oid = oidset_iter_next(&iter))) {
2075 struct object *obj = lookup_object(the_repository, oid);
2076 obj->flags &= ~COMMON;
2080 void negotiate_using_fetch(const struct oid_array *negotiation_tips,
2081 const struct string_list *server_options,
2082 int stateless_rpc,
2083 int fd[],
2084 struct oidset *acked_commits)
2086 struct fetch_negotiator negotiator;
2087 struct packet_reader reader;
2088 struct object_array nt_object_array = OBJECT_ARRAY_INIT;
2089 struct strbuf req_buf = STRBUF_INIT;
2090 int haves_to_send = INITIAL_FLUSH;
2091 int in_vain = 0;
2092 int seen_ack = 0;
2093 int last_iteration = 0;
2094 timestamp_t min_generation = GENERATION_NUMBER_INFINITY;
2096 fetch_negotiator_init(the_repository, &negotiator);
2097 mark_tips(&negotiator, negotiation_tips);
2099 packet_reader_init(&reader, fd[0], NULL, 0,
2100 PACKET_READ_CHOMP_NEWLINE |
2101 PACKET_READ_DIE_ON_ERR_PACKET);
2103 oid_array_for_each((struct oid_array *) negotiation_tips,
2104 add_to_object_array,
2105 &nt_object_array);
2107 while (!last_iteration) {
2108 int haves_added;
2109 struct object_id common_oid;
2110 int received_ready = 0;
2112 strbuf_reset(&req_buf);
2113 write_fetch_command_and_capabilities(&req_buf, server_options);
2115 packet_buf_write(&req_buf, "wait-for-done");
2117 haves_added = add_haves(&negotiator, &req_buf, &haves_to_send);
2118 in_vain += haves_added;
2119 if (!haves_added || (seen_ack && in_vain >= MAX_IN_VAIN))
2120 last_iteration = 1;
2122 /* Send request */
2123 packet_buf_flush(&req_buf);
2124 if (write_in_full(fd[1], req_buf.buf, req_buf.len) < 0)
2125 die_errno(_("unable to write request to remote"));
2127 /* Process ACKs/NAKs */
2128 process_section_header(&reader, "acknowledgments", 0);
2129 while (process_ack(&negotiator, &reader, &common_oid,
2130 &received_ready)) {
2131 struct commit *commit = lookup_commit(the_repository,
2132 &common_oid);
2133 if (commit) {
2134 timestamp_t generation;
2136 parse_commit_or_die(commit);
2137 commit->object.flags |= COMMON;
2138 generation = commit_graph_generation(commit);
2139 if (generation < min_generation)
2140 min_generation = generation;
2142 in_vain = 0;
2143 seen_ack = 1;
2144 oidset_insert(acked_commits, &common_oid);
2146 if (received_ready)
2147 die(_("unexpected 'ready' from remote"));
2148 else
2149 do_check_stateless_delimiter(stateless_rpc, &reader);
2150 if (can_all_from_reach_with_flag(&nt_object_array, COMMON,
2151 REACH_SCRATCH, 0,
2152 min_generation))
2153 last_iteration = 1;
2155 clear_common_flag(acked_commits);
2156 strbuf_release(&req_buf);
2159 int report_unmatched_refs(struct ref **sought, int nr_sought)
2161 int i, ret = 0;
2163 for (i = 0; i < nr_sought; i++) {
2164 if (!sought[i])
2165 continue;
2166 switch (sought[i]->match_status) {
2167 case REF_MATCHED:
2168 continue;
2169 case REF_NOT_MATCHED:
2170 error(_("no such remote ref %s"), sought[i]->name);
2171 break;
2172 case REF_UNADVERTISED_NOT_ALLOWED:
2173 error(_("Server does not allow request for unadvertised object %s"),
2174 sought[i]->name);
2175 break;
2177 ret = 1;
2179 return ret;