Raw
1 #define USE_THE_REPOSITORY_VARIABLE
2 #define DISABLE_SIGN_COMPARE_WARNINGS
3
4 #include "git-compat-util.h"
5 #include "repository.h"
6 #include "config.h"
7 #include "date.h"
8 #include "environment.h"
9 #include "gettext.h"
10 #include "hex.h"
11 #include "lockfile.h"
12 #include "refs.h"
13 #include "pkt-line.h"
14 #include "commit.h"
15 #include "tag.h"
16 #include "pack.h"
17 #include "sideband.h"
18 #include "fetch-pack.h"
19 #include "remote.h"
20 #include "run-command.h"
21 #include "connect.h"
22 #include "trace2.h"
23 #include "version.h"
24 #include "oid-array.h"
25 #include "oidset.h"
26 #include "packfile.h"
27 #include "odb.h"
28 #include "object-name.h"
29 #include "path.h"
30 #include "connected.h"
31 #include "fetch-negotiator.h"
32 #include "fsck.h"
33 #include "shallow.h"
34 #include "commit-reach.h"
35 #include "commit-graph.h"
36 #include "sigchain.h"
37 #include "mergesort.h"
38 #include "prio-queue.h"
39 #include "promisor-remote.h"
40
41 static int transfer_unpack_limit = -1;
42 static int fetch_unpack_limit = -1;
43 static int unpack_limit = 100;
44 static int prefer_ofs_delta = 1;
45 static int no_done;
46 static int deepen_since_ok;
47 static int deepen_not_ok;
48 static int fetch_fsck_objects = -1;
49 static int transfer_fsck_objects = -1;
50 static int agent_supported;
51 static int server_supports_filtering;
52 static int advertise_sid;
53 static struct shallow_lock shallow_lock;
54 static const char *alternate_shallow_file;
55 static struct strbuf fsck_msg_types = STRBUF_INIT;
56 static struct string_list uri_protocols = STRING_LIST_INIT_DUP;
57
58 /* Remember to update object flag allocation in object.h */
59 #define COMPLETE (1U << 0)
60 #define ALTERNATE (1U << 1)
61 #define COMMON (1U << 6)
62 #define REACH_SCRATCH (1U << 7)
63
64 /*
65 * After sending this many "have"s if we do not get any new ACK , we
66 * give up traversing our history.
67 */
68 #define MAX_IN_VAIN 256
69
70 static int multi_ack, use_sideband;
71 /* Allow specifying sha1 if it is a ref tip. */
72 #define ALLOW_TIP_SHA1 01
73 /* Allow request of a sha1 if it is reachable from a ref (possibly hidden ref). */
74 #define ALLOW_REACHABLE_SHA1 02
75 static unsigned int allow_unadvertised_object_request;
76
77 __attribute__((format (printf, 2, 3)))
78 static inline void print_verbose(const struct fetch_pack_args *args,
79 const char *fmt, ...)
80 {
81 va_list params;
82
83 if (!args->verbose)
84 return;
85
86 va_start(params, fmt);
87 vfprintf(stderr, fmt, params);
88 va_end(params);
89 fputc('\n', stderr);
90 }
91
92 struct alternate_object_cache {
93 struct object **items;
94 size_t nr, alloc;
95 };
96
97 static void cache_one_alternate(const struct object_id *oid,
98 void *vcache)
99 {
100 struct alternate_object_cache *cache = vcache;
101 struct object *obj = parse_object(the_repository, oid);
102
103 if (!obj || (obj->flags & ALTERNATE))
104 return;
105
106 obj->flags |= ALTERNATE;
107 ALLOC_GROW(cache->items, cache->nr + 1, cache->alloc);
108 cache->items[cache->nr++] = obj;
109 }
110
111 static void for_each_cached_alternate(struct fetch_negotiator *negotiator,
112 void (*cb)(struct fetch_negotiator *,
113 struct object *))
114 {
115 static int initialized;
116 static struct alternate_object_cache cache;
117 size_t i;
118
119 if (!initialized) {
120 odb_for_each_alternate_ref(the_repository->objects,
121 cache_one_alternate, &cache);
122 initialized = 1;
123 }
124
125 for (i = 0; i < cache.nr; i++)
126 cb(negotiator, cache.items[i]);
127 }
128
129 static void die_in_commit_graph_only(const struct object_id *oid)
130 {
131 die(_("You are attempting to fetch %s, which is in the commit graph file but not in the object database.\n"
132 "This is probably due to repo corruption.\n"
133 "If you are attempting to repair this repo corruption by refetching the missing object, use 'git fetch --refetch' with the missing object."),
134 oid_to_hex(oid));
135 }
136
137 static struct commit *deref_without_lazy_fetch(const struct object_id *oid,
138 int mark_tags_complete_and_check_obj_db)
139 {
140 enum object_type type;
141 struct object_info info = { .typep = &type };
142 struct commit *commit;
143
144 commit = lookup_commit_in_graph(the_repository, oid);
145 if (commit) {
146 if (mark_tags_complete_and_check_obj_db) {
147 if (!odb_has_object(the_repository->objects, oid,
148 ODB_HAS_OBJECT_RECHECK_PACKED))
149 die_in_commit_graph_only(oid);
150 }
151 return commit;
152 }
153
154 while (1) {
155 if (odb_read_object_info_extended(the_repository->objects, oid, &info,
156 OBJECT_INFO_SKIP_FETCH_OBJECT | OBJECT_INFO_QUICK))
157 return NULL;
158 if (type == OBJ_TAG) {
159 struct tag *tag = (struct tag *)
160 parse_object(the_repository, oid);
161
162 if (!tag->tagged)
163 return NULL;
164 if (mark_tags_complete_and_check_obj_db)
165 tag->object.flags |= COMPLETE;
166 oid = &tag->tagged->oid;
167 } else {
168 break;
169 }
170 }
171
172 if (type == OBJ_COMMIT) {
173 struct commit *commit = lookup_commit(the_repository, oid);
174 if (!commit || repo_parse_commit(the_repository, commit))
175 return NULL;
176 return commit;
177 }
178
179 return NULL;
180 }
181
182 static int rev_list_insert_ref(struct fetch_negotiator *negotiator,
183 const struct object_id *oid)
184 {
185 struct commit *c = deref_without_lazy_fetch(oid, 0);
186
187 if (c)
188 negotiator->add_tip(negotiator, c);
189 return 0;
190 }
191
192 static int rev_list_insert_ref_oid(const struct reference *ref, void *cb_data)
193 {
194 return rev_list_insert_ref(cb_data, ref->oid);
195 }
196
197 enum ack_type {
198 NAK = 0,
199 ACK,
200 ACK_continue,
201 ACK_common,
202 ACK_ready
203 };
204
205 static void consume_shallow_list(struct fetch_pack_args *args,
206 struct packet_reader *reader)
207 {
208 if (args->stateless_rpc && args->deepen) {
209 /* If we sent a depth we will get back "duplicate"
210 * shallow and unshallow commands every time there
211 * is a block of have lines exchanged.
212 */
213 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
214 if (starts_with(reader->line, "shallow "))
215 continue;
216 if (starts_with(reader->line, "unshallow "))
217 continue;
218 die(_("git fetch-pack: expected shallow list"));
219 }
220 if (reader->status != PACKET_READ_FLUSH)
221 die(_("git fetch-pack: expected a flush packet after shallow list"));
222 }
223 }
224
225 static enum ack_type get_ack(struct packet_reader *reader,
226 struct object_id *result_oid)
227 {
228 int len;
229 const char *arg;
230
231 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
232 die(_("git fetch-pack: expected ACK/NAK, got a flush packet"));
233 len = reader->pktlen;
234
235 if (!strcmp(reader->line, "NAK"))
236 return NAK;
237 if (skip_prefix(reader->line, "ACK ", &arg)) {
238 const char *p;
239 if (!parse_oid_hex(arg, result_oid, &p)) {
240 len -= p - reader->line;
241 if (len < 1)
242 return ACK;
243 if (strstr(p, "continue"))
244 return ACK_continue;
245 if (strstr(p, "common"))
246 return ACK_common;
247 if (strstr(p, "ready"))
248 return ACK_ready;
249 return ACK;
250 }
251 }
252 die(_("git fetch-pack: expected ACK/NAK, got '%s'"), reader->line);
253 }
254
255 static void send_request(struct fetch_pack_args *args,
256 int fd, struct strbuf *buf)
257 {
258 if (args->stateless_rpc) {
259 send_sideband(fd, -1, buf->buf, buf->len, LARGE_PACKET_MAX);
260 packet_flush(fd);
261 } else {
262 if (write_in_full(fd, buf->buf, buf->len) < 0)
263 die_errno(_("unable to write to remote"));
264 }
265 }
266
267 static void insert_one_alternate_object(struct fetch_negotiator *negotiator,
268 struct object *obj)
269 {
270 rev_list_insert_ref(negotiator, &obj->oid);
271 }
272
273 #define INITIAL_FLUSH 16
274 #define PIPESAFE_FLUSH 32
275 #define LARGE_FLUSH 16384
276
277 static int next_flush(int stateless_rpc, int count)
278 {
279 if (stateless_rpc) {
280 if (count < LARGE_FLUSH)
281 count <<= 1;
282 else
283 count = count * 11 / 10;
284 } else {
285 if (count < PIPESAFE_FLUSH)
286 count <<= 1;
287 else
288 count += PIPESAFE_FLUSH;
289 }
290 return count;
291 }
292
293 static void mark_tips(struct fetch_negotiator *negotiator,
294 const struct oid_array *negotiation_restrict_tips)
295 {
296 struct refs_for_each_ref_options opts = {
297 .flags = REFS_FOR_EACH_INCLUDE_BROKEN,
298 };
299 int i;
300
301 if (!negotiation_restrict_tips) {
302 refs_for_each_ref_ext(get_main_ref_store(the_repository),
303 rev_list_insert_ref_oid, negotiator, &opts);
304 return;
305 }
306
307 for (i = 0; i < negotiation_restrict_tips->nr; i++)
308 rev_list_insert_ref(negotiator, &negotiation_restrict_tips->oid[i]);
309 return;
310 }
311
312 static void send_filter(struct fetch_pack_args *args,
313 struct strbuf *req_buf,
314 int server_supports_filter)
315 {
316 if (args->filter_options.choice) {
317 const char *spec =
318 expand_list_objects_filter_spec(&args->filter_options);
319 if (server_supports_filter) {
320 print_verbose(args, _("Server supports filter"));
321 packet_buf_write(req_buf, "filter %s", spec);
322 trace2_data_string("fetch", the_repository,
323 "filter/effective", spec);
324 } else {
325 warning("filtering not recognized by server, ignoring");
326 trace2_data_string("fetch", the_repository,
327 "filter/unsupported", spec);
328 }
329 } else {
330 trace2_data_string("fetch", the_repository,
331 "filter/none", "");
332 }
333 }
334
335 static void add_oids_to_set(const struct oid_array *array,
336 struct oidset *set)
337 {
338 if (!array)
339 return;
340
341 for (size_t i = 0; i < array->nr; i++) {
342 struct object_id *oid = &array->oid[i];
343 if (!odb_has_object(the_repository->objects, oid, 0))
344 die(_("the object %s does not exist"), oid_to_hex(oid));
345
346 oidset_insert(set, oid);
347 }
348 }
349
350 static int find_common(struct fetch_negotiator *negotiator,
351 struct fetch_pack_args *args,
352 int fd[2], struct object_id *result_oid,
353 struct ref *refs)
354 {
355 int fetching;
356 int count = 0, flushes = 0, flush_at = INITIAL_FLUSH, retval;
357 int negotiation_round = 0, haves = 0;
358 const struct object_id *oid;
359 unsigned in_vain = 0;
360 int got_continue = 0;
361 int got_ready = 0;
362 struct strbuf req_buf = STRBUF_INIT;
363 size_t state_len = 0;
364 struct packet_reader reader;
365 struct oidset negotiation_include_oids = OIDSET_INIT;
366
367 if (args->stateless_rpc && multi_ack == 1)
368 die(_("the option '%s' requires '%s'"), "--stateless-rpc", "multi_ack_detailed");
369
370 packet_reader_init(&reader, fd[0], NULL, 0,
371 PACKET_READ_CHOMP_NEWLINE |
372 PACKET_READ_DIE_ON_ERR_PACKET);
373
374 mark_tips(negotiator, args->negotiation_restrict_tips);
375 for_each_cached_alternate(negotiator, insert_one_alternate_object);
376
377 fetching = 0;
378 for ( ; refs ; refs = refs->next) {
379 struct object_id *remote = &refs->old_oid;
380 const char *remote_hex;
381 struct object *o;
382
383 if (!args->refetch) {
384 /*
385 * If that object is complete (i.e. it is an ancestor of a
386 * local ref), we tell them we have it but do not have to
387 * tell them about its ancestors, which they already know
388 * about.
389 *
390 * We use lookup_object here because we are only
391 * interested in the case we *know* the object is
392 * reachable and we have already scanned it.
393 */
394 if (((o = lookup_object(the_repository, remote)) != NULL) &&
395 (o->flags & COMPLETE)) {
396 continue;
397 }
398 }
399
400 remote_hex = oid_to_hex(remote);
401 if (!fetching) {
402 struct strbuf c = STRBUF_INIT;
403 if (multi_ack == 2) strbuf_addstr(&c, " multi_ack_detailed");
404 if (multi_ack == 1) strbuf_addstr(&c, " multi_ack");
405 if (no_done) strbuf_addstr(&c, " no-done");
406 if (use_sideband == 2) strbuf_addstr(&c, " side-band-64k");
407 if (use_sideband == 1) strbuf_addstr(&c, " side-band");
408 if (args->deepen_relative) strbuf_addstr(&c, " deepen-relative");
409 if (args->use_thin_pack) strbuf_addstr(&c, " thin-pack");
410 if (args->no_progress) strbuf_addstr(&c, " no-progress");
411 if (args->include_tag) strbuf_addstr(&c, " include-tag");
412 if (prefer_ofs_delta) strbuf_addstr(&c, " ofs-delta");
413 if (deepen_since_ok) strbuf_addstr(&c, " deepen-since");
414 if (deepen_not_ok) strbuf_addstr(&c, " deepen-not");
415 if (agent_supported) strbuf_addf(&c, " agent=%s",
416 git_user_agent_sanitized());
417 if (advertise_sid)
418 strbuf_addf(&c, " session-id=%s", trace2_session_id());
419 if (args->filter_options.choice)
420 strbuf_addstr(&c, " filter");
421 packet_buf_write(&req_buf, "want %s%s\n", remote_hex, c.buf);
422 strbuf_release(&c);
423 } else
424 packet_buf_write(&req_buf, "want %s\n", remote_hex);
425 fetching++;
426 }
427
428 if (!fetching) {
429 strbuf_release(&req_buf);
430 packet_flush(fd[1]);
431 return 1;
432 }
433
434 if (is_repository_shallow(the_repository))
435 write_shallow_commits(&req_buf, 1, NULL);
436 if (args->depth > 0)
437 packet_buf_write(&req_buf, "deepen %d", args->depth);
438 if (args->deepen_since) {
439 timestamp_t max_age = approxidate(args->deepen_since);
440 packet_buf_write(&req_buf, "deepen-since %"PRItime, max_age);
441 }
442 if (args->deepen_not) {
443 int i;
444 for (i = 0; i < args->deepen_not->nr; i++) {
445 struct string_list_item *s = args->deepen_not->items + i;
446 packet_buf_write(&req_buf, "deepen-not %s", s->string);
447 }
448 }
449 send_filter(args, &req_buf, server_supports_filtering);
450 packet_buf_flush(&req_buf);
451 state_len = req_buf.len;
452
453 if (args->deepen) {
454 const char *arg;
455 struct object_id oid;
456
457 send_request(args, fd[1], &req_buf);
458 while (packet_reader_read(&reader) == PACKET_READ_NORMAL) {
459 if (skip_prefix(reader.line, "shallow ", &arg)) {
460 if (get_oid_hex(arg, &oid))
461 die(_("invalid shallow line: %s"), reader.line);
462 register_shallow(the_repository, &oid);
463 continue;
464 }
465 if (skip_prefix(reader.line, "unshallow ", &arg)) {
466 if (get_oid_hex(arg, &oid))
467 die(_("invalid unshallow line: %s"), reader.line);
468 if (!lookup_object(the_repository, &oid))
469 die(_("object not found: %s"), reader.line);
470 /* make sure that it is parsed as shallow */
471 if (!parse_object(the_repository, &oid))
472 die(_("error in object: %s"), reader.line);
473 if (unregister_shallow(&oid))
474 die(_("no shallow found: %s"), reader.line);
475 continue;
476 }
477 die(_("expected shallow/unshallow, got %s"), reader.line);
478 }
479 } else if (!args->stateless_rpc)
480 send_request(args, fd[1], &req_buf);
481
482 if (!args->stateless_rpc) {
483 /* If we aren't using the stateless-rpc interface
484 * we don't need to retain the headers.
485 */
486 strbuf_setlen(&req_buf, 0);
487 state_len = 0;
488 }
489
490 trace2_region_enter("fetch-pack", "negotiation_v0_v1", the_repository);
491 flushes = 0;
492 retval = -1;
493
494 /* Send unconditional haves from --negotiation-include */
495 add_oids_to_set(args->negotiation_include_tips,
496 &negotiation_include_oids);
497 if (oidset_size(&negotiation_include_oids)) {
498 struct oidset_iter iter;
499 oidset_iter_init(&negotiation_include_oids, &iter);
500
501 while ((oid = oidset_iter_next(&iter))) {
502 struct commit *commit;
503 packet_buf_write(&req_buf, "have %s\n",
504 oid_to_hex(oid));
505 print_verbose(args, "have %s", oid_to_hex(oid));
506 count++;
507
508 commit = lookup_commit(the_repository, oid);
509 if (commit)
510 negotiator->have_sent(negotiator, commit);
511 }
512 }
513
514 while ((oid = negotiator->next(negotiator))) {
515 packet_buf_write(&req_buf, "have %s\n", oid_to_hex(oid));
516 print_verbose(args, "have %s", oid_to_hex(oid));
517 in_vain++;
518 haves++;
519 if (flush_at <= ++count) {
520 int ack;
521
522 negotiation_round++;
523 trace2_region_enter_printf("negotiation_v0_v1", "round",
524 the_repository, "%d",
525 negotiation_round);
526 trace2_data_intmax("negotiation_v0_v1", the_repository,
527 "haves_added", haves);
528 trace2_data_intmax("negotiation_v0_v1", the_repository,
529 "in_vain", in_vain);
530 haves = 0;
531 packet_buf_flush(&req_buf);
532 send_request(args, fd[1], &req_buf);
533 strbuf_setlen(&req_buf, state_len);
534 flushes++;
535 flush_at = next_flush(args->stateless_rpc, count);
536
537 /*
538 * We keep one window "ahead" of the other side, and
539 * will wait for an ACK only on the next one
540 */
541 if (!args->stateless_rpc && count == INITIAL_FLUSH)
542 continue;
543
544 consume_shallow_list(args, &reader);
545 do {
546 ack = get_ack(&reader, result_oid);
547 if (ack)
548 print_verbose(args, _("got %s %d %s"), "ack",
549 ack, oid_to_hex(result_oid));
550 switch (ack) {
551 case ACK:
552 trace2_region_leave_printf("negotiation_v0_v1", "round",
553 the_repository, "%d",
554 negotiation_round);
555 flushes = 0;
556 multi_ack = 0;
557 retval = 0;
558 goto done;
559 case ACK_common:
560 case ACK_ready:
561 case ACK_continue: {
562 struct commit *commit =
563 lookup_commit(the_repository,
564 result_oid);
565 int was_common;
566
567 if (!commit)
568 die(_("invalid commit %s"), oid_to_hex(result_oid));
569 was_common = negotiator->ack(negotiator, commit);
570 if (args->stateless_rpc
571 && ack == ACK_common
572 && !was_common) {
573 /* We need to replay the have for this object
574 * on the next RPC request so the peer knows
575 * it is in common with us.
576 */
577 const char *hex = oid_to_hex(result_oid);
578 packet_buf_write(&req_buf, "have %s\n", hex);
579 state_len = req_buf.len;
580 haves++;
581 /*
582 * Reset in_vain because an ack
583 * for this commit has not been
584 * seen.
585 */
586 in_vain = 0;
587 } else if (!args->stateless_rpc
588 || ack != ACK_common)
589 in_vain = 0;
590 retval = 0;
591 got_continue = 1;
592 if (ack == ACK_ready)
593 got_ready = 1;
594 break;
595 }
596 }
597 } while (ack);
598 flushes--;
599 trace2_region_leave_printf("negotiation_v0_v1", "round",
600 the_repository, "%d",
601 negotiation_round);
602 if (got_continue && MAX_IN_VAIN < in_vain) {
603 print_verbose(args, _("giving up"));
604 break; /* give up */
605 }
606 if (got_ready)
607 break;
608 }
609 }
610 done:
611 trace2_region_leave("fetch-pack", "negotiation_v0_v1", the_repository);
612 trace2_data_intmax("negotiation_v0_v1", the_repository, "total_rounds",
613 negotiation_round);
614 if (!got_ready || !no_done) {
615 packet_buf_write(&req_buf, "done\n");
616 send_request(args, fd[1], &req_buf);
617 }
618 print_verbose(args, _("done"));
619 if (retval != 0) {
620 multi_ack = 0;
621 flushes++;
622 }
623 strbuf_release(&req_buf);
624 oidset_clear(&negotiation_include_oids);
625
626 if (!got_ready || !no_done)
627 consume_shallow_list(args, &reader);
628 while (flushes || multi_ack) {
629 int ack = get_ack(&reader, result_oid);
630 if (ack) {
631 print_verbose(args, _("got %s (%d) %s"), "ack",
632 ack, oid_to_hex(result_oid));
633 if (ack == ACK)
634 return 0;
635 multi_ack = 1;
636 continue;
637 }
638 flushes--;
639 }
640 /* it is no error to fetch into a completely empty repo */
641 return count ? retval : 0;
642 }
643
644 static struct prio_queue complete = { compare_commits_by_commit_date };
645
646 static int mark_complete(const struct object_id *oid)
647 {
648 struct commit *commit = deref_without_lazy_fetch(oid, 1);
649
650 if (commit && !(commit->object.flags & COMPLETE)) {
651 commit->object.flags |= COMPLETE;
652 prio_queue_put(&complete, commit);
653 }
654 return 0;
655 }
656
657 static int mark_complete_oid(const struct reference *ref, void *cb_data UNUSED)
658 {
659 return mark_complete(ref->oid);
660 }
661
662 static void mark_recent_complete_commits(struct fetch_pack_args *args,
663 timestamp_t cutoff)
664 {
665 while (complete.nr) {
666 struct commit *item = prio_queue_peek(&complete);
667 if (item->date < cutoff)
668 break;
669 print_verbose(args, _("Marking %s as complete"),
670 oid_to_hex(&item->object.oid));
671 pop_most_recent_commit(&complete, COMPLETE);
672 }
673 }
674
675 static void add_refs_to_oidset(struct oidset *oids, struct ref *refs)
676 {
677 for (; refs; refs = refs->next)
678 oidset_insert(oids, &refs->old_oid);
679 }
680
681 static int is_unmatched_ref(const struct ref *ref)
682 {
683 struct object_id oid;
684 const char *p;
685 return ref->match_status == REF_NOT_MATCHED &&
686 !parse_oid_hex(ref->name, &oid, &p) &&
687 *p == '\0' &&
688 oideq(&oid, &ref->old_oid);
689 }
690
691 static void filter_refs(struct fetch_pack_args *args,
692 struct ref **refs,
693 struct ref **sought, int nr_sought)
694 {
695 struct ref *newlist = NULL;
696 struct ref **newtail = &newlist;
697 struct ref *unmatched = NULL;
698 struct ref *ref, *next;
699 struct oidset tip_oids = OIDSET_INIT;
700 int i;
701 int strict = !(allow_unadvertised_object_request &
702 (ALLOW_TIP_SHA1 | ALLOW_REACHABLE_SHA1));
703
704 i = 0;
705 for (ref = *refs; ref; ref = next) {
706 int keep = 0;
707 next = ref->next;
708
709 if (starts_with(ref->name, "refs/") &&
710 check_refname_format(ref->name, 0)) {
711 /*
712 * trash or a peeled value; do not even add it to
713 * unmatched list
714 */
715 free_one_ref(ref);
716 continue;
717 } else {
718 while (i < nr_sought) {
719 int cmp = strcmp(ref->name, sought[i]->name);
720 if (cmp < 0)
721 break; /* definitely do not have it */
722 else if (cmp == 0) {
723 keep = 1; /* definitely have it */
724 sought[i]->match_status = REF_MATCHED;
725 }
726 i++;
727 }
728
729 if (!keep && args->fetch_all &&
730 (!args->deepen || !starts_with(ref->name, "refs/tags/")))
731 keep = 1;
732 }
733
734 if (keep) {
735 *newtail = ref;
736 ref->next = NULL;
737 newtail = &ref->next;
738 } else {
739 ref->next = unmatched;
740 unmatched = ref;
741 }
742 }
743
744 if (strict) {
745 for (i = 0; i < nr_sought; i++) {
746 ref = sought[i];
747 if (!is_unmatched_ref(ref))
748 continue;
749
750 add_refs_to_oidset(&tip_oids, unmatched);
751 add_refs_to_oidset(&tip_oids, newlist);
752 break;
753 }
754 }
755
756 /* Append unmatched requests to the list */
757 for (i = 0; i < nr_sought; i++) {
758 ref = sought[i];
759 if (!is_unmatched_ref(ref))
760 continue;
761
762 if (!strict || oidset_contains(&tip_oids, &ref->old_oid)) {
763 ref->match_status = REF_MATCHED;
764 *newtail = copy_ref(ref);
765 newtail = &(*newtail)->next;
766 } else {
767 ref->match_status = REF_UNADVERTISED_NOT_ALLOWED;
768 }
769 }
770
771 oidset_clear(&tip_oids);
772 free_refs(unmatched);
773
774 *refs = newlist;
775 }
776
777 static void mark_alternate_complete(struct fetch_negotiator *negotiator UNUSED,
778 struct object *obj)
779 {
780 mark_complete(&obj->oid);
781 }
782
783 /*
784 * Mark recent commits available locally and reachable from a local ref as
785 * COMPLETE.
786 *
787 * The cutoff time for recency is determined by this heuristic: it is the
788 * earliest commit time of the objects in refs that are commits and that we know
789 * the commit time of.
790 */
791 static void mark_complete_and_common_ref(struct fetch_negotiator *negotiator,
792 struct fetch_pack_args *args,
793 struct ref **refs)
794 {
795 struct ref *ref;
796 int old_save_commit_buffer = save_commit_buffer;
797 timestamp_t cutoff = 0;
798
799 if (args->refetch)
800 return;
801
802 save_commit_buffer = 0;
803
804 trace2_region_enter("fetch-pack", "parse_remote_refs_and_find_cutoff", NULL);
805 for (ref = *refs; ref; ref = ref->next) {
806 struct commit *commit;
807
808 commit = lookup_commit_in_graph(the_repository, &ref->old_oid);
809 if (!commit) {
810 struct object *o;
811
812 if (!odb_has_object(the_repository->objects, &ref->old_oid, 0))
813 continue;
814 o = parse_object(the_repository, &ref->old_oid);
815 if (!o || o->type != OBJ_COMMIT)
816 continue;
817
818 commit = (struct commit *)o;
819 }
820
821 /*
822 * We already have it -- which may mean that we were
823 * in sync with the other side at some time after
824 * that (it is OK if we guess wrong here).
825 */
826 if (!cutoff || cutoff < commit->date)
827 cutoff = commit->date;
828 }
829 trace2_region_leave("fetch-pack", "parse_remote_refs_and_find_cutoff", NULL);
830
831 /*
832 * This block marks all local refs as COMPLETE, and then recursively marks all
833 * parents of those refs as COMPLETE.
834 */
835 trace2_region_enter("fetch-pack", "mark_complete_local_refs", NULL);
836 if (!args->deepen) {
837 struct refs_for_each_ref_options opts = {
838 .flags = REFS_FOR_EACH_INCLUDE_BROKEN,
839 };
840
841 refs_for_each_ref_ext(get_main_ref_store(the_repository),
842 mark_complete_oid, NULL, &opts);
843 for_each_cached_alternate(NULL, mark_alternate_complete);
844 if (cutoff)
845 mark_recent_complete_commits(args, cutoff);
846 }
847 trace2_region_leave("fetch-pack", "mark_complete_local_refs", NULL);
848
849 /*
850 * Mark all complete remote refs as common refs.
851 * Don't mark them common yet; the server has to be told so first.
852 */
853 trace2_region_enter("fetch-pack", "mark_common_remote_refs", NULL);
854 for (ref = *refs; ref; ref = ref->next) {
855 struct commit *c = deref_without_lazy_fetch(&ref->old_oid, 0);
856
857 if (!c || !(c->object.flags & COMPLETE))
858 continue;
859
860 negotiator->known_common(negotiator, c);
861 }
862 trace2_region_leave("fetch-pack", "mark_common_remote_refs", NULL);
863
864 save_commit_buffer = old_save_commit_buffer;
865 }
866
867 /*
868 * Returns 1 if every object pointed to by the given remote refs is available
869 * locally and reachable from a local ref, and 0 otherwise.
870 */
871 static int everything_local(struct fetch_pack_args *args,
872 struct ref **refs)
873 {
874 struct ref *ref;
875 int retval;
876
877 for (retval = 1, ref = *refs; ref ; ref = ref->next) {
878 const struct object_id *remote = &ref->old_oid;
879 struct object *o;
880
881 o = lookup_object(the_repository, remote);
882 if (!o || !(o->flags & COMPLETE)) {
883 retval = 0;
884 print_verbose(args, "want %s (%s)", oid_to_hex(remote),
885 ref->name);
886 continue;
887 }
888 print_verbose(args, _("already have %s (%s)"), oid_to_hex(remote),
889 ref->name);
890 }
891
892 return retval;
893 }
894
895 static int sideband_demux(int in UNUSED, int out, void *data)
896 {
897 int *xd = data;
898 int ret;
899
900 ret = recv_sideband("fetch-pack", xd[0], out);
901 close(out);
902 return ret;
903 }
904
905 static void create_promisor_file(const char *keep_name,
906 struct ref **sought, int nr_sought)
907 {
908 struct strbuf promisor_name = STRBUF_INIT;
909 int suffix_stripped;
910
911 strbuf_addstr(&promisor_name, keep_name);
912 suffix_stripped = strbuf_strip_suffix(&promisor_name, ".keep");
913 if (!suffix_stripped)
914 BUG("name of pack lockfile should end with .keep (was '%s')",
915 keep_name);
916 strbuf_addstr(&promisor_name, ".promisor");
917
918 write_promisor_file(promisor_name.buf, sought, nr_sought);
919
920 strbuf_release(&promisor_name);
921 }
922
923 static void parse_gitmodules_oids(int fd, struct oidset *gitmodules_oids)
924 {
925 int len = the_hash_algo->hexsz + 1; /* hash + NL */
926
927 do {
928 char hex_hash[GIT_MAX_HEXSZ + 1];
929 int read_len = read_in_full(fd, hex_hash, len);
930 struct object_id oid;
931 const char *end;
932
933 if (!read_len)
934 return;
935 if (read_len != len)
936 die("invalid length read %d", read_len);
937 if (parse_oid_hex(hex_hash, &oid, &end) || *end != '\n')
938 die("invalid hash");
939 oidset_insert(gitmodules_oids, &oid);
940 } while (1);
941 }
942
943 static void add_index_pack_keep_option(struct strvec *args)
944 {
945 char hostname[HOST_NAME_MAX + 1];
946
947 if (xgethostname(hostname, sizeof(hostname)))
948 xsnprintf(hostname, sizeof(hostname), "localhost");
949 strvec_pushf(args, "--keep=fetch-pack %"PRIuMAX " on %s",
950 (uintmax_t)getpid(), hostname);
951 }
952
953 /*
954 * If packfile URIs were provided, pass a non-NULL pointer to index_pack_args.
955 * The strings to pass as the --index-pack-arg arguments to http-fetch will be
956 * stored there. (It must be freed by the caller.)
957 */
958 static int get_pack(struct fetch_pack_args *args,
959 int xd[2], struct string_list *pack_lockfiles,
960 struct strvec *index_pack_args,
961 struct ref **sought, int nr_sought,
962 struct oidset *gitmodules_oids)
963 {
964 struct async demux;
965 int do_keep = args->keep_pack;
966 const char *cmd_name;
967 struct pack_header header;
968 int pass_header = 0;
969 struct child_process cmd = CHILD_PROCESS_INIT;
970 int fsck_objects = 0;
971 int ret;
972
973 memset(&demux, 0, sizeof(demux));
974 if (use_sideband) {
975 /* xd[] is talking with upload-pack; subprocess reads from
976 * xd[0], spits out band#2 to stderr, and feeds us band#1
977 * through demux->out.
978 */
979 demux.proc = sideband_demux;
980 demux.data = xd;
981 demux.out = -1;
982 demux.isolate_sigpipe = 1;
983 if (start_async(&demux))
984 die(_("fetch-pack: unable to fork off sideband demultiplexer"));
985 }
986 else
987 demux.out = xd[0];
988
989 if (!args->keep_pack && unpack_limit && !index_pack_args) {
990
991 if (read_pack_header(demux.out, &header))
992 die(_("protocol error: bad pack header"));
993 pass_header = 1;
994 if (ntohl(header.hdr_entries) < unpack_limit)
995 do_keep = 0;
996 else
997 do_keep = 1;
998 }
999
1000 if (alternate_shallow_file) {
1001 strvec_push(&cmd.args, "--shallow-file");
1002 strvec_push(&cmd.args, alternate_shallow_file);
1003 }
1004
1005 fsck_objects = fetch_pack_fsck_objects();
1006
1007 if (do_keep || args->from_promisor || index_pack_args || fsck_objects) {
1008 if (pack_lockfiles || fsck_objects)
1009 cmd.out = -1;
1010 cmd_name = "index-pack";
1011 strvec_push(&cmd.args, cmd_name);
1012 strvec_push(&cmd.args, "--stdin");
1013 if (!args->quiet && !args->no_progress)
1014 strvec_push(&cmd.args, "-v");
1015 if (args->use_thin_pack)
1016 strvec_push(&cmd.args, "--fix-thin");
1017 if ((do_keep || index_pack_args) && (args->lock_pack || unpack_limit))
1018 add_index_pack_keep_option(&cmd.args);
1019 if (!index_pack_args && args->check_self_contained_and_connected)
1020 strvec_push(&cmd.args, "--check-self-contained-and-connected");
1021 else
1022 /*
1023 * We cannot perform any connectivity checks because
1024 * not all packs have been downloaded; let the caller
1025 * have this responsibility.
1026 */
1027 args->check_self_contained_and_connected = 0;
1028
1029 if (args->from_promisor)
1030 /*
1031 * create_promisor_file() may be called afterwards but
1032 * we still need index-pack to know that this is a
1033 * promisor pack. For example, if transfer.fsckobjects
1034 * is true, index-pack needs to know that .gitmodules
1035 * is a promisor object (so that it won't complain if
1036 * it is missing).
1037 */
1038 strvec_push(&cmd.args, "--promisor");
1039 }
1040 else {
1041 cmd_name = "unpack-objects";
1042 strvec_push(&cmd.args, cmd_name);
1043 if (args->quiet || args->no_progress)
1044 strvec_push(&cmd.args, "-q");
1045 args->check_self_contained_and_connected = 0;
1046 }
1047
1048 if (pass_header)
1049 strvec_pushf(&cmd.args, "--pack_header=%"PRIu32",%"PRIu32,
1050 ntohl(header.hdr_version),
1051 ntohl(header.hdr_entries));
1052 if (fsck_objects) {
1053 if (args->from_promisor || index_pack_args)
1054 /*
1055 * We cannot use --strict in index-pack because it
1056 * checks both broken objects and links, but we only
1057 * want to check for broken objects.
1058 */
1059 strvec_push(&cmd.args, "--fsck-objects");
1060 else
1061 strvec_pushf(&cmd.args, "--strict%s",
1062 fsck_msg_types.buf);
1063 }
1064
1065 if (index_pack_args)
1066 strvec_pushv(index_pack_args, cmd.args.v);
1067
1068 sigchain_push(SIGPIPE, SIG_IGN);
1069
1070 cmd.in = demux.out;
1071 cmd.git_cmd = 1;
1072 if (start_command(&cmd))
1073 die(_("fetch-pack: unable to fork off %s"), cmd_name);
1074 if (do_keep && (pack_lockfiles || fsck_objects)) {
1075 int is_well_formed;
1076 char *pack_lockfile = index_pack_lockfile(the_repository,
1077 cmd.out,
1078 &is_well_formed);
1079
1080 if (!is_well_formed)
1081 die(_("fetch-pack: invalid index-pack output"));
1082 if (pack_lockfiles && pack_lockfile)
1083 string_list_append_nodup(pack_lockfiles, pack_lockfile);
1084 else
1085 free(pack_lockfile);
1086 parse_gitmodules_oids(cmd.out, gitmodules_oids);
1087 close(cmd.out);
1088 }
1089
1090 if (!use_sideband)
1091 /* Closed by start_command() */
1092 xd[0] = -1;
1093
1094 ret = finish_command(&cmd);
1095 if (!ret || (args->check_self_contained_and_connected && ret == 1))
1096 args->self_contained_and_connected =
1097 args->check_self_contained_and_connected &&
1098 ret == 0;
1099 else
1100 die(_("%s failed"), cmd_name);
1101 if (use_sideband && finish_async(&demux))
1102 die(_("error in sideband demultiplexer"));
1103
1104 sigchain_pop(SIGPIPE);
1105
1106 /*
1107 * Now that index-pack has succeeded, write the promisor file using the
1108 * obtained .keep filename if necessary
1109 */
1110 if (do_keep && pack_lockfiles && pack_lockfiles->nr && args->from_promisor)
1111 create_promisor_file(pack_lockfiles->items[0].string, sought, nr_sought);
1112
1113 return 0;
1114 }
1115
1116 static int ref_compare_name(const struct ref *a, const struct ref *b)
1117 {
1118 return strcmp(a->name, b->name);
1119 }
1120
1121 DEFINE_LIST_SORT(static, sort_ref_list, struct ref, next);
1122
1123 static int cmp_ref_by_name(const void *a_, const void *b_)
1124 {
1125 const struct ref *a = *((const struct ref **)a_);
1126 const struct ref *b = *((const struct ref **)b_);
1127 return strcmp(a->name, b->name);
1128 }
1129
1130 static struct ref *do_fetch_pack(struct fetch_pack_args *args,
1131 int fd[2],
1132 const struct ref *orig_ref,
1133 struct ref **sought, int nr_sought,
1134 struct shallow_info *si,
1135 struct string_list *pack_lockfiles)
1136 {
1137 struct fsck_options fsck_options = { 0 };
1138 struct repository *r = the_repository;
1139 struct ref *ref = copy_ref_list(orig_ref);
1140 struct object_id oid;
1141 const char *agent_feature;
1142 size_t agent_len;
1143 struct fetch_negotiator negotiator_alloc;
1144 struct fetch_negotiator *negotiator;
1145
1146 negotiator = &negotiator_alloc;
1147 if (args->refetch) {
1148 fetch_negotiator_init_noop(negotiator);
1149 } else {
1150 fetch_negotiator_init(r, negotiator);
1151 }
1152
1153 sort_ref_list(&ref, ref_compare_name);
1154 QSORT(sought, nr_sought, cmp_ref_by_name);
1155
1156 if ((agent_feature = server_feature_value("agent", &agent_len))) {
1157 agent_supported = 1;
1158 if (agent_len)
1159 print_verbose(args, _("Server version is %.*s"),
1160 (int)agent_len, agent_feature);
1161 }
1162
1163 if (!server_supports("session-id"))
1164 advertise_sid = 0;
1165
1166 if (server_supports("shallow"))
1167 print_verbose(args, _("Server supports %s"), "shallow");
1168 else if (args->depth > 0 || is_repository_shallow(r))
1169 die(_("Server does not support shallow clients"));
1170 if (args->depth > 0 || args->deepen_since || args->deepen_not)
1171 args->deepen = 1;
1172 if (server_supports("multi_ack_detailed")) {
1173 print_verbose(args, _("Server supports %s"), "multi_ack_detailed");
1174 multi_ack = 2;
1175 if (server_supports("no-done")) {
1176 print_verbose(args, _("Server supports %s"), "no-done");
1177 if (args->stateless_rpc)
1178 no_done = 1;
1179 }
1180 }
1181 else if (server_supports("multi_ack")) {
1182 print_verbose(args, _("Server supports %s"), "multi_ack");
1183 multi_ack = 1;
1184 }
1185 if (server_supports("side-band-64k")) {
1186 print_verbose(args, _("Server supports %s"), "side-band-64k");
1187 use_sideband = 2;
1188 }
1189 else if (server_supports("side-band")) {
1190 print_verbose(args, _("Server supports %s"), "side-band");
1191 use_sideband = 1;
1192 }
1193 if (server_supports("allow-tip-sha1-in-want")) {
1194 print_verbose(args, _("Server supports %s"), "allow-tip-sha1-in-want");
1195 allow_unadvertised_object_request |= ALLOW_TIP_SHA1;
1196 }
1197 if (server_supports("allow-reachable-sha1-in-want")) {
1198 print_verbose(args, _("Server supports %s"), "allow-reachable-sha1-in-want");
1199 allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
1200 }
1201 if (server_supports("thin-pack"))
1202 print_verbose(args, _("Server supports %s"), "thin-pack");
1203 else
1204 args->use_thin_pack = 0;
1205 if (server_supports("no-progress"))
1206 print_verbose(args, _("Server supports %s"), "no-progress");
1207 else
1208 args->no_progress = 0;
1209 if (server_supports("include-tag"))
1210 print_verbose(args, _("Server supports %s"), "include-tag");
1211 else
1212 args->include_tag = 0;
1213 if (server_supports("ofs-delta"))
1214 print_verbose(args, _("Server supports %s"), "ofs-delta");
1215 else
1216 prefer_ofs_delta = 0;
1217
1218 if (server_supports("filter")) {
1219 server_supports_filtering = 1;
1220 print_verbose(args, _("Server supports %s"), "filter");
1221 } else if (args->filter_options.choice) {
1222 warning("filtering not recognized by server, ignoring");
1223 }
1224
1225 if (server_supports("deepen-since")) {
1226 print_verbose(args, _("Server supports %s"), "deepen-since");
1227 deepen_since_ok = 1;
1228 } else if (args->deepen_since)
1229 die(_("Server does not support --shallow-since"));
1230 if (server_supports("deepen-not")) {
1231 print_verbose(args, _("Server supports %s"), "deepen-not");
1232 deepen_not_ok = 1;
1233 } else if (args->deepen_not)
1234 die(_("Server does not support --shallow-exclude"));
1235 if (server_supports("deepen-relative"))
1236 print_verbose(args, _("Server supports %s"), "deepen-relative");
1237 else if (args->deepen_relative)
1238 die(_("Server does not support --deepen"));
1239 if (!server_supports_hash(the_hash_algo->name, NULL))
1240 die(_("Server does not support this repository's object format"));
1241
1242 mark_complete_and_common_ref(negotiator, args, &ref);
1243 filter_refs(args, &ref, sought, nr_sought);
1244 if (!args->refetch && everything_local(args, &ref)) {
1245 packet_flush(fd[1]);
1246 goto all_done;
1247 }
1248 if (find_common(negotiator, args, fd, &oid, ref) < 0)
1249 if (!args->keep_pack)
1250 /* When cloning, it is not unusual to have
1251 * no common commit.
1252 */
1253 warning(_("no common commits"));
1254
1255 if (args->stateless_rpc)
1256 packet_flush(fd[1]);
1257 if (args->deepen)
1258 setup_alternate_shallow(&shallow_lock, &alternate_shallow_file,
1259 NULL);
1260 else if (si->nr_ours || si->nr_theirs) {
1261 if (args->reject_shallow_remote)
1262 die(_("source repository is shallow, reject to clone."));
1263 alternate_shallow_file = setup_temporary_shallow(si->shallow);
1264 } else
1265 alternate_shallow_file = NULL;
1266
1267 fsck_options_init(&fsck_options, the_repository, FSCK_OPTIONS_MISSING_GITMODULES);
1268 if (get_pack(args, fd, pack_lockfiles, NULL, sought, nr_sought,
1269 &fsck_options.gitmodules_found))
1270 die(_("git fetch-pack: fetch failed."));
1271 if (fsck_finish(&fsck_options))
1272 die("fsck failed");
1273
1274 all_done:
1275 fsck_options_clear(&fsck_options);
1276 if (negotiator)
1277 negotiator->release(negotiator);
1278 return ref;
1279 }
1280
1281 static void add_shallow_requests(struct strbuf *req_buf,
1282 const struct fetch_pack_args *args)
1283 {
1284 if (is_repository_shallow(the_repository))
1285 write_shallow_commits(req_buf, 1, NULL);
1286 if (args->depth > 0)
1287 packet_buf_write(req_buf, "deepen %d", args->depth);
1288 if (args->deepen_since) {
1289 timestamp_t max_age = approxidate(args->deepen_since);
1290 packet_buf_write(req_buf, "deepen-since %"PRItime, max_age);
1291 }
1292 if (args->deepen_not) {
1293 int i;
1294 for (i = 0; i < args->deepen_not->nr; i++) {
1295 struct string_list_item *s = args->deepen_not->items + i;
1296 packet_buf_write(req_buf, "deepen-not %s", s->string);
1297 }
1298 }
1299 if (args->deepen_relative)
1300 packet_buf_write(req_buf, "deepen-relative\n");
1301 }
1302
1303 static void add_wants(const struct ref *wants, struct strbuf *req_buf)
1304 {
1305 int use_ref_in_want = server_supports_feature("fetch", "ref-in-want", 0);
1306
1307 for ( ; wants ; wants = wants->next) {
1308 const struct object_id *remote = &wants->old_oid;
1309 struct object *o;
1310
1311 /*
1312 * If that object is complete (i.e. it is an ancestor of a
1313 * local ref), we tell them we have it but do not have to
1314 * tell them about its ancestors, which they already know
1315 * about.
1316 *
1317 * We use lookup_object here because we are only
1318 * interested in the case we *know* the object is
1319 * reachable and we have already scanned it.
1320 */
1321 if (((o = lookup_object(the_repository, remote)) != NULL) &&
1322 (o->flags & COMPLETE)) {
1323 continue;
1324 }
1325
1326 if (!use_ref_in_want || wants->exact_oid)
1327 packet_buf_write(req_buf, "want %s\n", oid_to_hex(remote));
1328 else
1329 packet_buf_write(req_buf, "want-ref %s\n", wants->name);
1330 }
1331 }
1332
1333 static void add_common(struct strbuf *req_buf, struct oidset *common)
1334 {
1335 struct oidset_iter iter;
1336 const struct object_id *oid;
1337 oidset_iter_init(common, &iter);
1338
1339 while ((oid = oidset_iter_next(&iter))) {
1340 packet_buf_write(req_buf, "have %s\n", oid_to_hex(oid));
1341 }
1342 }
1343
1344 static int add_haves(struct fetch_negotiator *negotiator,
1345 struct strbuf *req_buf,
1346 int *haves_to_send,
1347 struct oidset *negotiation_include_oids)
1348 {
1349 int haves_added = 0;
1350 const struct object_id *oid;
1351
1352 /* Send unconditional haves from --negotiation-include */
1353 if (negotiation_include_oids) {
1354 struct oidset_iter iter;
1355 oidset_iter_init(negotiation_include_oids, &iter);
1356
1357 while ((oid = oidset_iter_next(&iter))) {
1358 struct commit *commit = lookup_commit(the_repository, oid);
1359 if (commit) {
1360 packet_buf_write(req_buf, "have %s\n",
1361 oid_to_hex(oid));
1362 negotiator->have_sent(negotiator, commit);
1363 }
1364 }
1365 }
1366
1367 while ((oid = negotiator->next(negotiator))) {
1368 packet_buf_write(req_buf, "have %s\n", oid_to_hex(oid));
1369 if (++haves_added >= *haves_to_send)
1370 break;
1371 }
1372
1373 /* Increase haves to send on next round */
1374 *haves_to_send = next_flush(1, *haves_to_send);
1375
1376 return haves_added;
1377 }
1378
1379 static void write_fetch_command_and_capabilities(struct strbuf *req_buf,
1380 const struct string_list *server_options)
1381 {
1382 const char *hash_name;
1383
1384 ensure_server_supports_v2("fetch");
1385 packet_buf_write(req_buf, "command=fetch");
1386 if (server_supports_v2("agent"))
1387 packet_buf_write(req_buf, "agent=%s", git_user_agent_sanitized());
1388 if (advertise_sid && server_supports_v2("session-id"))
1389 packet_buf_write(req_buf, "session-id=%s", trace2_session_id());
1390 if (server_options && server_options->nr) {
1391 int i;
1392 ensure_server_supports_v2("server-option");
1393 for (i = 0; i < server_options->nr; i++)
1394 packet_buf_write(req_buf, "server-option=%s",
1395 server_options->items[i].string);
1396 }
1397
1398 if (server_feature_v2("object-format", &hash_name)) {
1399 int hash_algo = hash_algo_by_name(hash_name);
1400 if (hash_algo_by_ptr(the_hash_algo) != hash_algo)
1401 die(_("mismatched algorithms: client %s; server %s"),
1402 the_hash_algo->name, hash_name);
1403 packet_buf_write(req_buf, "object-format=%s", the_hash_algo->name);
1404 } else if (hash_algo_by_ptr(the_hash_algo) != GIT_HASH_SHA1_LEGACY) {
1405 die(_("the server does not support algorithm '%s'"),
1406 the_hash_algo->name);
1407 }
1408 packet_buf_delim(req_buf);
1409 }
1410
1411 static int send_fetch_request(struct fetch_negotiator *negotiator, int fd_out,
1412 struct fetch_pack_args *args,
1413 const struct ref *wants, struct oidset *common,
1414 int *haves_to_send, int *in_vain,
1415 int sideband_all, int seen_ack,
1416 struct oidset *negotiation_include_oids)
1417 {
1418 int haves_added;
1419 int done_sent = 0;
1420 struct strbuf req_buf = STRBUF_INIT;
1421
1422 write_fetch_command_and_capabilities(&req_buf, args->server_options);
1423
1424 if (args->use_thin_pack)
1425 packet_buf_write(&req_buf, "thin-pack");
1426 if (args->no_progress)
1427 packet_buf_write(&req_buf, "no-progress");
1428 if (args->include_tag)
1429 packet_buf_write(&req_buf, "include-tag");
1430 if (prefer_ofs_delta)
1431 packet_buf_write(&req_buf, "ofs-delta");
1432 if (sideband_all)
1433 packet_buf_write(&req_buf, "sideband-all");
1434
1435 /* Add shallow-info and deepen request */
1436 if (server_supports_feature("fetch", "shallow", 0))
1437 add_shallow_requests(&req_buf, args);
1438 else if (is_repository_shallow(the_repository) || args->deepen)
1439 die(_("Server does not support shallow requests"));
1440
1441 /* Add filter */
1442 send_filter(args, &req_buf,
1443 server_supports_feature("fetch", "filter", 0));
1444
1445 if (server_supports_feature("fetch", "packfile-uris", 0)) {
1446 int i;
1447 struct strbuf to_send = STRBUF_INIT;
1448
1449 for (i = 0; i < uri_protocols.nr; i++) {
1450 const char *s = uri_protocols.items[i].string;
1451
1452 if (!strcmp(s, "https") || !strcmp(s, "http")) {
1453 if (to_send.len)
1454 strbuf_addch(&to_send, ',');
1455 strbuf_addstr(&to_send, s);
1456 }
1457 }
1458 if (to_send.len) {
1459 packet_buf_write(&req_buf, "packfile-uris %s",
1460 to_send.buf);
1461 strbuf_release(&to_send);
1462 }
1463 }
1464
1465 /* add wants */
1466 add_wants(wants, &req_buf);
1467
1468 /* Add all of the common commits we've found in previous rounds */
1469 add_common(&req_buf, common);
1470
1471 haves_added = add_haves(negotiator, &req_buf, haves_to_send,
1472 negotiation_include_oids);
1473 *in_vain += haves_added;
1474 trace2_data_intmax("negotiation_v2", the_repository, "haves_added", haves_added);
1475 trace2_data_intmax("negotiation_v2", the_repository, "in_vain", *in_vain);
1476 if (!haves_added || (seen_ack && *in_vain >= MAX_IN_VAIN)) {
1477 /* Send Done */
1478 packet_buf_write(&req_buf, "done\n");
1479 done_sent = 1;
1480 }
1481
1482 /* Send request */
1483 packet_buf_flush(&req_buf);
1484 if (write_in_full(fd_out, req_buf.buf, req_buf.len) < 0)
1485 die_errno(_("unable to write request to remote"));
1486
1487 strbuf_release(&req_buf);
1488 return done_sent;
1489 }
1490
1491 /*
1492 * Processes a section header in a server's response and checks if it matches
1493 * `section`. If the value of `peek` is 1, the header line will be peeked (and
1494 * not consumed); if 0, the line will be consumed and the function will die if
1495 * the section header doesn't match what was expected.
1496 */
1497 static int process_section_header(struct packet_reader *reader,
1498 const char *section, int peek)
1499 {
1500 int ret = 0;
1501
1502 if (packet_reader_peek(reader) == PACKET_READ_NORMAL &&
1503 !strcmp(reader->line, section))
1504 ret = 1;
1505
1506 if (!peek) {
1507 if (!ret) {
1508 if (reader->line)
1509 die(_("expected '%s', received '%s'"),
1510 section, reader->line);
1511 else
1512 die(_("expected '%s'"), section);
1513 }
1514 packet_reader_read(reader);
1515 }
1516
1517 return ret;
1518 }
1519
1520 static int process_ack(struct fetch_negotiator *negotiator,
1521 struct packet_reader *reader,
1522 struct object_id *common_oid,
1523 int *received_ready)
1524 {
1525 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1526 const char *arg;
1527
1528 if (!strcmp(reader->line, "NAK"))
1529 continue;
1530
1531 if (skip_prefix(reader->line, "ACK ", &arg)) {
1532 if (!get_oid_hex(arg, common_oid)) {
1533 struct commit *commit;
1534 commit = lookup_commit(the_repository, common_oid);
1535 if (negotiator)
1536 negotiator->ack(negotiator, commit);
1537 }
1538 return 1;
1539 }
1540
1541 if (!strcmp(reader->line, "ready")) {
1542 *received_ready = 1;
1543 continue;
1544 }
1545
1546 die(_("unexpected acknowledgment line: '%s'"), reader->line);
1547 }
1548
1549 if (reader->status != PACKET_READ_FLUSH &&
1550 reader->status != PACKET_READ_DELIM)
1551 die(_("error processing acks: %d"), reader->status);
1552
1553 /*
1554 * If an "acknowledgments" section is sent, a packfile is sent if and
1555 * only if "ready" was sent in this section. The other sections
1556 * ("shallow-info" and "wanted-refs") are sent only if a packfile is
1557 * sent. Therefore, a DELIM is expected if "ready" is sent, and a FLUSH
1558 * otherwise.
1559 */
1560 if (*received_ready && reader->status != PACKET_READ_DELIM)
1561 /*
1562 * TRANSLATORS: The parameter will be 'ready', a protocol
1563 * keyword.
1564 */
1565 die(_("expected packfile to be sent after '%s'"), "ready");
1566 if (!*received_ready && reader->status != PACKET_READ_FLUSH)
1567 /*
1568 * TRANSLATORS: The parameter will be 'ready', a protocol
1569 * keyword.
1570 */
1571 die(_("expected no other sections to be sent after no '%s'"), "ready");
1572
1573 return 0;
1574 }
1575
1576 static void receive_shallow_info(struct fetch_pack_args *args,
1577 struct packet_reader *reader,
1578 struct oid_array *shallows,
1579 struct shallow_info *si)
1580 {
1581 int unshallow_received = 0;
1582
1583 process_section_header(reader, "shallow-info", 0);
1584 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1585 const char *arg;
1586 struct object_id oid;
1587
1588 if (skip_prefix(reader->line, "shallow ", &arg)) {
1589 if (get_oid_hex(arg, &oid))
1590 die(_("invalid shallow line: %s"), reader->line);
1591 oid_array_append(shallows, &oid);
1592 continue;
1593 }
1594 if (skip_prefix(reader->line, "unshallow ", &arg)) {
1595 if (get_oid_hex(arg, &oid))
1596 die(_("invalid unshallow line: %s"), reader->line);
1597 if (!lookup_object(the_repository, &oid))
1598 die(_("object not found: %s"), reader->line);
1599 /* make sure that it is parsed as shallow */
1600 if (!parse_object(the_repository, &oid))
1601 die(_("error in object: %s"), reader->line);
1602 if (unregister_shallow(&oid))
1603 die(_("no shallow found: %s"), reader->line);
1604 unshallow_received = 1;
1605 continue;
1606 }
1607 die(_("expected shallow/unshallow, got %s"), reader->line);
1608 }
1609
1610 if (reader->status != PACKET_READ_FLUSH &&
1611 reader->status != PACKET_READ_DELIM)
1612 die(_("error processing shallow info: %d"), reader->status);
1613
1614 if (args->deepen || unshallow_received) {
1615 /*
1616 * Treat these as shallow lines caused by our depth settings.
1617 * In v0, these lines cannot cause refs to be rejected; do the
1618 * same.
1619 */
1620 int i;
1621
1622 for (i = 0; i < shallows->nr; i++)
1623 register_shallow(the_repository, &shallows->oid[i]);
1624 setup_alternate_shallow(&shallow_lock, &alternate_shallow_file,
1625 NULL);
1626 args->deepen = 1;
1627 } else if (shallows->nr) {
1628 /*
1629 * Treat these as shallow lines caused by the remote being
1630 * shallow. In v0, remote refs that reach these objects are
1631 * rejected (unless --update-shallow is set); do the same.
1632 */
1633 prepare_shallow_info(si, shallows);
1634 if (si->nr_ours || si->nr_theirs) {
1635 if (args->reject_shallow_remote)
1636 die(_("source repository is shallow, reject to clone."));
1637 alternate_shallow_file =
1638 setup_temporary_shallow(si->shallow);
1639 } else
1640 alternate_shallow_file = NULL;
1641 } else {
1642 alternate_shallow_file = NULL;
1643 }
1644 }
1645
1646 static int cmp_name_ref(const void *name, const void *ref)
1647 {
1648 return strcmp(name, (*(struct ref **)ref)->name);
1649 }
1650
1651 static void receive_wanted_refs(struct packet_reader *reader,
1652 struct ref **sought, int nr_sought)
1653 {
1654 process_section_header(reader, "wanted-refs", 0);
1655 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1656 struct object_id oid;
1657 const char *end;
1658 struct ref **found;
1659
1660 if (parse_oid_hex(reader->line, &oid, &end) || *end++ != ' ')
1661 die(_("expected wanted-ref, got '%s'"), reader->line);
1662
1663 found = bsearch(end, sought, nr_sought, sizeof(*sought),
1664 cmp_name_ref);
1665 if (!found)
1666 die(_("unexpected wanted-ref: '%s'"), reader->line);
1667 oidcpy(&(*found)->old_oid, &oid);
1668 }
1669
1670 if (reader->status != PACKET_READ_DELIM)
1671 die(_("error processing wanted refs: %d"), reader->status);
1672 }
1673
1674 static void receive_packfile_uris(struct packet_reader *reader,
1675 struct string_list *uris)
1676 {
1677 process_section_header(reader, "packfile-uris", 0);
1678 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1679 if (reader->pktlen < the_hash_algo->hexsz ||
1680 reader->line[the_hash_algo->hexsz] != ' ')
1681 die("expected '<hash> <uri>', got: %s", reader->line);
1682
1683 string_list_append(uris, reader->line);
1684 }
1685 if (reader->status != PACKET_READ_DELIM)
1686 die("expected DELIM");
1687 }
1688
1689 enum fetch_state {
1690 FETCH_CHECK_LOCAL = 0,
1691 FETCH_SEND_REQUEST,
1692 FETCH_PROCESS_ACKS,
1693 FETCH_GET_PACK,
1694 FETCH_DONE,
1695 };
1696
1697 static void do_check_stateless_delimiter(int stateless_rpc,
1698 struct packet_reader *reader)
1699 {
1700 check_stateless_delimiter(stateless_rpc, reader,
1701 _("git fetch-pack: expected response end packet"));
1702 }
1703
1704 static struct ref *do_fetch_pack_v2(struct fetch_pack_args *args,
1705 int fd[2],
1706 const struct ref *orig_ref,
1707 struct ref **sought, int nr_sought,
1708 struct oid_array *shallows,
1709 struct shallow_info *si,
1710 struct string_list *pack_lockfiles)
1711 {
1712 struct repository *r = the_repository;
1713 struct fsck_options fsck_options;
1714 struct ref *ref = copy_ref_list(orig_ref);
1715 enum fetch_state state = FETCH_CHECK_LOCAL;
1716 struct oidset common = OIDSET_INIT;
1717 struct oidset negotiation_include_oids = OIDSET_INIT;
1718 struct packet_reader reader;
1719 int in_vain = 0, negotiation_started = 0;
1720 int negotiation_round = 0;
1721 int haves_to_send = INITIAL_FLUSH;
1722 struct fetch_negotiator negotiator_alloc;
1723 struct fetch_negotiator *negotiator;
1724 int seen_ack = 0;
1725 struct object_id common_oid;
1726 int received_ready = 0;
1727 struct string_list packfile_uris = STRING_LIST_INIT_DUP;
1728 int i;
1729 struct strvec index_pack_args = STRVEC_INIT;
1730 const char *promisor_remote_config;
1731
1732 fsck_options_init(&fsck_options, the_repository, FSCK_OPTIONS_MISSING_GITMODULES);
1733
1734 if (server_feature_v2("promisor-remote", &promisor_remote_config))
1735 promisor_remote_reply(promisor_remote_config, NULL);
1736
1737 if (args->filter_options.choice == LOFC_AUTO) {
1738 struct strbuf errbuf = STRBUF_INIT;
1739 char *constructed_filter = promisor_remote_construct_filter(r);
1740
1741 list_objects_filter_release(&args->filter_options);
1742 /* Disallow 'auto' as a result of the resolution of this 'auto' filter below */
1743 args->filter_options.allow_auto_filter = 0;
1744
1745 if (constructed_filter &&
1746 gently_parse_list_objects_filter(&args->filter_options,
1747 constructed_filter,
1748 &errbuf))
1749 die(_("couldn't resolve 'auto' filter '%s': %s"),
1750 constructed_filter, errbuf.buf);
1751
1752 free(constructed_filter);
1753 strbuf_release(&errbuf);
1754 }
1755
1756 negotiator = &negotiator_alloc;
1757 if (args->refetch)
1758 fetch_negotiator_init_noop(negotiator);
1759 else
1760 fetch_negotiator_init(r, negotiator);
1761
1762 packet_reader_init(&reader, fd[0], NULL, 0,
1763 PACKET_READ_CHOMP_NEWLINE |
1764 PACKET_READ_DIE_ON_ERR_PACKET);
1765 if (git_env_bool("GIT_TEST_SIDEBAND_ALL", 1) &&
1766 server_supports_feature("fetch", "sideband-all", 0)) {
1767 reader.use_sideband = 1;
1768 reader.me = "fetch-pack";
1769 }
1770
1771 while (state != FETCH_DONE) {
1772 switch (state) {
1773 case FETCH_CHECK_LOCAL:
1774 sort_ref_list(&ref, ref_compare_name);
1775 QSORT(sought, nr_sought, cmp_ref_by_name);
1776
1777 /* v2 supports these by default */
1778 allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
1779 use_sideband = 2;
1780 if (args->depth > 0 || args->deepen_since || args->deepen_not)
1781 args->deepen = 1;
1782
1783 /* Filter 'ref' by 'sought' and those that aren't local */
1784 mark_complete_and_common_ref(negotiator, args, &ref);
1785 filter_refs(args, &ref, sought, nr_sought);
1786 if (!args->refetch && everything_local(args, &ref))
1787 state = FETCH_DONE;
1788 else
1789 state = FETCH_SEND_REQUEST;
1790
1791 mark_tips(negotiator, args->negotiation_restrict_tips);
1792 add_oids_to_set(args->negotiation_include_tips,
1793 &negotiation_include_oids);
1794 for_each_cached_alternate(negotiator,
1795 insert_one_alternate_object);
1796 break;
1797 case FETCH_SEND_REQUEST:
1798 if (!negotiation_started) {
1799 negotiation_started = 1;
1800 trace2_region_enter("fetch-pack",
1801 "negotiation_v2",
1802 the_repository);
1803 }
1804 negotiation_round++;
1805 trace2_region_enter_printf("negotiation_v2", "round",
1806 the_repository, "%d",
1807 negotiation_round);
1808 if (send_fetch_request(negotiator, fd[1], args, ref,
1809 &common,
1810 &haves_to_send, &in_vain,
1811 reader.use_sideband,
1812 seen_ack,
1813 &negotiation_include_oids)) {
1814 trace2_region_leave_printf("negotiation_v2", "round",
1815 the_repository, "%d",
1816 negotiation_round);
1817 state = FETCH_GET_PACK;
1818 }
1819 else
1820 state = FETCH_PROCESS_ACKS;
1821 break;
1822 case FETCH_PROCESS_ACKS:
1823 /* Process ACKs/NAKs */
1824 process_section_header(&reader, "acknowledgments", 0);
1825 while (process_ack(negotiator, &reader, &common_oid,
1826 &received_ready)) {
1827 in_vain = 0;
1828 seen_ack = 1;
1829 oidset_insert(&common, &common_oid);
1830 }
1831 trace2_region_leave_printf("negotiation_v2", "round",
1832 the_repository, "%d",
1833 negotiation_round);
1834 if (received_ready) {
1835 /*
1836 * Don't check for response delimiter; get_pack() will
1837 * read the rest of this response.
1838 */
1839 state = FETCH_GET_PACK;
1840 } else {
1841 do_check_stateless_delimiter(args->stateless_rpc, &reader);
1842 state = FETCH_SEND_REQUEST;
1843 }
1844 break;
1845 case FETCH_GET_PACK:
1846 trace2_region_leave("fetch-pack",
1847 "negotiation_v2",
1848 the_repository);
1849 trace2_data_intmax("negotiation_v2", the_repository,
1850 "total_rounds", negotiation_round);
1851 /* Check for shallow-info section */
1852 if (process_section_header(&reader, "shallow-info", 1))
1853 receive_shallow_info(args, &reader, shallows, si);
1854
1855 if (process_section_header(&reader, "wanted-refs", 1))
1856 receive_wanted_refs(&reader, sought, nr_sought);
1857
1858 /* get the pack(s) */
1859 if (git_env_bool("GIT_TRACE_REDACT", 1))
1860 reader.options |= PACKET_READ_REDACT_URI_PATH;
1861 if (process_section_header(&reader, "packfile-uris", 1))
1862 receive_packfile_uris(&reader, &packfile_uris);
1863 /* We don't expect more URIs. Reset to avoid expensive URI check. */
1864 reader.options &= ~PACKET_READ_REDACT_URI_PATH;
1865
1866 process_section_header(&reader, "packfile", 0);
1867
1868 /*
1869 * this is the final request we'll make of the server;
1870 * do a half-duplex shutdown to indicate that they can
1871 * hang up as soon as the pack is sent.
1872 */
1873 close(fd[1]);
1874 fd[1] = -1;
1875
1876 if (get_pack(args, fd, pack_lockfiles,
1877 packfile_uris.nr ? &index_pack_args : NULL,
1878 sought, nr_sought, &fsck_options.gitmodules_found))
1879 die(_("git fetch-pack: fetch failed."));
1880 do_check_stateless_delimiter(args->stateless_rpc, &reader);
1881
1882 state = FETCH_DONE;
1883 break;
1884 case FETCH_DONE:
1885 continue;
1886 }
1887 }
1888
1889 for (i = 0; i < packfile_uris.nr; i++) {
1890 int j;
1891 struct child_process cmd = CHILD_PROCESS_INIT;
1892 char packname[GIT_MAX_HEXSZ + 1];
1893 const char *uri = packfile_uris.items[i].string +
1894 the_hash_algo->hexsz + 1;
1895
1896 strvec_push(&cmd.args, "http-fetch");
1897 strvec_pushf(&cmd.args, "--packfile=%.*s",
1898 (int) the_hash_algo->hexsz,
1899 packfile_uris.items[i].string);
1900 for (j = 0; j < index_pack_args.nr; j++)
1901 strvec_pushf(&cmd.args, "--index-pack-arg=%s",
1902 index_pack_args.v[j]);
1903 strvec_push(&cmd.args, uri);
1904 cmd.git_cmd = 1;
1905 cmd.no_stdin = 1;
1906 cmd.out = -1;
1907 if (start_command(&cmd))
1908 die("fetch-pack: unable to spawn http-fetch");
1909
1910 if (read_in_full(cmd.out, packname, 5) < 0 ||
1911 memcmp(packname, "keep\t", 5))
1912 die("fetch-pack: expected keep then TAB at start of http-fetch output");
1913
1914 if (read_in_full(cmd.out, packname,
1915 the_hash_algo->hexsz + 1) < 0 ||
1916 packname[the_hash_algo->hexsz] != '\n')
1917 die("fetch-pack: expected hash then LF at end of http-fetch output");
1918
1919 packname[the_hash_algo->hexsz] = '\0';
1920
1921 parse_gitmodules_oids(cmd.out, &fsck_options.gitmodules_found);
1922
1923 close(cmd.out);
1924
1925 if (finish_command(&cmd))
1926 die("fetch-pack: unable to finish http-fetch");
1927
1928 if (memcmp(packfile_uris.items[i].string, packname,
1929 the_hash_algo->hexsz))
1930 die("fetch-pack: pack downloaded from %s does not match expected hash %.*s",
1931 uri, (int) the_hash_algo->hexsz,
1932 packfile_uris.items[i].string);
1933
1934 string_list_append_nodup(pack_lockfiles,
1935 xstrfmt("%s/pack/pack-%s.keep",
1936 repo_get_object_directory(the_repository),
1937 packname));
1938 }
1939 string_list_clear(&packfile_uris, 0);
1940 strvec_clear(&index_pack_args);
1941
1942 if (fsck_finish(&fsck_options))
1943 die("fsck failed");
1944
1945 if (negotiator)
1946 negotiator->release(negotiator);
1947
1948 fsck_options_clear(&fsck_options);
1949 oidset_clear(&common);
1950 oidset_clear(&negotiation_include_oids);
1951 return ref;
1952 }
1953
1954 int fetch_pack_fsck_config(const char *var, const char *value,
1955 struct strbuf *msg_types)
1956 {
1957 const char *msg_id;
1958
1959 if (strcmp(var, "fetch.fsck.skiplist") == 0) {
1960 char *path ;
1961
1962 if (git_config_pathname(&path, var, value))
1963 return -1;
1964 if (path)
1965 strbuf_addf(msg_types, "%cskiplist=%s",
1966 msg_types->len ? ',' : '=', path);
1967 free(path);
1968 return 0;
1969 }
1970
1971 if (skip_prefix(var, "fetch.fsck.", &msg_id)) {
1972 if (!value)
1973 return config_error_nonbool(var);
1974 if (is_valid_msg_type(msg_id, value))
1975 strbuf_addf(msg_types, "%c%s=%s",
1976 msg_types->len ? ',' : '=', msg_id, value);
1977 else
1978 warning("Skipping unknown msg id '%s'", msg_id);
1979 return 0;
1980 }
1981
1982 return 1;
1983 }
1984
1985 static int fetch_pack_config_cb(const char *var, const char *value,
1986 const struct config_context *ctx, void *cb)
1987 {
1988 int ret = fetch_pack_fsck_config(var, value, &fsck_msg_types);
1989 if (ret > 0)
1990 return git_default_config(var, value, ctx, cb);
1991
1992 return ret;
1993 }
1994
1995 static void fetch_pack_config(void)
1996 {
1997 repo_config_get_int(the_repository, "fetch.unpacklimit", &fetch_unpack_limit);
1998 repo_config_get_int(the_repository, "transfer.unpacklimit", &transfer_unpack_limit);
1999 repo_config_get_bool(the_repository, "repack.usedeltabaseoffset", &prefer_ofs_delta);
2000 repo_config_get_bool(the_repository, "fetch.fsckobjects", &fetch_fsck_objects);
2001 repo_config_get_bool(the_repository, "transfer.fsckobjects", &transfer_fsck_objects);
2002 repo_config_get_bool(the_repository, "transfer.advertisesid", &advertise_sid);
2003 if (!uri_protocols.nr) {
2004 char *str;
2005
2006 if (!repo_config_get_string(the_repository, "fetch.uriprotocols", &str) && str) {
2007 string_list_split(&uri_protocols, str, ",", -1);
2008 free(str);
2009 }
2010 }
2011
2012 repo_config(the_repository, fetch_pack_config_cb, NULL);
2013 }
2014
2015 static void fetch_pack_setup(void)
2016 {
2017 static int did_setup;
2018 if (did_setup)
2019 return;
2020 fetch_pack_config();
2021 if (0 <= fetch_unpack_limit)
2022 unpack_limit = fetch_unpack_limit;
2023 else if (0 <= transfer_unpack_limit)
2024 unpack_limit = transfer_unpack_limit;
2025 did_setup = 1;
2026 }
2027
2028 static int remove_duplicates_in_refs(struct ref **ref, int nr)
2029 {
2030 struct string_list names = STRING_LIST_INIT_NODUP;
2031 int src, dst;
2032
2033 for (src = dst = 0; src < nr; src++) {
2034 struct string_list_item *item;
2035 item = string_list_insert(&names, ref[src]->name);
2036 if (item->util)
2037 continue; /* already have it */
2038 item->util = ref[src];
2039 if (src != dst)
2040 ref[dst] = ref[src];
2041 dst++;
2042 }
2043 for (src = dst; src < nr; src++)
2044 ref[src] = NULL;
2045 string_list_clear(&names, 0);
2046 return dst;
2047 }
2048
2049 static void update_shallow(struct fetch_pack_args *args,
2050 struct ref **sought, int nr_sought,
2051 struct shallow_info *si)
2052 {
2053 struct oid_array ref = OID_ARRAY_INIT;
2054 int *status;
2055 int i;
2056
2057 if (args->deepen && alternate_shallow_file) {
2058 if (*alternate_shallow_file == '\0') { /* --unshallow */
2059 unlink_or_warn(git_path_shallow(the_repository));
2060 rollback_shallow_file(the_repository, &shallow_lock);
2061 } else
2062 commit_shallow_file(the_repository, &shallow_lock);
2063 alternate_shallow_file = NULL;
2064 return;
2065 }
2066
2067 if (!si->shallow || !si->shallow->nr)
2068 return;
2069
2070 if (args->cloning) {
2071 /*
2072 * remote is shallow, but this is a clone, there are
2073 * no objects in repo to worry about. Accept any
2074 * shallow points that exist in the pack (iow in repo
2075 * after get_pack() and odb_reprepare())
2076 */
2077 struct oid_array extra = OID_ARRAY_INIT;
2078 struct object_id *oid = si->shallow->oid;
2079 for (i = 0; i < si->shallow->nr; i++)
2080 if (odb_has_object(the_repository->objects, &oid[i],
2081 ODB_HAS_OBJECT_RECHECK_PACKED | ODB_HAS_OBJECT_FETCH_PROMISOR))
2082 oid_array_append(&extra, &oid[i]);
2083 if (extra.nr) {
2084 setup_alternate_shallow(&shallow_lock,
2085 &alternate_shallow_file,
2086 &extra);
2087 commit_shallow_file(the_repository, &shallow_lock);
2088 alternate_shallow_file = NULL;
2089 }
2090 oid_array_clear(&extra);
2091 return;
2092 }
2093
2094 if (!si->nr_ours && !si->nr_theirs)
2095 return;
2096
2097 remove_nonexistent_theirs_shallow(si);
2098 if (!si->nr_ours && !si->nr_theirs)
2099 return;
2100 for (i = 0; i < nr_sought; i++)
2101 oid_array_append(&ref, &sought[i]->old_oid);
2102 si->ref = &ref;
2103
2104 if (args->update_shallow) {
2105 /*
2106 * remote is also shallow, .git/shallow may be updated
2107 * so all refs can be accepted. Make sure we only add
2108 * shallow roots that are actually reachable from new
2109 * refs.
2110 */
2111 struct oid_array extra = OID_ARRAY_INIT;
2112 struct object_id *oid = si->shallow->oid;
2113 assign_shallow_commits_to_refs(si, NULL, NULL);
2114 if (!si->nr_ours && !si->nr_theirs) {
2115 oid_array_clear(&ref);
2116 return;
2117 }
2118 for (i = 0; i < si->nr_ours; i++)
2119 oid_array_append(&extra, &oid[si->ours[i]]);
2120 for (i = 0; i < si->nr_theirs; i++)
2121 oid_array_append(&extra, &oid[si->theirs[i]]);
2122 setup_alternate_shallow(&shallow_lock,
2123 &alternate_shallow_file,
2124 &extra);
2125 commit_shallow_file(the_repository, &shallow_lock);
2126 oid_array_clear(&extra);
2127 oid_array_clear(&ref);
2128 alternate_shallow_file = NULL;
2129 return;
2130 }
2131
2132 /*
2133 * remote is also shallow, check what ref is safe to update
2134 * without updating .git/shallow
2135 */
2136 CALLOC_ARRAY(status, nr_sought);
2137 assign_shallow_commits_to_refs(si, NULL, status);
2138 if (si->nr_ours || si->nr_theirs) {
2139 for (i = 0; i < nr_sought; i++)
2140 if (status[i])
2141 sought[i]->status = REF_STATUS_REJECT_SHALLOW;
2142 }
2143 free(status);
2144 oid_array_clear(&ref);
2145 }
2146
2147 static const struct object_id *iterate_ref_map(void *cb_data)
2148 {
2149 struct ref **rm = cb_data;
2150 struct ref *ref = *rm;
2151
2152 if (!ref)
2153 return NULL;
2154 *rm = ref->next;
2155 return &ref->old_oid;
2156 }
2157
2158 int fetch_pack_fsck_objects(void)
2159 {
2160 fetch_pack_setup();
2161 if (fetch_fsck_objects >= 0)
2162 return fetch_fsck_objects;
2163 if (transfer_fsck_objects >= 0)
2164 return transfer_fsck_objects;
2165 return 0;
2166 }
2167
2168 struct ref *fetch_pack(struct fetch_pack_args *args,
2169 int fd[],
2170 const struct ref *ref,
2171 struct ref **sought, int nr_sought,
2172 struct oid_array *shallow,
2173 struct string_list *pack_lockfiles,
2174 enum protocol_version version)
2175 {
2176 struct ref *ref_cpy;
2177 struct shallow_info si;
2178 struct oid_array shallows_scratch = OID_ARRAY_INIT;
2179
2180 fetch_pack_setup();
2181 if (nr_sought)
2182 nr_sought = remove_duplicates_in_refs(sought, nr_sought);
2183
2184 if (version != protocol_v2 && !ref) {
2185 packet_flush(fd[1]);
2186 die(_("no matching remote head"));
2187 }
2188 if (version == protocol_v2) {
2189 if (shallow->nr)
2190 BUG("Protocol V2 does not provide shallows at this point in the fetch");
2191 memset(&si, 0, sizeof(si));
2192 ref_cpy = do_fetch_pack_v2(args, fd, ref, sought, nr_sought,
2193 &shallows_scratch, &si,
2194 pack_lockfiles);
2195 } else {
2196 prepare_shallow_info(&si, shallow);
2197 ref_cpy = do_fetch_pack(args, fd, ref, sought, nr_sought,
2198 &si, pack_lockfiles);
2199 }
2200 odb_reprepare(the_repository->objects);
2201
2202 if (!args->cloning && args->deepen) {
2203 struct check_connected_options opt = CHECK_CONNECTED_INIT;
2204 struct ref *iterator = ref_cpy;
2205 opt.shallow_file = alternate_shallow_file;
2206 if (args->deepen)
2207 opt.is_deepening_fetch = 1;
2208 if (check_connected(iterate_ref_map, &iterator, &opt)) {
2209 error(_("remote did not send all necessary objects"));
2210 free_refs(ref_cpy);
2211 ref_cpy = NULL;
2212 rollback_shallow_file(the_repository, &shallow_lock);
2213 goto cleanup;
2214 }
2215 args->connectivity_checked = 1;
2216 }
2217
2218 update_shallow(args, sought, nr_sought, &si);
2219 cleanup:
2220 clear_shallow_info(&si);
2221 oid_array_clear(&shallows_scratch);
2222 return ref_cpy;
2223 }
2224
2225 static int add_to_object_array(const struct object_id *oid, void *data)
2226 {
2227 struct object_array *a = data;
2228
2229 add_object_array(lookup_object(the_repository, oid), "", a);
2230 return 0;
2231 }
2232
2233 static void clear_common_flag(struct oidset *s)
2234 {
2235 struct oidset_iter iter;
2236 const struct object_id *oid;
2237 oidset_iter_init(s, &iter);
2238
2239 while ((oid = oidset_iter_next(&iter))) {
2240 struct object *obj = lookup_object(the_repository, oid);
2241 obj->flags &= ~COMMON;
2242 }
2243 }
2244
2245 void negotiate_using_fetch(const struct oid_array *negotiation_restrict_tips,
2246 const struct string_list *server_options,
2247 int stateless_rpc,
2248 int fd[],
2249 struct oidset *acked_commits,
2250 const struct oid_array *negotiation_include_tips)
2251 {
2252 struct fetch_negotiator negotiator;
2253 struct packet_reader reader;
2254 struct object_array nt_object_array = OBJECT_ARRAY_INIT;
2255 struct strbuf req_buf = STRBUF_INIT;
2256 struct oidset negotiation_include_oids = OIDSET_INIT;
2257 int haves_to_send = INITIAL_FLUSH;
2258 int in_vain = 0;
2259 int seen_ack = 0;
2260 int last_iteration = 0;
2261 int negotiation_round = 0;
2262 timestamp_t min_generation = GENERATION_NUMBER_INFINITY;
2263
2264 fetch_negotiator_init(the_repository, &negotiator);
2265 mark_tips(&negotiator, negotiation_restrict_tips);
2266
2267 add_oids_to_set(negotiation_include_tips,
2268 &negotiation_include_oids);
2269
2270 packet_reader_init(&reader, fd[0], NULL, 0,
2271 PACKET_READ_CHOMP_NEWLINE |
2272 PACKET_READ_DIE_ON_ERR_PACKET);
2273
2274 oid_array_for_each((struct oid_array *) negotiation_restrict_tips,
2275 add_to_object_array,
2276 &nt_object_array);
2277
2278 trace2_region_enter("fetch-pack", "negotiate_using_fetch", the_repository);
2279 while (!last_iteration) {
2280 int haves_added;
2281 struct object_id common_oid;
2282 int received_ready = 0;
2283
2284 negotiation_round++;
2285
2286 trace2_region_enter_printf("negotiate_using_fetch", "round",
2287 the_repository, "%d",
2288 negotiation_round);
2289 strbuf_reset(&req_buf);
2290 write_fetch_command_and_capabilities(&req_buf, server_options);
2291
2292 packet_buf_write(&req_buf, "wait-for-done");
2293
2294 haves_added = add_haves(&negotiator, &req_buf, &haves_to_send,
2295 &negotiation_include_oids);
2296 in_vain += haves_added;
2297 if (!haves_added || (seen_ack && in_vain >= MAX_IN_VAIN))
2298 last_iteration = 1;
2299
2300 trace2_data_intmax("negotiate_using_fetch", the_repository,
2301 "haves_added", haves_added);
2302 trace2_data_intmax("negotiate_using_fetch", the_repository,
2303 "in_vain", in_vain);
2304
2305 /* Send request */
2306 packet_buf_flush(&req_buf);
2307 if (write_in_full(fd[1], req_buf.buf, req_buf.len) < 0)
2308 die_errno(_("unable to write request to remote"));
2309
2310 /* Process ACKs/NAKs */
2311 process_section_header(&reader, "acknowledgments", 0);
2312 while (process_ack(&negotiator, &reader, &common_oid,
2313 &received_ready)) {
2314 struct commit *commit = lookup_commit(the_repository,
2315 &common_oid);
2316 if (commit) {
2317 timestamp_t generation;
2318
2319 parse_commit_or_die(commit);
2320 commit->object.flags |= COMMON;
2321 generation = commit_graph_generation(commit);
2322 if (generation < min_generation)
2323 min_generation = generation;
2324 }
2325 in_vain = 0;
2326 seen_ack = 1;
2327 oidset_insert(acked_commits, &common_oid);
2328 }
2329 if (received_ready)
2330 die(_("unexpected 'ready' from remote"));
2331 else
2332 do_check_stateless_delimiter(stateless_rpc, &reader);
2333 if (can_all_from_reach_with_flag(&nt_object_array, COMMON,
2334 REACH_SCRATCH, 0,
2335 min_generation))
2336 last_iteration = 1;
2337 trace2_region_leave_printf("negotiation", "round",
2338 the_repository, "%d",
2339 negotiation_round);
2340 }
2341 trace2_region_leave("fetch-pack", "negotiate_using_fetch", the_repository);
2342 trace2_data_intmax("negotiate_using_fetch", the_repository,
2343 "total_rounds", negotiation_round);
2344
2345 clear_common_flag(acked_commits);
2346 object_array_clear(&nt_object_array);
2347 oidset_clear(&negotiation_include_oids);
2348 negotiator.release(&negotiator);
2349 strbuf_release(&req_buf);
2350 }
2351
2352 int report_unmatched_refs(struct ref **sought, int nr_sought)
2353 {
2354 int i, ret = 0;
2355
2356 for (i = 0; i < nr_sought; i++) {
2357 if (!sought[i])
2358 continue;
2359 switch (sought[i]->match_status) {
2360 case REF_MATCHED:
2361 continue;
2362 case REF_NOT_MATCHED:
2363 error(_("no such remote ref %s"), sought[i]->name);
2364 break;
2365 case REF_UNADVERTISED_NOT_ALLOWED:
2366 error(_("Server does not allow request for unadvertised object %s"),
2367 sought[i]->name);
2368 break;
2369 }
2370 ret = 1;
2371 }
2372 return ret;
2373 }