Merge branch 'mt/grep-cached-untracked'
[git/debian.git] / fetch-pack.c
blob1eaedcb5dc2ed45e18e29bf185958a663f89eccb
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"
27 static int transfer_unpack_limit = -1;
28 static int fetch_unpack_limit = -1;
29 static int unpack_limit = 100;
30 static int prefer_ofs_delta = 1;
31 static int no_done;
32 static int deepen_since_ok;
33 static int deepen_not_ok;
34 static int fetch_fsck_objects = -1;
35 static int transfer_fsck_objects = -1;
36 static int agent_supported;
37 static int server_supports_filtering;
38 static int advertise_sid;
39 static struct shallow_lock shallow_lock;
40 static const char *alternate_shallow_file;
41 static struct strbuf fsck_msg_types = STRBUF_INIT;
42 static struct string_list uri_protocols = STRING_LIST_INIT_DUP;
44 /* Remember to update object flag allocation in object.h */
45 #define COMPLETE (1U << 0)
46 #define ALTERNATE (1U << 1)
49 * After sending this many "have"s if we do not get any new ACK , we
50 * give up traversing our history.
52 #define MAX_IN_VAIN 256
54 static int multi_ack, use_sideband;
55 /* Allow specifying sha1 if it is a ref tip. */
56 #define ALLOW_TIP_SHA1 01
57 /* Allow request of a sha1 if it is reachable from a ref (possibly hidden ref). */
58 #define ALLOW_REACHABLE_SHA1 02
59 static unsigned int allow_unadvertised_object_request;
61 __attribute__((format (printf, 2, 3)))
62 static inline void print_verbose(const struct fetch_pack_args *args,
63 const char *fmt, ...)
65 va_list params;
67 if (!args->verbose)
68 return;
70 va_start(params, fmt);
71 vfprintf(stderr, fmt, params);
72 va_end(params);
73 fputc('\n', stderr);
76 struct alternate_object_cache {
77 struct object **items;
78 size_t nr, alloc;
81 static void cache_one_alternate(const struct object_id *oid,
82 void *vcache)
84 struct alternate_object_cache *cache = vcache;
85 struct object *obj = parse_object(the_repository, oid);
87 if (!obj || (obj->flags & ALTERNATE))
88 return;
90 obj->flags |= ALTERNATE;
91 ALLOC_GROW(cache->items, cache->nr + 1, cache->alloc);
92 cache->items[cache->nr++] = obj;
95 static void for_each_cached_alternate(struct fetch_negotiator *negotiator,
96 void (*cb)(struct fetch_negotiator *,
97 struct object *))
99 static int initialized;
100 static struct alternate_object_cache cache;
101 size_t i;
103 if (!initialized) {
104 for_each_alternate_ref(cache_one_alternate, &cache);
105 initialized = 1;
108 for (i = 0; i < cache.nr; i++)
109 cb(negotiator, cache.items[i]);
112 static struct commit *deref_without_lazy_fetch(const struct object_id *oid,
113 int mark_tags_complete)
115 enum object_type type;
116 struct object_info info = { .typep = &type };
118 while (1) {
119 if (oid_object_info_extended(the_repository, oid, &info,
120 OBJECT_INFO_SKIP_FETCH_OBJECT | OBJECT_INFO_QUICK))
121 return NULL;
122 if (type == OBJ_TAG) {
123 struct tag *tag = (struct tag *)
124 parse_object(the_repository, oid);
126 if (!tag->tagged)
127 return NULL;
128 if (mark_tags_complete)
129 tag->object.flags |= COMPLETE;
130 oid = &tag->tagged->oid;
131 } else {
132 break;
135 if (type == OBJ_COMMIT)
136 return (struct commit *) parse_object(the_repository, oid);
137 return NULL;
140 static int rev_list_insert_ref(struct fetch_negotiator *negotiator,
141 const struct object_id *oid)
143 struct commit *c = deref_without_lazy_fetch(oid, 0);
145 if (c)
146 negotiator->add_tip(negotiator, c);
147 return 0;
150 static int rev_list_insert_ref_oid(const char *refname, const struct object_id *oid,
151 int flag, void *cb_data)
153 return rev_list_insert_ref(cb_data, oid);
156 enum ack_type {
157 NAK = 0,
158 ACK,
159 ACK_continue,
160 ACK_common,
161 ACK_ready
164 static void consume_shallow_list(struct fetch_pack_args *args,
165 struct packet_reader *reader)
167 if (args->stateless_rpc && args->deepen) {
168 /* If we sent a depth we will get back "duplicate"
169 * shallow and unshallow commands every time there
170 * is a block of have lines exchanged.
172 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
173 if (starts_with(reader->line, "shallow "))
174 continue;
175 if (starts_with(reader->line, "unshallow "))
176 continue;
177 die(_("git fetch-pack: expected shallow list"));
179 if (reader->status != PACKET_READ_FLUSH)
180 die(_("git fetch-pack: expected a flush packet after shallow list"));
184 static enum ack_type get_ack(struct packet_reader *reader,
185 struct object_id *result_oid)
187 int len;
188 const char *arg;
190 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
191 die(_("git fetch-pack: expected ACK/NAK, got a flush packet"));
192 len = reader->pktlen;
194 if (!strcmp(reader->line, "NAK"))
195 return NAK;
196 if (skip_prefix(reader->line, "ACK ", &arg)) {
197 const char *p;
198 if (!parse_oid_hex(arg, result_oid, &p)) {
199 len -= p - reader->line;
200 if (len < 1)
201 return ACK;
202 if (strstr(p, "continue"))
203 return ACK_continue;
204 if (strstr(p, "common"))
205 return ACK_common;
206 if (strstr(p, "ready"))
207 return ACK_ready;
208 return ACK;
211 die(_("git fetch-pack: expected ACK/NAK, got '%s'"), reader->line);
214 static void send_request(struct fetch_pack_args *args,
215 int fd, struct strbuf *buf)
217 if (args->stateless_rpc) {
218 send_sideband(fd, -1, buf->buf, buf->len, LARGE_PACKET_MAX);
219 packet_flush(fd);
220 } else {
221 if (write_in_full(fd, buf->buf, buf->len) < 0)
222 die_errno(_("unable to write to remote"));
226 static void insert_one_alternate_object(struct fetch_negotiator *negotiator,
227 struct object *obj)
229 rev_list_insert_ref(negotiator, &obj->oid);
232 #define INITIAL_FLUSH 16
233 #define PIPESAFE_FLUSH 32
234 #define LARGE_FLUSH 16384
236 static int next_flush(int stateless_rpc, int count)
238 if (stateless_rpc) {
239 if (count < LARGE_FLUSH)
240 count <<= 1;
241 else
242 count = count * 11 / 10;
243 } else {
244 if (count < PIPESAFE_FLUSH)
245 count <<= 1;
246 else
247 count += PIPESAFE_FLUSH;
249 return count;
252 static void mark_tips(struct fetch_negotiator *negotiator,
253 const struct oid_array *negotiation_tips)
255 int i;
257 if (!negotiation_tips) {
258 for_each_rawref(rev_list_insert_ref_oid, negotiator);
259 return;
262 for (i = 0; i < negotiation_tips->nr; i++)
263 rev_list_insert_ref(negotiator, &negotiation_tips->oid[i]);
264 return;
267 static int find_common(struct fetch_negotiator *negotiator,
268 struct fetch_pack_args *args,
269 int fd[2], struct object_id *result_oid,
270 struct ref *refs)
272 int fetching;
273 int count = 0, flushes = 0, flush_at = INITIAL_FLUSH, retval;
274 const struct object_id *oid;
275 unsigned in_vain = 0;
276 int got_continue = 0;
277 int got_ready = 0;
278 struct strbuf req_buf = STRBUF_INIT;
279 size_t state_len = 0;
280 struct packet_reader reader;
282 if (args->stateless_rpc && multi_ack == 1)
283 die(_("--stateless-rpc requires multi_ack_detailed"));
285 packet_reader_init(&reader, fd[0], NULL, 0,
286 PACKET_READ_CHOMP_NEWLINE |
287 PACKET_READ_DIE_ON_ERR_PACKET);
289 mark_tips(negotiator, args->negotiation_tips);
290 for_each_cached_alternate(negotiator, insert_one_alternate_object);
292 fetching = 0;
293 for ( ; refs ; refs = refs->next) {
294 struct object_id *remote = &refs->old_oid;
295 const char *remote_hex;
296 struct object *o;
299 * If that object is complete (i.e. it is an ancestor of a
300 * local ref), we tell them we have it but do not have to
301 * tell them about its ancestors, which they already know
302 * about.
304 * We use lookup_object here because we are only
305 * interested in the case we *know* the object is
306 * reachable and we have already scanned it.
308 if (((o = lookup_object(the_repository, remote)) != NULL) &&
309 (o->flags & COMPLETE)) {
310 continue;
313 remote_hex = oid_to_hex(remote);
314 if (!fetching) {
315 struct strbuf c = STRBUF_INIT;
316 if (multi_ack == 2) strbuf_addstr(&c, " multi_ack_detailed");
317 if (multi_ack == 1) strbuf_addstr(&c, " multi_ack");
318 if (no_done) strbuf_addstr(&c, " no-done");
319 if (use_sideband == 2) strbuf_addstr(&c, " side-band-64k");
320 if (use_sideband == 1) strbuf_addstr(&c, " side-band");
321 if (args->deepen_relative) strbuf_addstr(&c, " deepen-relative");
322 if (args->use_thin_pack) strbuf_addstr(&c, " thin-pack");
323 if (args->no_progress) strbuf_addstr(&c, " no-progress");
324 if (args->include_tag) strbuf_addstr(&c, " include-tag");
325 if (prefer_ofs_delta) strbuf_addstr(&c, " ofs-delta");
326 if (deepen_since_ok) strbuf_addstr(&c, " deepen-since");
327 if (deepen_not_ok) strbuf_addstr(&c, " deepen-not");
328 if (agent_supported) strbuf_addf(&c, " agent=%s",
329 git_user_agent_sanitized());
330 if (advertise_sid)
331 strbuf_addf(&c, " session-id=%s", trace2_session_id());
332 if (args->filter_options.choice)
333 strbuf_addstr(&c, " filter");
334 packet_buf_write(&req_buf, "want %s%s\n", remote_hex, c.buf);
335 strbuf_release(&c);
336 } else
337 packet_buf_write(&req_buf, "want %s\n", remote_hex);
338 fetching++;
341 if (!fetching) {
342 strbuf_release(&req_buf);
343 packet_flush(fd[1]);
344 return 1;
347 if (is_repository_shallow(the_repository))
348 write_shallow_commits(&req_buf, 1, NULL);
349 if (args->depth > 0)
350 packet_buf_write(&req_buf, "deepen %d", args->depth);
351 if (args->deepen_since) {
352 timestamp_t max_age = approxidate(args->deepen_since);
353 packet_buf_write(&req_buf, "deepen-since %"PRItime, max_age);
355 if (args->deepen_not) {
356 int i;
357 for (i = 0; i < args->deepen_not->nr; i++) {
358 struct string_list_item *s = args->deepen_not->items + i;
359 packet_buf_write(&req_buf, "deepen-not %s", s->string);
362 if (server_supports_filtering && args->filter_options.choice) {
363 const char *spec =
364 expand_list_objects_filter_spec(&args->filter_options);
365 packet_buf_write(&req_buf, "filter %s", spec);
367 packet_buf_flush(&req_buf);
368 state_len = req_buf.len;
370 if (args->deepen) {
371 const char *arg;
372 struct object_id oid;
374 send_request(args, fd[1], &req_buf);
375 while (packet_reader_read(&reader) == PACKET_READ_NORMAL) {
376 if (skip_prefix(reader.line, "shallow ", &arg)) {
377 if (get_oid_hex(arg, &oid))
378 die(_("invalid shallow line: %s"), reader.line);
379 register_shallow(the_repository, &oid);
380 continue;
382 if (skip_prefix(reader.line, "unshallow ", &arg)) {
383 if (get_oid_hex(arg, &oid))
384 die(_("invalid unshallow line: %s"), reader.line);
385 if (!lookup_object(the_repository, &oid))
386 die(_("object not found: %s"), reader.line);
387 /* make sure that it is parsed as shallow */
388 if (!parse_object(the_repository, &oid))
389 die(_("error in object: %s"), reader.line);
390 if (unregister_shallow(&oid))
391 die(_("no shallow found: %s"), reader.line);
392 continue;
394 die(_("expected shallow/unshallow, got %s"), reader.line);
396 } else if (!args->stateless_rpc)
397 send_request(args, fd[1], &req_buf);
399 if (!args->stateless_rpc) {
400 /* If we aren't using the stateless-rpc interface
401 * we don't need to retain the headers.
403 strbuf_setlen(&req_buf, 0);
404 state_len = 0;
407 trace2_region_enter("fetch-pack", "negotiation_v0_v1", the_repository);
408 flushes = 0;
409 retval = -1;
410 while ((oid = negotiator->next(negotiator))) {
411 packet_buf_write(&req_buf, "have %s\n", oid_to_hex(oid));
412 print_verbose(args, "have %s", oid_to_hex(oid));
413 in_vain++;
414 if (flush_at <= ++count) {
415 int ack;
417 packet_buf_flush(&req_buf);
418 send_request(args, fd[1], &req_buf);
419 strbuf_setlen(&req_buf, state_len);
420 flushes++;
421 flush_at = next_flush(args->stateless_rpc, count);
424 * We keep one window "ahead" of the other side, and
425 * will wait for an ACK only on the next one
427 if (!args->stateless_rpc && count == INITIAL_FLUSH)
428 continue;
430 consume_shallow_list(args, &reader);
431 do {
432 ack = get_ack(&reader, result_oid);
433 if (ack)
434 print_verbose(args, _("got %s %d %s"), "ack",
435 ack, oid_to_hex(result_oid));
436 switch (ack) {
437 case ACK:
438 flushes = 0;
439 multi_ack = 0;
440 retval = 0;
441 goto done;
442 case ACK_common:
443 case ACK_ready:
444 case ACK_continue: {
445 struct commit *commit =
446 lookup_commit(the_repository,
447 result_oid);
448 int was_common;
450 if (!commit)
451 die(_("invalid commit %s"), oid_to_hex(result_oid));
452 was_common = negotiator->ack(negotiator, commit);
453 if (args->stateless_rpc
454 && ack == ACK_common
455 && !was_common) {
456 /* We need to replay the have for this object
457 * on the next RPC request so the peer knows
458 * it is in common with us.
460 const char *hex = oid_to_hex(result_oid);
461 packet_buf_write(&req_buf, "have %s\n", hex);
462 state_len = req_buf.len;
464 * Reset in_vain because an ack
465 * for this commit has not been
466 * seen.
468 in_vain = 0;
469 } else if (!args->stateless_rpc
470 || ack != ACK_common)
471 in_vain = 0;
472 retval = 0;
473 got_continue = 1;
474 if (ack == ACK_ready)
475 got_ready = 1;
476 break;
479 } while (ack);
480 flushes--;
481 if (got_continue && MAX_IN_VAIN < in_vain) {
482 print_verbose(args, _("giving up"));
483 break; /* give up */
485 if (got_ready)
486 break;
489 done:
490 trace2_region_leave("fetch-pack", "negotiation_v0_v1", the_repository);
491 if (!got_ready || !no_done) {
492 packet_buf_write(&req_buf, "done\n");
493 send_request(args, fd[1], &req_buf);
495 print_verbose(args, _("done"));
496 if (retval != 0) {
497 multi_ack = 0;
498 flushes++;
500 strbuf_release(&req_buf);
502 if (!got_ready || !no_done)
503 consume_shallow_list(args, &reader);
504 while (flushes || multi_ack) {
505 int ack = get_ack(&reader, result_oid);
506 if (ack) {
507 print_verbose(args, _("got %s (%d) %s"), "ack",
508 ack, oid_to_hex(result_oid));
509 if (ack == ACK)
510 return 0;
511 multi_ack = 1;
512 continue;
514 flushes--;
516 /* it is no error to fetch into a completely empty repo */
517 return count ? retval : 0;
520 static struct commit_list *complete;
522 static int mark_complete(const struct object_id *oid)
524 struct commit *commit = deref_without_lazy_fetch(oid, 1);
526 if (commit && !(commit->object.flags & COMPLETE)) {
527 commit->object.flags |= COMPLETE;
528 commit_list_insert(commit, &complete);
530 return 0;
533 static int mark_complete_oid(const char *refname, const struct object_id *oid,
534 int flag, void *cb_data)
536 return mark_complete(oid);
539 static void mark_recent_complete_commits(struct fetch_pack_args *args,
540 timestamp_t cutoff)
542 while (complete && cutoff <= complete->item->date) {
543 print_verbose(args, _("Marking %s as complete"),
544 oid_to_hex(&complete->item->object.oid));
545 pop_most_recent_commit(&complete, COMPLETE);
549 static void add_refs_to_oidset(struct oidset *oids, struct ref *refs)
551 for (; refs; refs = refs->next)
552 oidset_insert(oids, &refs->old_oid);
555 static int is_unmatched_ref(const struct ref *ref)
557 struct object_id oid;
558 const char *p;
559 return ref->match_status == REF_NOT_MATCHED &&
560 !parse_oid_hex(ref->name, &oid, &p) &&
561 *p == '\0' &&
562 oideq(&oid, &ref->old_oid);
565 static void filter_refs(struct fetch_pack_args *args,
566 struct ref **refs,
567 struct ref **sought, int nr_sought)
569 struct ref *newlist = NULL;
570 struct ref **newtail = &newlist;
571 struct ref *unmatched = NULL;
572 struct ref *ref, *next;
573 struct oidset tip_oids = OIDSET_INIT;
574 int i;
575 int strict = !(allow_unadvertised_object_request &
576 (ALLOW_TIP_SHA1 | ALLOW_REACHABLE_SHA1));
578 i = 0;
579 for (ref = *refs; ref; ref = next) {
580 int keep = 0;
581 next = ref->next;
583 if (starts_with(ref->name, "refs/") &&
584 check_refname_format(ref->name, 0)) {
586 * trash or a peeled value; do not even add it to
587 * unmatched list
589 free_one_ref(ref);
590 continue;
591 } else {
592 while (i < nr_sought) {
593 int cmp = strcmp(ref->name, sought[i]->name);
594 if (cmp < 0)
595 break; /* definitely do not have it */
596 else if (cmp == 0) {
597 keep = 1; /* definitely have it */
598 sought[i]->match_status = REF_MATCHED;
600 i++;
603 if (!keep && args->fetch_all &&
604 (!args->deepen || !starts_with(ref->name, "refs/tags/")))
605 keep = 1;
608 if (keep) {
609 *newtail = ref;
610 ref->next = NULL;
611 newtail = &ref->next;
612 } else {
613 ref->next = unmatched;
614 unmatched = ref;
618 if (strict) {
619 for (i = 0; i < nr_sought; i++) {
620 ref = sought[i];
621 if (!is_unmatched_ref(ref))
622 continue;
624 add_refs_to_oidset(&tip_oids, unmatched);
625 add_refs_to_oidset(&tip_oids, newlist);
626 break;
630 /* Append unmatched requests to the list */
631 for (i = 0; i < nr_sought; i++) {
632 ref = sought[i];
633 if (!is_unmatched_ref(ref))
634 continue;
636 if (!strict || oidset_contains(&tip_oids, &ref->old_oid)) {
637 ref->match_status = REF_MATCHED;
638 *newtail = copy_ref(ref);
639 newtail = &(*newtail)->next;
640 } else {
641 ref->match_status = REF_UNADVERTISED_NOT_ALLOWED;
645 oidset_clear(&tip_oids);
646 free_refs(unmatched);
648 *refs = newlist;
651 static void mark_alternate_complete(struct fetch_negotiator *unused,
652 struct object *obj)
654 mark_complete(&obj->oid);
657 struct loose_object_iter {
658 struct oidset *loose_object_set;
659 struct ref *refs;
663 * Mark recent commits available locally and reachable from a local ref as
664 * COMPLETE.
666 * The cutoff time for recency is determined by this heuristic: it is the
667 * earliest commit time of the objects in refs that are commits and that we know
668 * the commit time of.
670 static void mark_complete_and_common_ref(struct fetch_negotiator *negotiator,
671 struct fetch_pack_args *args,
672 struct ref **refs)
674 struct ref *ref;
675 int old_save_commit_buffer = save_commit_buffer;
676 timestamp_t cutoff = 0;
678 save_commit_buffer = 0;
680 trace2_region_enter("fetch-pack", "parse_remote_refs_and_find_cutoff", NULL);
681 for (ref = *refs; ref; ref = ref->next) {
682 struct object *o;
684 if (!has_object_file_with_flags(&ref->old_oid,
685 OBJECT_INFO_QUICK |
686 OBJECT_INFO_SKIP_FETCH_OBJECT))
687 continue;
688 o = parse_object(the_repository, &ref->old_oid);
689 if (!o)
690 continue;
693 * We already have it -- which may mean that we were
694 * in sync with the other side at some time after
695 * that (it is OK if we guess wrong here).
697 if (o->type == OBJ_COMMIT) {
698 struct commit *commit = (struct commit *)o;
699 if (!cutoff || cutoff < commit->date)
700 cutoff = commit->date;
703 trace2_region_leave("fetch-pack", "parse_remote_refs_and_find_cutoff", NULL);
706 * This block marks all local refs as COMPLETE, and then recursively marks all
707 * parents of those refs as COMPLETE.
709 trace2_region_enter("fetch-pack", "mark_complete_local_refs", NULL);
710 if (!args->deepen) {
711 for_each_rawref(mark_complete_oid, NULL);
712 for_each_cached_alternate(NULL, mark_alternate_complete);
713 commit_list_sort_by_date(&complete);
714 if (cutoff)
715 mark_recent_complete_commits(args, cutoff);
717 trace2_region_leave("fetch-pack", "mark_complete_local_refs", NULL);
720 * Mark all complete remote refs as common refs.
721 * Don't mark them common yet; the server has to be told so first.
723 trace2_region_enter("fetch-pack", "mark_common_remote_refs", NULL);
724 for (ref = *refs; ref; ref = ref->next) {
725 struct commit *c = deref_without_lazy_fetch(&ref->old_oid, 0);
727 if (!c || !(c->object.flags & COMPLETE))
728 continue;
730 negotiator->known_common(negotiator, c);
732 trace2_region_leave("fetch-pack", "mark_common_remote_refs", NULL);
734 save_commit_buffer = old_save_commit_buffer;
738 * Returns 1 if every object pointed to by the given remote refs is available
739 * locally and reachable from a local ref, and 0 otherwise.
741 static int everything_local(struct fetch_pack_args *args,
742 struct ref **refs)
744 struct ref *ref;
745 int retval;
747 for (retval = 1, ref = *refs; ref ; ref = ref->next) {
748 const struct object_id *remote = &ref->old_oid;
749 struct object *o;
751 o = lookup_object(the_repository, remote);
752 if (!o || !(o->flags & COMPLETE)) {
753 retval = 0;
754 print_verbose(args, "want %s (%s)", oid_to_hex(remote),
755 ref->name);
756 continue;
758 print_verbose(args, _("already have %s (%s)"), oid_to_hex(remote),
759 ref->name);
762 return retval;
765 static int sideband_demux(int in, int out, void *data)
767 int *xd = data;
768 int ret;
770 ret = recv_sideband("fetch-pack", xd[0], out);
771 close(out);
772 return ret;
775 static void create_promisor_file(const char *keep_name,
776 struct ref **sought, int nr_sought)
778 struct strbuf promisor_name = STRBUF_INIT;
779 int suffix_stripped;
781 strbuf_addstr(&promisor_name, keep_name);
782 suffix_stripped = strbuf_strip_suffix(&promisor_name, ".keep");
783 if (!suffix_stripped)
784 BUG("name of pack lockfile should end with .keep (was '%s')",
785 keep_name);
786 strbuf_addstr(&promisor_name, ".promisor");
788 write_promisor_file(promisor_name.buf, sought, nr_sought);
790 strbuf_release(&promisor_name);
794 * Pass 1 as "only_packfile" if the pack received is the only pack in this
795 * fetch request (that is, if there were no packfile URIs provided).
797 static int get_pack(struct fetch_pack_args *args,
798 int xd[2], struct string_list *pack_lockfiles,
799 int only_packfile,
800 struct ref **sought, int nr_sought)
802 struct async demux;
803 int do_keep = args->keep_pack;
804 const char *cmd_name;
805 struct pack_header header;
806 int pass_header = 0;
807 struct child_process cmd = CHILD_PROCESS_INIT;
808 int ret;
810 memset(&demux, 0, sizeof(demux));
811 if (use_sideband) {
812 /* xd[] is talking with upload-pack; subprocess reads from
813 * xd[0], spits out band#2 to stderr, and feeds us band#1
814 * through demux->out.
816 demux.proc = sideband_demux;
817 demux.data = xd;
818 demux.out = -1;
819 demux.isolate_sigpipe = 1;
820 if (start_async(&demux))
821 die(_("fetch-pack: unable to fork off sideband demultiplexer"));
823 else
824 demux.out = xd[0];
826 if (!args->keep_pack && unpack_limit) {
828 if (read_pack_header(demux.out, &header))
829 die(_("protocol error: bad pack header"));
830 pass_header = 1;
831 if (ntohl(header.hdr_entries) < unpack_limit)
832 do_keep = 0;
833 else
834 do_keep = 1;
837 if (alternate_shallow_file) {
838 strvec_push(&cmd.args, "--shallow-file");
839 strvec_push(&cmd.args, alternate_shallow_file);
842 if (do_keep || args->from_promisor) {
843 if (pack_lockfiles)
844 cmd.out = -1;
845 cmd_name = "index-pack";
846 strvec_push(&cmd.args, cmd_name);
847 strvec_push(&cmd.args, "--stdin");
848 if (!args->quiet && !args->no_progress)
849 strvec_push(&cmd.args, "-v");
850 if (args->use_thin_pack)
851 strvec_push(&cmd.args, "--fix-thin");
852 if (do_keep && (args->lock_pack || unpack_limit)) {
853 char hostname[HOST_NAME_MAX + 1];
854 if (xgethostname(hostname, sizeof(hostname)))
855 xsnprintf(hostname, sizeof(hostname), "localhost");
856 strvec_pushf(&cmd.args,
857 "--keep=fetch-pack %"PRIuMAX " on %s",
858 (uintmax_t)getpid(), hostname);
860 if (only_packfile && args->check_self_contained_and_connected)
861 strvec_push(&cmd.args, "--check-self-contained-and-connected");
862 else
864 * We cannot perform any connectivity checks because
865 * not all packs have been downloaded; let the caller
866 * have this responsibility.
868 args->check_self_contained_and_connected = 0;
870 if (args->from_promisor)
872 * create_promisor_file() may be called afterwards but
873 * we still need index-pack to know that this is a
874 * promisor pack. For example, if transfer.fsckobjects
875 * is true, index-pack needs to know that .gitmodules
876 * is a promisor object (so that it won't complain if
877 * it is missing).
879 strvec_push(&cmd.args, "--promisor");
881 else {
882 cmd_name = "unpack-objects";
883 strvec_push(&cmd.args, cmd_name);
884 if (args->quiet || args->no_progress)
885 strvec_push(&cmd.args, "-q");
886 args->check_self_contained_and_connected = 0;
889 if (pass_header)
890 strvec_pushf(&cmd.args, "--pack_header=%"PRIu32",%"PRIu32,
891 ntohl(header.hdr_version),
892 ntohl(header.hdr_entries));
893 if (fetch_fsck_objects >= 0
894 ? fetch_fsck_objects
895 : transfer_fsck_objects >= 0
896 ? transfer_fsck_objects
897 : 0) {
898 if (args->from_promisor || !only_packfile)
900 * We cannot use --strict in index-pack because it
901 * checks both broken objects and links, but we only
902 * want to check for broken objects.
904 strvec_push(&cmd.args, "--fsck-objects");
905 else
906 strvec_pushf(&cmd.args, "--strict%s",
907 fsck_msg_types.buf);
910 cmd.in = demux.out;
911 cmd.git_cmd = 1;
912 if (start_command(&cmd))
913 die(_("fetch-pack: unable to fork off %s"), cmd_name);
914 if (do_keep && pack_lockfiles) {
915 char *pack_lockfile = index_pack_lockfile(cmd.out);
916 if (pack_lockfile)
917 string_list_append_nodup(pack_lockfiles, pack_lockfile);
918 close(cmd.out);
921 if (!use_sideband)
922 /* Closed by start_command() */
923 xd[0] = -1;
925 ret = finish_command(&cmd);
926 if (!ret || (args->check_self_contained_and_connected && ret == 1))
927 args->self_contained_and_connected =
928 args->check_self_contained_and_connected &&
929 ret == 0;
930 else
931 die(_("%s failed"), cmd_name);
932 if (use_sideband && finish_async(&demux))
933 die(_("error in sideband demultiplexer"));
936 * Now that index-pack has succeeded, write the promisor file using the
937 * obtained .keep filename if necessary
939 if (do_keep && pack_lockfiles && pack_lockfiles->nr && args->from_promisor)
940 create_promisor_file(pack_lockfiles->items[0].string, sought, nr_sought);
942 return 0;
945 static int cmp_ref_by_name(const void *a_, const void *b_)
947 const struct ref *a = *((const struct ref **)a_);
948 const struct ref *b = *((const struct ref **)b_);
949 return strcmp(a->name, b->name);
952 static struct ref *do_fetch_pack(struct fetch_pack_args *args,
953 int fd[2],
954 const struct ref *orig_ref,
955 struct ref **sought, int nr_sought,
956 struct shallow_info *si,
957 struct string_list *pack_lockfiles)
959 struct repository *r = the_repository;
960 struct ref *ref = copy_ref_list(orig_ref);
961 struct object_id oid;
962 const char *agent_feature;
963 int agent_len;
964 struct fetch_negotiator negotiator_alloc;
965 struct fetch_negotiator *negotiator;
967 negotiator = &negotiator_alloc;
968 fetch_negotiator_init(r, negotiator);
970 sort_ref_list(&ref, ref_compare_name);
971 QSORT(sought, nr_sought, cmp_ref_by_name);
973 if ((agent_feature = server_feature_value("agent", &agent_len))) {
974 agent_supported = 1;
975 if (agent_len)
976 print_verbose(args, _("Server version is %.*s"),
977 agent_len, agent_feature);
980 if (!server_supports("session-id"))
981 advertise_sid = 0;
983 if (server_supports("shallow"))
984 print_verbose(args, _("Server supports %s"), "shallow");
985 else if (args->depth > 0 || is_repository_shallow(r))
986 die(_("Server does not support shallow clients"));
987 if (args->depth > 0 || args->deepen_since || args->deepen_not)
988 args->deepen = 1;
989 if (server_supports("multi_ack_detailed")) {
990 print_verbose(args, _("Server supports %s"), "multi_ack_detailed");
991 multi_ack = 2;
992 if (server_supports("no-done")) {
993 print_verbose(args, _("Server supports %s"), "no-done");
994 if (args->stateless_rpc)
995 no_done = 1;
998 else if (server_supports("multi_ack")) {
999 print_verbose(args, _("Server supports %s"), "multi_ack");
1000 multi_ack = 1;
1002 if (server_supports("side-band-64k")) {
1003 print_verbose(args, _("Server supports %s"), "side-band-64k");
1004 use_sideband = 2;
1006 else if (server_supports("side-band")) {
1007 print_verbose(args, _("Server supports %s"), "side-band");
1008 use_sideband = 1;
1010 if (server_supports("allow-tip-sha1-in-want")) {
1011 print_verbose(args, _("Server supports %s"), "allow-tip-sha1-in-want");
1012 allow_unadvertised_object_request |= ALLOW_TIP_SHA1;
1014 if (server_supports("allow-reachable-sha1-in-want")) {
1015 print_verbose(args, _("Server supports %s"), "allow-reachable-sha1-in-want");
1016 allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
1018 if (server_supports("thin-pack"))
1019 print_verbose(args, _("Server supports %s"), "thin-pack");
1020 else
1021 args->use_thin_pack = 0;
1022 if (server_supports("no-progress"))
1023 print_verbose(args, _("Server supports %s"), "no-progress");
1024 else
1025 args->no_progress = 0;
1026 if (server_supports("include-tag"))
1027 print_verbose(args, _("Server supports %s"), "include-tag");
1028 else
1029 args->include_tag = 0;
1030 if (server_supports("ofs-delta"))
1031 print_verbose(args, _("Server supports %s"), "ofs-delta");
1032 else
1033 prefer_ofs_delta = 0;
1035 if (server_supports("filter")) {
1036 server_supports_filtering = 1;
1037 print_verbose(args, _("Server supports %s"), "filter");
1038 } else if (args->filter_options.choice) {
1039 warning("filtering not recognized by server, ignoring");
1042 if (server_supports("deepen-since")) {
1043 print_verbose(args, _("Server supports %s"), "deepen-since");
1044 deepen_since_ok = 1;
1045 } else if (args->deepen_since)
1046 die(_("Server does not support --shallow-since"));
1047 if (server_supports("deepen-not")) {
1048 print_verbose(args, _("Server supports %s"), "deepen-not");
1049 deepen_not_ok = 1;
1050 } else if (args->deepen_not)
1051 die(_("Server does not support --shallow-exclude"));
1052 if (server_supports("deepen-relative"))
1053 print_verbose(args, _("Server supports %s"), "deepen-relative");
1054 else if (args->deepen_relative)
1055 die(_("Server does not support --deepen"));
1056 if (!server_supports_hash(the_hash_algo->name, NULL))
1057 die(_("Server does not support this repository's object format"));
1059 mark_complete_and_common_ref(negotiator, args, &ref);
1060 filter_refs(args, &ref, sought, nr_sought);
1061 if (everything_local(args, &ref)) {
1062 packet_flush(fd[1]);
1063 goto all_done;
1065 if (find_common(negotiator, args, fd, &oid, ref) < 0)
1066 if (!args->keep_pack)
1067 /* When cloning, it is not unusual to have
1068 * no common commit.
1070 warning(_("no common commits"));
1072 if (args->stateless_rpc)
1073 packet_flush(fd[1]);
1074 if (args->deepen)
1075 setup_alternate_shallow(&shallow_lock, &alternate_shallow_file,
1076 NULL);
1077 else if (si->nr_ours || si->nr_theirs)
1078 alternate_shallow_file = setup_temporary_shallow(si->shallow);
1079 else
1080 alternate_shallow_file = NULL;
1081 if (get_pack(args, fd, pack_lockfiles, 1, sought, nr_sought))
1082 die(_("git fetch-pack: fetch failed."));
1084 all_done:
1085 if (negotiator)
1086 negotiator->release(negotiator);
1087 return ref;
1090 static void add_shallow_requests(struct strbuf *req_buf,
1091 const struct fetch_pack_args *args)
1093 if (is_repository_shallow(the_repository))
1094 write_shallow_commits(req_buf, 1, NULL);
1095 if (args->depth > 0)
1096 packet_buf_write(req_buf, "deepen %d", args->depth);
1097 if (args->deepen_since) {
1098 timestamp_t max_age = approxidate(args->deepen_since);
1099 packet_buf_write(req_buf, "deepen-since %"PRItime, max_age);
1101 if (args->deepen_not) {
1102 int i;
1103 for (i = 0; i < args->deepen_not->nr; i++) {
1104 struct string_list_item *s = args->deepen_not->items + i;
1105 packet_buf_write(req_buf, "deepen-not %s", s->string);
1108 if (args->deepen_relative)
1109 packet_buf_write(req_buf, "deepen-relative\n");
1112 static void add_wants(const struct ref *wants, struct strbuf *req_buf)
1114 int use_ref_in_want = server_supports_feature("fetch", "ref-in-want", 0);
1116 for ( ; wants ; wants = wants->next) {
1117 const struct object_id *remote = &wants->old_oid;
1118 struct object *o;
1121 * If that object is complete (i.e. it is an ancestor of a
1122 * local ref), we tell them we have it but do not have to
1123 * tell them about its ancestors, which they already know
1124 * about.
1126 * We use lookup_object here because we are only
1127 * interested in the case we *know* the object is
1128 * reachable and we have already scanned it.
1130 if (((o = lookup_object(the_repository, remote)) != NULL) &&
1131 (o->flags & COMPLETE)) {
1132 continue;
1135 if (!use_ref_in_want || wants->exact_oid)
1136 packet_buf_write(req_buf, "want %s\n", oid_to_hex(remote));
1137 else
1138 packet_buf_write(req_buf, "want-ref %s\n", wants->name);
1142 static void add_common(struct strbuf *req_buf, struct oidset *common)
1144 struct oidset_iter iter;
1145 const struct object_id *oid;
1146 oidset_iter_init(common, &iter);
1148 while ((oid = oidset_iter_next(&iter))) {
1149 packet_buf_write(req_buf, "have %s\n", oid_to_hex(oid));
1153 static int add_haves(struct fetch_negotiator *negotiator,
1154 int seen_ack,
1155 struct strbuf *req_buf,
1156 int *haves_to_send, int *in_vain)
1158 int ret = 0;
1159 int haves_added = 0;
1160 const struct object_id *oid;
1162 while ((oid = negotiator->next(negotiator))) {
1163 packet_buf_write(req_buf, "have %s\n", oid_to_hex(oid));
1164 if (++haves_added >= *haves_to_send)
1165 break;
1168 *in_vain += haves_added;
1169 if (!haves_added || (seen_ack && *in_vain >= MAX_IN_VAIN)) {
1170 /* Send Done */
1171 packet_buf_write(req_buf, "done\n");
1172 ret = 1;
1175 /* Increase haves to send on next round */
1176 *haves_to_send = next_flush(1, *haves_to_send);
1178 return ret;
1181 static int send_fetch_request(struct fetch_negotiator *negotiator, int fd_out,
1182 struct fetch_pack_args *args,
1183 const struct ref *wants, struct oidset *common,
1184 int *haves_to_send, int *in_vain,
1185 int sideband_all, int seen_ack)
1187 int ret = 0;
1188 const char *hash_name;
1189 struct strbuf req_buf = STRBUF_INIT;
1191 if (server_supports_v2("fetch", 1))
1192 packet_buf_write(&req_buf, "command=fetch");
1193 if (server_supports_v2("agent", 0))
1194 packet_buf_write(&req_buf, "agent=%s", git_user_agent_sanitized());
1195 if (advertise_sid && server_supports_v2("session-id", 0))
1196 packet_buf_write(&req_buf, "session-id=%s", trace2_session_id());
1197 if (args->server_options && args->server_options->nr &&
1198 server_supports_v2("server-option", 1)) {
1199 int i;
1200 for (i = 0; i < args->server_options->nr; i++)
1201 packet_buf_write(&req_buf, "server-option=%s",
1202 args->server_options->items[i].string);
1205 if (server_feature_v2("object-format", &hash_name)) {
1206 int hash_algo = hash_algo_by_name(hash_name);
1207 if (hash_algo_by_ptr(the_hash_algo) != hash_algo)
1208 die(_("mismatched algorithms: client %s; server %s"),
1209 the_hash_algo->name, hash_name);
1210 packet_write_fmt(fd_out, "object-format=%s", the_hash_algo->name);
1211 } else if (hash_algo_by_ptr(the_hash_algo) != GIT_HASH_SHA1) {
1212 die(_("the server does not support algorithm '%s'"),
1213 the_hash_algo->name);
1216 packet_buf_delim(&req_buf);
1217 if (args->use_thin_pack)
1218 packet_buf_write(&req_buf, "thin-pack");
1219 if (args->no_progress)
1220 packet_buf_write(&req_buf, "no-progress");
1221 if (args->include_tag)
1222 packet_buf_write(&req_buf, "include-tag");
1223 if (prefer_ofs_delta)
1224 packet_buf_write(&req_buf, "ofs-delta");
1225 if (sideband_all)
1226 packet_buf_write(&req_buf, "sideband-all");
1228 /* Add shallow-info and deepen request */
1229 if (server_supports_feature("fetch", "shallow", 0))
1230 add_shallow_requests(&req_buf, args);
1231 else if (is_repository_shallow(the_repository) || args->deepen)
1232 die(_("Server does not support shallow requests"));
1234 /* Add filter */
1235 if (server_supports_feature("fetch", "filter", 0) &&
1236 args->filter_options.choice) {
1237 const char *spec =
1238 expand_list_objects_filter_spec(&args->filter_options);
1239 print_verbose(args, _("Server supports filter"));
1240 packet_buf_write(&req_buf, "filter %s", spec);
1241 } else if (args->filter_options.choice) {
1242 warning("filtering not recognized by server, ignoring");
1245 if (server_supports_feature("fetch", "packfile-uris", 0)) {
1246 int i;
1247 struct strbuf to_send = STRBUF_INIT;
1249 for (i = 0; i < uri_protocols.nr; i++) {
1250 const char *s = uri_protocols.items[i].string;
1252 if (!strcmp(s, "https") || !strcmp(s, "http")) {
1253 if (to_send.len)
1254 strbuf_addch(&to_send, ',');
1255 strbuf_addstr(&to_send, s);
1258 if (to_send.len) {
1259 packet_buf_write(&req_buf, "packfile-uris %s",
1260 to_send.buf);
1261 strbuf_release(&to_send);
1265 /* add wants */
1266 add_wants(wants, &req_buf);
1268 /* Add all of the common commits we've found in previous rounds */
1269 add_common(&req_buf, common);
1271 /* Add initial haves */
1272 ret = add_haves(negotiator, seen_ack, &req_buf,
1273 haves_to_send, in_vain);
1275 /* Send request */
1276 packet_buf_flush(&req_buf);
1277 if (write_in_full(fd_out, req_buf.buf, req_buf.len) < 0)
1278 die_errno(_("unable to write request to remote"));
1280 strbuf_release(&req_buf);
1281 return ret;
1285 * Processes a section header in a server's response and checks if it matches
1286 * `section`. If the value of `peek` is 1, the header line will be peeked (and
1287 * not consumed); if 0, the line will be consumed and the function will die if
1288 * the section header doesn't match what was expected.
1290 static int process_section_header(struct packet_reader *reader,
1291 const char *section, int peek)
1293 int ret;
1295 if (packet_reader_peek(reader) != PACKET_READ_NORMAL)
1296 die(_("error reading section header '%s'"), section);
1298 ret = !strcmp(reader->line, section);
1300 if (!peek) {
1301 if (!ret)
1302 die(_("expected '%s', received '%s'"),
1303 section, reader->line);
1304 packet_reader_read(reader);
1307 return ret;
1310 enum common_found {
1312 * No commit was found to be possessed by both the client and the
1313 * server, and "ready" was not received.
1315 NO_COMMON_FOUND,
1318 * At least one commit was found to be possessed by both the client and
1319 * the server, and "ready" was not received.
1321 COMMON_FOUND,
1324 * "ready" was received, indicating that the server is ready to send
1325 * the packfile without any further negotiation.
1327 READY
1330 static enum common_found process_acks(struct fetch_negotiator *negotiator,
1331 struct packet_reader *reader,
1332 struct oidset *common)
1334 /* received */
1335 int received_ready = 0;
1336 int received_ack = 0;
1338 process_section_header(reader, "acknowledgments", 0);
1339 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1340 const char *arg;
1342 if (!strcmp(reader->line, "NAK"))
1343 continue;
1345 if (skip_prefix(reader->line, "ACK ", &arg)) {
1346 struct object_id oid;
1347 received_ack = 1;
1348 if (!get_oid_hex(arg, &oid)) {
1349 struct commit *commit;
1350 oidset_insert(common, &oid);
1351 commit = lookup_commit(the_repository, &oid);
1352 if (negotiator)
1353 negotiator->ack(negotiator, commit);
1355 continue;
1358 if (!strcmp(reader->line, "ready")) {
1359 received_ready = 1;
1360 continue;
1363 die(_("unexpected acknowledgment line: '%s'"), reader->line);
1366 if (reader->status != PACKET_READ_FLUSH &&
1367 reader->status != PACKET_READ_DELIM)
1368 die(_("error processing acks: %d"), reader->status);
1371 * If an "acknowledgments" section is sent, a packfile is sent if and
1372 * only if "ready" was sent in this section. The other sections
1373 * ("shallow-info" and "wanted-refs") are sent only if a packfile is
1374 * sent. Therefore, a DELIM is expected if "ready" is sent, and a FLUSH
1375 * otherwise.
1377 if (received_ready && reader->status != PACKET_READ_DELIM)
1378 die(_("expected packfile to be sent after 'ready'"));
1379 if (!received_ready && reader->status != PACKET_READ_FLUSH)
1380 die(_("expected no other sections to be sent after no 'ready'"));
1382 return received_ready ? READY :
1383 (received_ack ? COMMON_FOUND : NO_COMMON_FOUND);
1386 static void receive_shallow_info(struct fetch_pack_args *args,
1387 struct packet_reader *reader,
1388 struct oid_array *shallows,
1389 struct shallow_info *si)
1391 int unshallow_received = 0;
1393 process_section_header(reader, "shallow-info", 0);
1394 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1395 const char *arg;
1396 struct object_id oid;
1398 if (skip_prefix(reader->line, "shallow ", &arg)) {
1399 if (get_oid_hex(arg, &oid))
1400 die(_("invalid shallow line: %s"), reader->line);
1401 oid_array_append(shallows, &oid);
1402 continue;
1404 if (skip_prefix(reader->line, "unshallow ", &arg)) {
1405 if (get_oid_hex(arg, &oid))
1406 die(_("invalid unshallow line: %s"), reader->line);
1407 if (!lookup_object(the_repository, &oid))
1408 die(_("object not found: %s"), reader->line);
1409 /* make sure that it is parsed as shallow */
1410 if (!parse_object(the_repository, &oid))
1411 die(_("error in object: %s"), reader->line);
1412 if (unregister_shallow(&oid))
1413 die(_("no shallow found: %s"), reader->line);
1414 unshallow_received = 1;
1415 continue;
1417 die(_("expected shallow/unshallow, got %s"), reader->line);
1420 if (reader->status != PACKET_READ_FLUSH &&
1421 reader->status != PACKET_READ_DELIM)
1422 die(_("error processing shallow info: %d"), reader->status);
1424 if (args->deepen || unshallow_received) {
1426 * Treat these as shallow lines caused by our depth settings.
1427 * In v0, these lines cannot cause refs to be rejected; do the
1428 * same.
1430 int i;
1432 for (i = 0; i < shallows->nr; i++)
1433 register_shallow(the_repository, &shallows->oid[i]);
1434 setup_alternate_shallow(&shallow_lock, &alternate_shallow_file,
1435 NULL);
1436 args->deepen = 1;
1437 } else if (shallows->nr) {
1439 * Treat these as shallow lines caused by the remote being
1440 * shallow. In v0, remote refs that reach these objects are
1441 * rejected (unless --update-shallow is set); do the same.
1443 prepare_shallow_info(si, shallows);
1444 if (si->nr_ours || si->nr_theirs)
1445 alternate_shallow_file =
1446 setup_temporary_shallow(si->shallow);
1447 else
1448 alternate_shallow_file = NULL;
1449 } else {
1450 alternate_shallow_file = NULL;
1454 static int cmp_name_ref(const void *name, const void *ref)
1456 return strcmp(name, (*(struct ref **)ref)->name);
1459 static void receive_wanted_refs(struct packet_reader *reader,
1460 struct ref **sought, int nr_sought)
1462 process_section_header(reader, "wanted-refs", 0);
1463 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1464 struct object_id oid;
1465 const char *end;
1466 struct ref **found;
1468 if (parse_oid_hex(reader->line, &oid, &end) || *end++ != ' ')
1469 die(_("expected wanted-ref, got '%s'"), reader->line);
1471 found = bsearch(end, sought, nr_sought, sizeof(*sought),
1472 cmp_name_ref);
1473 if (!found)
1474 die(_("unexpected wanted-ref: '%s'"), reader->line);
1475 oidcpy(&(*found)->old_oid, &oid);
1478 if (reader->status != PACKET_READ_DELIM)
1479 die(_("error processing wanted refs: %d"), reader->status);
1482 static void receive_packfile_uris(struct packet_reader *reader,
1483 struct string_list *uris)
1485 process_section_header(reader, "packfile-uris", 0);
1486 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1487 if (reader->pktlen < the_hash_algo->hexsz ||
1488 reader->line[the_hash_algo->hexsz] != ' ')
1489 die("expected '<hash> <uri>', got: %s\n", reader->line);
1491 string_list_append(uris, reader->line);
1493 if (reader->status != PACKET_READ_DELIM)
1494 die("expected DELIM");
1497 enum fetch_state {
1498 FETCH_CHECK_LOCAL = 0,
1499 FETCH_SEND_REQUEST,
1500 FETCH_PROCESS_ACKS,
1501 FETCH_GET_PACK,
1502 FETCH_DONE,
1505 static void do_check_stateless_delimiter(const struct fetch_pack_args *args,
1506 struct packet_reader *reader)
1508 check_stateless_delimiter(args->stateless_rpc, reader,
1509 _("git fetch-pack: expected response end packet"));
1512 static struct ref *do_fetch_pack_v2(struct fetch_pack_args *args,
1513 int fd[2],
1514 const struct ref *orig_ref,
1515 struct ref **sought, int nr_sought,
1516 struct oid_array *shallows,
1517 struct shallow_info *si,
1518 struct string_list *pack_lockfiles)
1520 struct repository *r = the_repository;
1521 struct ref *ref = copy_ref_list(orig_ref);
1522 enum fetch_state state = FETCH_CHECK_LOCAL;
1523 struct oidset common = OIDSET_INIT;
1524 struct packet_reader reader;
1525 int in_vain = 0, negotiation_started = 0;
1526 int haves_to_send = INITIAL_FLUSH;
1527 struct fetch_negotiator negotiator_alloc;
1528 struct fetch_negotiator *negotiator;
1529 int seen_ack = 0;
1530 struct string_list packfile_uris = STRING_LIST_INIT_DUP;
1531 int i;
1533 negotiator = &negotiator_alloc;
1534 fetch_negotiator_init(r, negotiator);
1536 packet_reader_init(&reader, fd[0], NULL, 0,
1537 PACKET_READ_CHOMP_NEWLINE |
1538 PACKET_READ_DIE_ON_ERR_PACKET);
1539 if (git_env_bool("GIT_TEST_SIDEBAND_ALL", 1) &&
1540 server_supports_feature("fetch", "sideband-all", 0)) {
1541 reader.use_sideband = 1;
1542 reader.me = "fetch-pack";
1545 while (state != FETCH_DONE) {
1546 switch (state) {
1547 case FETCH_CHECK_LOCAL:
1548 sort_ref_list(&ref, ref_compare_name);
1549 QSORT(sought, nr_sought, cmp_ref_by_name);
1551 /* v2 supports these by default */
1552 allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
1553 use_sideband = 2;
1554 if (args->depth > 0 || args->deepen_since || args->deepen_not)
1555 args->deepen = 1;
1557 /* Filter 'ref' by 'sought' and those that aren't local */
1558 mark_complete_and_common_ref(negotiator, args, &ref);
1559 filter_refs(args, &ref, sought, nr_sought);
1560 if (everything_local(args, &ref))
1561 state = FETCH_DONE;
1562 else
1563 state = FETCH_SEND_REQUEST;
1565 mark_tips(negotiator, args->negotiation_tips);
1566 for_each_cached_alternate(negotiator,
1567 insert_one_alternate_object);
1568 break;
1569 case FETCH_SEND_REQUEST:
1570 if (!negotiation_started) {
1571 negotiation_started = 1;
1572 trace2_region_enter("fetch-pack",
1573 "negotiation_v2",
1574 the_repository);
1576 if (send_fetch_request(negotiator, fd[1], args, ref,
1577 &common,
1578 &haves_to_send, &in_vain,
1579 reader.use_sideband,
1580 seen_ack))
1581 state = FETCH_GET_PACK;
1582 else
1583 state = FETCH_PROCESS_ACKS;
1584 break;
1585 case FETCH_PROCESS_ACKS:
1586 /* Process ACKs/NAKs */
1587 switch (process_acks(negotiator, &reader, &common)) {
1588 case READY:
1590 * Don't check for response delimiter; get_pack() will
1591 * read the rest of this response.
1593 state = FETCH_GET_PACK;
1594 break;
1595 case COMMON_FOUND:
1596 in_vain = 0;
1597 seen_ack = 1;
1598 /* fallthrough */
1599 case NO_COMMON_FOUND:
1600 do_check_stateless_delimiter(args, &reader);
1601 state = FETCH_SEND_REQUEST;
1602 break;
1604 break;
1605 case FETCH_GET_PACK:
1606 trace2_region_leave("fetch-pack",
1607 "negotiation_v2",
1608 the_repository);
1609 /* Check for shallow-info section */
1610 if (process_section_header(&reader, "shallow-info", 1))
1611 receive_shallow_info(args, &reader, shallows, si);
1613 if (process_section_header(&reader, "wanted-refs", 1))
1614 receive_wanted_refs(&reader, sought, nr_sought);
1616 /* get the pack(s) */
1617 if (process_section_header(&reader, "packfile-uris", 1))
1618 receive_packfile_uris(&reader, &packfile_uris);
1619 process_section_header(&reader, "packfile", 0);
1620 if (get_pack(args, fd, pack_lockfiles,
1621 !packfile_uris.nr, sought, nr_sought))
1622 die(_("git fetch-pack: fetch failed."));
1623 do_check_stateless_delimiter(args, &reader);
1625 state = FETCH_DONE;
1626 break;
1627 case FETCH_DONE:
1628 continue;
1632 for (i = 0; i < packfile_uris.nr; i++) {
1633 struct child_process cmd = CHILD_PROCESS_INIT;
1634 char packname[GIT_MAX_HEXSZ + 1];
1635 const char *uri = packfile_uris.items[i].string +
1636 the_hash_algo->hexsz + 1;
1638 strvec_push(&cmd.args, "http-fetch");
1639 strvec_pushf(&cmd.args, "--packfile=%.*s",
1640 (int) the_hash_algo->hexsz,
1641 packfile_uris.items[i].string);
1642 strvec_push(&cmd.args, uri);
1643 cmd.git_cmd = 1;
1644 cmd.no_stdin = 1;
1645 cmd.out = -1;
1646 if (start_command(&cmd))
1647 die("fetch-pack: unable to spawn http-fetch");
1649 if (read_in_full(cmd.out, packname, 5) < 0 ||
1650 memcmp(packname, "keep\t", 5))
1651 die("fetch-pack: expected keep then TAB at start of http-fetch output");
1653 if (read_in_full(cmd.out, packname,
1654 the_hash_algo->hexsz + 1) < 0 ||
1655 packname[the_hash_algo->hexsz] != '\n')
1656 die("fetch-pack: expected hash then LF at end of http-fetch output");
1658 packname[the_hash_algo->hexsz] = '\0';
1660 close(cmd.out);
1662 if (finish_command(&cmd))
1663 die("fetch-pack: unable to finish http-fetch");
1665 if (memcmp(packfile_uris.items[i].string, packname,
1666 the_hash_algo->hexsz))
1667 die("fetch-pack: pack downloaded from %s does not match expected hash %.*s",
1668 uri, (int) the_hash_algo->hexsz,
1669 packfile_uris.items[i].string);
1671 string_list_append_nodup(pack_lockfiles,
1672 xstrfmt("%s/pack/pack-%s.keep",
1673 get_object_directory(),
1674 packname));
1676 string_list_clear(&packfile_uris, 0);
1678 if (negotiator)
1679 negotiator->release(negotiator);
1681 oidset_clear(&common);
1682 return ref;
1685 static int fetch_pack_config_cb(const char *var, const char *value, void *cb)
1687 if (strcmp(var, "fetch.fsck.skiplist") == 0) {
1688 const char *path;
1690 if (git_config_pathname(&path, var, value))
1691 return 1;
1692 strbuf_addf(&fsck_msg_types, "%cskiplist=%s",
1693 fsck_msg_types.len ? ',' : '=', path);
1694 free((char *)path);
1695 return 0;
1698 if (skip_prefix(var, "fetch.fsck.", &var)) {
1699 if (is_valid_msg_type(var, value))
1700 strbuf_addf(&fsck_msg_types, "%c%s=%s",
1701 fsck_msg_types.len ? ',' : '=', var, value);
1702 else
1703 warning("Skipping unknown msg id '%s'", var);
1704 return 0;
1707 return git_default_config(var, value, cb);
1710 static void fetch_pack_config(void)
1712 git_config_get_int("fetch.unpacklimit", &fetch_unpack_limit);
1713 git_config_get_int("transfer.unpacklimit", &transfer_unpack_limit);
1714 git_config_get_bool("repack.usedeltabaseoffset", &prefer_ofs_delta);
1715 git_config_get_bool("fetch.fsckobjects", &fetch_fsck_objects);
1716 git_config_get_bool("transfer.fsckobjects", &transfer_fsck_objects);
1717 git_config_get_bool("transfer.advertisesid", &advertise_sid);
1718 if (!uri_protocols.nr) {
1719 char *str;
1721 if (!git_config_get_string("fetch.uriprotocols", &str) && str) {
1722 string_list_split(&uri_protocols, str, ',', -1);
1723 free(str);
1727 git_config(fetch_pack_config_cb, NULL);
1730 static void fetch_pack_setup(void)
1732 static int did_setup;
1733 if (did_setup)
1734 return;
1735 fetch_pack_config();
1736 if (0 <= transfer_unpack_limit)
1737 unpack_limit = transfer_unpack_limit;
1738 else if (0 <= fetch_unpack_limit)
1739 unpack_limit = fetch_unpack_limit;
1740 did_setup = 1;
1743 static int remove_duplicates_in_refs(struct ref **ref, int nr)
1745 struct string_list names = STRING_LIST_INIT_NODUP;
1746 int src, dst;
1748 for (src = dst = 0; src < nr; src++) {
1749 struct string_list_item *item;
1750 item = string_list_insert(&names, ref[src]->name);
1751 if (item->util)
1752 continue; /* already have it */
1753 item->util = ref[src];
1754 if (src != dst)
1755 ref[dst] = ref[src];
1756 dst++;
1758 for (src = dst; src < nr; src++)
1759 ref[src] = NULL;
1760 string_list_clear(&names, 0);
1761 return dst;
1764 static void update_shallow(struct fetch_pack_args *args,
1765 struct ref **sought, int nr_sought,
1766 struct shallow_info *si)
1768 struct oid_array ref = OID_ARRAY_INIT;
1769 int *status;
1770 int i;
1772 if (args->deepen && alternate_shallow_file) {
1773 if (*alternate_shallow_file == '\0') { /* --unshallow */
1774 unlink_or_warn(git_path_shallow(the_repository));
1775 rollback_shallow_file(the_repository, &shallow_lock);
1776 } else
1777 commit_shallow_file(the_repository, &shallow_lock);
1778 alternate_shallow_file = NULL;
1779 return;
1782 if (!si->shallow || !si->shallow->nr)
1783 return;
1785 if (args->cloning) {
1787 * remote is shallow, but this is a clone, there are
1788 * no objects in repo to worry about. Accept any
1789 * shallow points that exist in the pack (iow in repo
1790 * after get_pack() and reprepare_packed_git())
1792 struct oid_array extra = OID_ARRAY_INIT;
1793 struct object_id *oid = si->shallow->oid;
1794 for (i = 0; i < si->shallow->nr; i++)
1795 if (has_object_file(&oid[i]))
1796 oid_array_append(&extra, &oid[i]);
1797 if (extra.nr) {
1798 setup_alternate_shallow(&shallow_lock,
1799 &alternate_shallow_file,
1800 &extra);
1801 commit_shallow_file(the_repository, &shallow_lock);
1802 alternate_shallow_file = NULL;
1804 oid_array_clear(&extra);
1805 return;
1808 if (!si->nr_ours && !si->nr_theirs)
1809 return;
1811 remove_nonexistent_theirs_shallow(si);
1812 if (!si->nr_ours && !si->nr_theirs)
1813 return;
1814 for (i = 0; i < nr_sought; i++)
1815 oid_array_append(&ref, &sought[i]->old_oid);
1816 si->ref = &ref;
1818 if (args->update_shallow) {
1820 * remote is also shallow, .git/shallow may be updated
1821 * so all refs can be accepted. Make sure we only add
1822 * shallow roots that are actually reachable from new
1823 * refs.
1825 struct oid_array extra = OID_ARRAY_INIT;
1826 struct object_id *oid = si->shallow->oid;
1827 assign_shallow_commits_to_refs(si, NULL, NULL);
1828 if (!si->nr_ours && !si->nr_theirs) {
1829 oid_array_clear(&ref);
1830 return;
1832 for (i = 0; i < si->nr_ours; i++)
1833 oid_array_append(&extra, &oid[si->ours[i]]);
1834 for (i = 0; i < si->nr_theirs; i++)
1835 oid_array_append(&extra, &oid[si->theirs[i]]);
1836 setup_alternate_shallow(&shallow_lock,
1837 &alternate_shallow_file,
1838 &extra);
1839 commit_shallow_file(the_repository, &shallow_lock);
1840 oid_array_clear(&extra);
1841 oid_array_clear(&ref);
1842 alternate_shallow_file = NULL;
1843 return;
1847 * remote is also shallow, check what ref is safe to update
1848 * without updating .git/shallow
1850 status = xcalloc(nr_sought, sizeof(*status));
1851 assign_shallow_commits_to_refs(si, NULL, status);
1852 if (si->nr_ours || si->nr_theirs) {
1853 for (i = 0; i < nr_sought; i++)
1854 if (status[i])
1855 sought[i]->status = REF_STATUS_REJECT_SHALLOW;
1857 free(status);
1858 oid_array_clear(&ref);
1861 static int iterate_ref_map(void *cb_data, struct object_id *oid)
1863 struct ref **rm = cb_data;
1864 struct ref *ref = *rm;
1866 if (!ref)
1867 return -1; /* end of the list */
1868 *rm = ref->next;
1869 oidcpy(oid, &ref->old_oid);
1870 return 0;
1873 struct ref *fetch_pack(struct fetch_pack_args *args,
1874 int fd[],
1875 const struct ref *ref,
1876 struct ref **sought, int nr_sought,
1877 struct oid_array *shallow,
1878 struct string_list *pack_lockfiles,
1879 enum protocol_version version)
1881 struct ref *ref_cpy;
1882 struct shallow_info si;
1883 struct oid_array shallows_scratch = OID_ARRAY_INIT;
1885 fetch_pack_setup();
1886 if (nr_sought)
1887 nr_sought = remove_duplicates_in_refs(sought, nr_sought);
1889 if (version != protocol_v2 && !ref) {
1890 packet_flush(fd[1]);
1891 die(_("no matching remote head"));
1893 if (version == protocol_v2) {
1894 if (shallow->nr)
1895 BUG("Protocol V2 does not provide shallows at this point in the fetch");
1896 memset(&si, 0, sizeof(si));
1897 ref_cpy = do_fetch_pack_v2(args, fd, ref, sought, nr_sought,
1898 &shallows_scratch, &si,
1899 pack_lockfiles);
1900 } else {
1901 prepare_shallow_info(&si, shallow);
1902 ref_cpy = do_fetch_pack(args, fd, ref, sought, nr_sought,
1903 &si, pack_lockfiles);
1905 reprepare_packed_git(the_repository);
1907 if (!args->cloning && args->deepen) {
1908 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1909 struct ref *iterator = ref_cpy;
1910 opt.shallow_file = alternate_shallow_file;
1911 if (args->deepen)
1912 opt.is_deepening_fetch = 1;
1913 if (check_connected(iterate_ref_map, &iterator, &opt)) {
1914 error(_("remote did not send all necessary objects"));
1915 free_refs(ref_cpy);
1916 ref_cpy = NULL;
1917 rollback_shallow_file(the_repository, &shallow_lock);
1918 goto cleanup;
1920 args->connectivity_checked = 1;
1923 update_shallow(args, sought, nr_sought, &si);
1924 cleanup:
1925 clear_shallow_info(&si);
1926 oid_array_clear(&shallows_scratch);
1927 return ref_cpy;
1930 int report_unmatched_refs(struct ref **sought, int nr_sought)
1932 int i, ret = 0;
1934 for (i = 0; i < nr_sought; i++) {
1935 if (!sought[i])
1936 continue;
1937 switch (sought[i]->match_status) {
1938 case REF_MATCHED:
1939 continue;
1940 case REF_NOT_MATCHED:
1941 error(_("no such remote ref %s"), sought[i]->name);
1942 break;
1943 case REF_UNADVERTISED_NOT_ALLOWED:
1944 error(_("Server does not allow request for unadvertised object %s"),
1945 sought[i]->name);
1946 break;
1948 ret = 1;
1950 return ret;