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 "sha1-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
26static int transfer_unpack_limit = -1;
27static int fetch_unpack_limit = -1;
28static int unpack_limit = 100;
29static int prefer_ofs_delta = 1;
30static int no_done;
31static int deepen_since_ok;
32static int deepen_not_ok;
33static int fetch_fsck_objects = -1;
34static int transfer_fsck_objects = -1;
35static int agent_supported;
36static int server_supports_filtering;
37static struct lock_file shallow_lock;
38static const char *alternate_shallow_file;
39static char *negotiation_algorithm;
40static struct strbuf fsck_msg_types = STRBUF_INIT;
41
42/* Remember to update object flag allocation in object.h */
43#define COMPLETE (1U << 0)
44#define ALTERNATE (1U << 1)
45
46/*
47 * After sending this many "have"s if we do not get any new ACK , we
48 * give up traversing our history.
49 */
50#define MAX_IN_VAIN 256
51
52static int multi_ack, use_sideband;
53/* Allow specifying sha1 if it is a ref tip. */
54#define ALLOW_TIP_SHA1 01
55/* Allow request of a sha1 if it is reachable from a ref (possibly hidden ref). */
56#define ALLOW_REACHABLE_SHA1 02
57static unsigned int allow_unadvertised_object_request;
58
59__attribute__((format (printf, 2, 3)))
60static inline void print_verbose(const struct fetch_pack_args *args,
61 const char *fmt, ...)
62{
63 va_list params;
64
65 if (!args->verbose)
66 return;
67
68 va_start(params, fmt);
69 vfprintf(stderr, fmt, params);
70 va_end(params);
71 fputc('\n', stderr);
72}
73
74struct alternate_object_cache {
75 struct object **items;
76 size_t nr, alloc;
77};
78
79static void cache_one_alternate(const struct object_id *oid,
80 void *vcache)
81{
82 struct alternate_object_cache *cache = vcache;
83 struct object *obj = parse_object(the_repository, oid);
84
85 if (!obj || (obj->flags & ALTERNATE))
86 return;
87
88 obj->flags |= ALTERNATE;
89 ALLOC_GROW(cache->items, cache->nr + 1, cache->alloc);
90 cache->items[cache->nr++] = obj;
91}
92
93static void for_each_cached_alternate(struct fetch_negotiator *negotiator,
94 void (*cb)(struct fetch_negotiator *,
95 struct object *))
96{
97 static int initialized;
98 static struct alternate_object_cache cache;
99 size_t i;
100
101 if (!initialized) {
102 for_each_alternate_ref(cache_one_alternate, &cache);
103 initialized = 1;
104 }
105
106 for (i = 0; i < cache.nr; i++)
107 cb(negotiator, cache.items[i]);
108}
109
110static int rev_list_insert_ref(struct fetch_negotiator *negotiator,
111 const char *refname,
112 const struct object_id *oid)
113{
114 struct object *o = deref_tag(the_repository,
115 parse_object(the_repository, oid),
116 refname, 0);
117
118 if (o && o->type == OBJ_COMMIT)
119 negotiator->add_tip(negotiator, (struct commit *)o);
120
121 return 0;
122}
123
124static int rev_list_insert_ref_oid(const char *refname, const struct object_id *oid,
125 int flag, void *cb_data)
126{
127 return rev_list_insert_ref(cb_data, refname, oid);
128}
129
130enum ack_type {
131 NAK = 0,
132 ACK,
133 ACK_continue,
134 ACK_common,
135 ACK_ready
136};
137
138static void consume_shallow_list(struct fetch_pack_args *args, int fd)
139{
140 if (args->stateless_rpc && args->deepen) {
141 /* If we sent a depth we will get back "duplicate"
142 * shallow and unshallow commands every time there
143 * is a block of have lines exchanged.
144 */
145 char *line;
146 while ((line = packet_read_line(fd, NULL))) {
147 if (starts_with(line, "shallow "))
148 continue;
149 if (starts_with(line, "unshallow "))
150 continue;
151 die(_("git fetch-pack: expected shallow list"));
152 }
153 }
154}
155
156static enum ack_type get_ack(int fd, struct object_id *result_oid)
157{
158 int len;
159 char *line = packet_read_line(fd, &len);
160 const char *arg;
161
162 if (!line)
163 die(_("git fetch-pack: expected ACK/NAK, got a flush packet"));
164 if (!strcmp(line, "NAK"))
165 return NAK;
166 if (skip_prefix(line, "ACK ", &arg)) {
167 if (!get_oid_hex(arg, result_oid)) {
168 arg += 40;
169 len -= arg - line;
170 if (len < 1)
171 return ACK;
172 if (strstr(arg, "continue"))
173 return ACK_continue;
174 if (strstr(arg, "common"))
175 return ACK_common;
176 if (strstr(arg, "ready"))
177 return ACK_ready;
178 return ACK;
179 }
180 }
181 if (skip_prefix(line, "ERR ", &arg))
182 die(_("remote error: %s"), arg);
183 die(_("git fetch-pack: expected ACK/NAK, got '%s'"), line);
184}
185
186static void send_request(struct fetch_pack_args *args,
187 int fd, struct strbuf *buf)
188{
189 if (args->stateless_rpc) {
190 send_sideband(fd, -1, buf->buf, buf->len, LARGE_PACKET_MAX);
191 packet_flush(fd);
192 } else
193 write_or_die(fd, buf->buf, buf->len);
194}
195
196static void insert_one_alternate_object(struct fetch_negotiator *negotiator,
197 struct object *obj)
198{
199 rev_list_insert_ref(negotiator, NULL, &obj->oid);
200}
201
202#define INITIAL_FLUSH 16
203#define PIPESAFE_FLUSH 32
204#define LARGE_FLUSH 16384
205
206static int next_flush(int stateless_rpc, int count)
207{
208 if (stateless_rpc) {
209 if (count < LARGE_FLUSH)
210 count <<= 1;
211 else
212 count = count * 11 / 10;
213 } else {
214 if (count < PIPESAFE_FLUSH)
215 count <<= 1;
216 else
217 count += PIPESAFE_FLUSH;
218 }
219 return count;
220}
221
222static void mark_tips(struct fetch_negotiator *negotiator,
223 const struct oid_array *negotiation_tips)
224{
225 int i;
226
227 if (!negotiation_tips) {
228 for_each_ref(rev_list_insert_ref_oid, negotiator);
229 return;
230 }
231
232 for (i = 0; i < negotiation_tips->nr; i++)
233 rev_list_insert_ref(negotiator, NULL,
234 &negotiation_tips->oid[i]);
235 return;
236}
237
238static int find_common(struct fetch_negotiator *negotiator,
239 struct fetch_pack_args *args,
240 int fd[2], struct object_id *result_oid,
241 struct ref *refs)
242{
243 int fetching;
244 int count = 0, flushes = 0, flush_at = INITIAL_FLUSH, retval;
245 const struct object_id *oid;
246 unsigned in_vain = 0;
247 int got_continue = 0;
248 int got_ready = 0;
249 struct strbuf req_buf = STRBUF_INIT;
250 size_t state_len = 0;
251
252 if (args->stateless_rpc && multi_ack == 1)
253 die(_("--stateless-rpc requires multi_ack_detailed"));
254
255 if (!args->no_dependents) {
256 mark_tips(negotiator, args->negotiation_tips);
257 for_each_cached_alternate(negotiator, insert_one_alternate_object);
258 }
259
260 fetching = 0;
261 for ( ; refs ; refs = refs->next) {
262 struct object_id *remote = &refs->old_oid;
263 const char *remote_hex;
264 struct object *o;
265
266 /*
267 * If that object is complete (i.e. it is an ancestor of a
268 * local ref), we tell them we have it but do not have to
269 * tell them about its ancestors, which they already know
270 * about.
271 *
272 * We use lookup_object here because we are only
273 * interested in the case we *know* the object is
274 * reachable and we have already scanned it.
275 *
276 * Do this only if args->no_dependents is false (if it is true,
277 * we cannot trust the object flags).
278 */
279 if (!args->no_dependents &&
280 ((o = lookup_object(the_repository, remote->hash)) != NULL) &&
281 (o->flags & COMPLETE)) {
282 continue;
283 }
284
285 remote_hex = oid_to_hex(remote);
286 if (!fetching) {
287 struct strbuf c = STRBUF_INIT;
288 if (multi_ack == 2) strbuf_addstr(&c, " multi_ack_detailed");
289 if (multi_ack == 1) strbuf_addstr(&c, " multi_ack");
290 if (no_done) strbuf_addstr(&c, " no-done");
291 if (use_sideband == 2) strbuf_addstr(&c, " side-band-64k");
292 if (use_sideband == 1) strbuf_addstr(&c, " side-band");
293 if (args->deepen_relative) strbuf_addstr(&c, " deepen-relative");
294 if (args->use_thin_pack) strbuf_addstr(&c, " thin-pack");
295 if (args->no_progress) strbuf_addstr(&c, " no-progress");
296 if (args->include_tag) strbuf_addstr(&c, " include-tag");
297 if (prefer_ofs_delta) strbuf_addstr(&c, " ofs-delta");
298 if (deepen_since_ok) strbuf_addstr(&c, " deepen-since");
299 if (deepen_not_ok) strbuf_addstr(&c, " deepen-not");
300 if (agent_supported) strbuf_addf(&c, " agent=%s",
301 git_user_agent_sanitized());
302 if (args->filter_options.choice)
303 strbuf_addstr(&c, " filter");
304 packet_buf_write(&req_buf, "want %s%s\n", remote_hex, c.buf);
305 strbuf_release(&c);
306 } else
307 packet_buf_write(&req_buf, "want %s\n", remote_hex);
308 fetching++;
309 }
310
311 if (!fetching) {
312 strbuf_release(&req_buf);
313 packet_flush(fd[1]);
314 return 1;
315 }
316
317 if (is_repository_shallow(the_repository))
318 write_shallow_commits(&req_buf, 1, NULL);
319 if (args->depth > 0)
320 packet_buf_write(&req_buf, "deepen %d", args->depth);
321 if (args->deepen_since) {
322 timestamp_t max_age = approxidate(args->deepen_since);
323 packet_buf_write(&req_buf, "deepen-since %"PRItime, max_age);
324 }
325 if (args->deepen_not) {
326 int i;
327 for (i = 0; i < args->deepen_not->nr; i++) {
328 struct string_list_item *s = args->deepen_not->items + i;
329 packet_buf_write(&req_buf, "deepen-not %s", s->string);
330 }
331 }
332 if (server_supports_filtering && args->filter_options.choice) {
333 struct strbuf expanded_filter_spec = STRBUF_INIT;
334 expand_list_objects_filter_spec(&args->filter_options,
335 &expanded_filter_spec);
336 packet_buf_write(&req_buf, "filter %s",
337 expanded_filter_spec.buf);
338 strbuf_release(&expanded_filter_spec);
339 }
340 packet_buf_flush(&req_buf);
341 state_len = req_buf.len;
342
343 if (args->deepen) {
344 char *line;
345 const char *arg;
346 struct object_id oid;
347
348 send_request(args, fd[1], &req_buf);
349 while ((line = packet_read_line(fd[0], NULL))) {
350 if (skip_prefix(line, "shallow ", &arg)) {
351 if (get_oid_hex(arg, &oid))
352 die(_("invalid shallow line: %s"), line);
353 register_shallow(the_repository, &oid);
354 continue;
355 }
356 if (skip_prefix(line, "unshallow ", &arg)) {
357 if (get_oid_hex(arg, &oid))
358 die(_("invalid unshallow line: %s"), line);
359 if (!lookup_object(the_repository, oid.hash))
360 die(_("object not found: %s"), line);
361 /* make sure that it is parsed as shallow */
362 if (!parse_object(the_repository, &oid))
363 die(_("error in object: %s"), line);
364 if (unregister_shallow(&oid))
365 die(_("no shallow found: %s"), line);
366 continue;
367 }
368 die(_("expected shallow/unshallow, got %s"), line);
369 }
370 } else if (!args->stateless_rpc)
371 send_request(args, fd[1], &req_buf);
372
373 if (!args->stateless_rpc) {
374 /* If we aren't using the stateless-rpc interface
375 * we don't need to retain the headers.
376 */
377 strbuf_setlen(&req_buf, 0);
378 state_len = 0;
379 }
380
381 flushes = 0;
382 retval = -1;
383 if (args->no_dependents)
384 goto done;
385 while ((oid = negotiator->next(negotiator))) {
386 packet_buf_write(&req_buf, "have %s\n", oid_to_hex(oid));
387 print_verbose(args, "have %s", oid_to_hex(oid));
388 in_vain++;
389 if (flush_at <= ++count) {
390 int ack;
391
392 packet_buf_flush(&req_buf);
393 send_request(args, fd[1], &req_buf);
394 strbuf_setlen(&req_buf, state_len);
395 flushes++;
396 flush_at = next_flush(args->stateless_rpc, count);
397
398 /*
399 * We keep one window "ahead" of the other side, and
400 * will wait for an ACK only on the next one
401 */
402 if (!args->stateless_rpc && count == INITIAL_FLUSH)
403 continue;
404
405 consume_shallow_list(args, fd[0]);
406 do {
407 ack = get_ack(fd[0], result_oid);
408 if (ack)
409 print_verbose(args, _("got %s %d %s"), "ack",
410 ack, oid_to_hex(result_oid));
411 switch (ack) {
412 case ACK:
413 flushes = 0;
414 multi_ack = 0;
415 retval = 0;
416 goto done;
417 case ACK_common:
418 case ACK_ready:
419 case ACK_continue: {
420 struct commit *commit =
421 lookup_commit(the_repository,
422 result_oid);
423 int was_common;
424
425 if (!commit)
426 die(_("invalid commit %s"), oid_to_hex(result_oid));
427 was_common = negotiator->ack(negotiator, commit);
428 if (args->stateless_rpc
429 && ack == ACK_common
430 && !was_common) {
431 /* We need to replay the have for this object
432 * on the next RPC request so the peer knows
433 * it is in common with us.
434 */
435 const char *hex = oid_to_hex(result_oid);
436 packet_buf_write(&req_buf, "have %s\n", hex);
437 state_len = req_buf.len;
438 /*
439 * Reset in_vain because an ack
440 * for this commit has not been
441 * seen.
442 */
443 in_vain = 0;
444 } else if (!args->stateless_rpc
445 || ack != ACK_common)
446 in_vain = 0;
447 retval = 0;
448 got_continue = 1;
449 if (ack == ACK_ready)
450 got_ready = 1;
451 break;
452 }
453 }
454 } while (ack);
455 flushes--;
456 if (got_continue && MAX_IN_VAIN < in_vain) {
457 print_verbose(args, _("giving up"));
458 break; /* give up */
459 }
460 if (got_ready)
461 break;
462 }
463 }
464done:
465 if (!got_ready || !no_done) {
466 packet_buf_write(&req_buf, "done\n");
467 send_request(args, fd[1], &req_buf);
468 }
469 print_verbose(args, _("done"));
470 if (retval != 0) {
471 multi_ack = 0;
472 flushes++;
473 }
474 strbuf_release(&req_buf);
475
476 if (!got_ready || !no_done)
477 consume_shallow_list(args, fd[0]);
478 while (flushes || multi_ack) {
479 int ack = get_ack(fd[0], result_oid);
480 if (ack) {
481 print_verbose(args, _("got %s (%d) %s"), "ack",
482 ack, oid_to_hex(result_oid));
483 if (ack == ACK)
484 return 0;
485 multi_ack = 1;
486 continue;
487 }
488 flushes--;
489 }
490 /* it is no error to fetch into a completely empty repo */
491 return count ? retval : 0;
492}
493
494static struct commit_list *complete;
495
496static int mark_complete(const struct object_id *oid)
497{
498 struct object *o = parse_object(the_repository, oid);
499
500 while (o && o->type == OBJ_TAG) {
501 struct tag *t = (struct tag *) o;
502 if (!t->tagged)
503 break; /* broken repository */
504 o->flags |= COMPLETE;
505 o = parse_object(the_repository, &t->tagged->oid);
506 }
507 if (o && o->type == OBJ_COMMIT) {
508 struct commit *commit = (struct commit *)o;
509 if (!(commit->object.flags & COMPLETE)) {
510 commit->object.flags |= COMPLETE;
511 commit_list_insert(commit, &complete);
512 }
513 }
514 return 0;
515}
516
517static int mark_complete_oid(const char *refname, const struct object_id *oid,
518 int flag, void *cb_data)
519{
520 return mark_complete(oid);
521}
522
523static void mark_recent_complete_commits(struct fetch_pack_args *args,
524 timestamp_t cutoff)
525{
526 while (complete && cutoff <= complete->item->date) {
527 print_verbose(args, _("Marking %s as complete"),
528 oid_to_hex(&complete->item->object.oid));
529 pop_most_recent_commit(&complete, COMPLETE);
530 }
531}
532
533static void add_refs_to_oidset(struct oidset *oids, struct ref *refs)
534{
535 for (; refs; refs = refs->next)
536 oidset_insert(oids, &refs->old_oid);
537}
538
539static int is_unmatched_ref(const struct ref *ref)
540{
541 struct object_id oid;
542 const char *p;
543 return ref->match_status == REF_NOT_MATCHED &&
544 !parse_oid_hex(ref->name, &oid, &p) &&
545 *p == '\0' &&
546 oideq(&oid, &ref->old_oid);
547}
548
549static void filter_refs(struct fetch_pack_args *args,
550 struct ref **refs,
551 struct ref **sought, int nr_sought)
552{
553 struct ref *newlist = NULL;
554 struct ref **newtail = &newlist;
555 struct ref *unmatched = NULL;
556 struct ref *ref, *next;
557 struct oidset tip_oids = OIDSET_INIT;
558 int i;
559 int strict = !(allow_unadvertised_object_request &
560 (ALLOW_TIP_SHA1 | ALLOW_REACHABLE_SHA1));
561
562 i = 0;
563 for (ref = *refs; ref; ref = next) {
564 int keep = 0;
565 next = ref->next;
566
567 if (starts_with(ref->name, "refs/") &&
568 check_refname_format(ref->name, 0))
569 ; /* trash */
570 else {
571 while (i < nr_sought) {
572 int cmp = strcmp(ref->name, sought[i]->name);
573 if (cmp < 0)
574 break; /* definitely do not have it */
575 else if (cmp == 0) {
576 keep = 1; /* definitely have it */
577 sought[i]->match_status = REF_MATCHED;
578 }
579 i++;
580 }
581
582 if (!keep && args->fetch_all &&
583 (!args->deepen || !starts_with(ref->name, "refs/tags/")))
584 keep = 1;
585 }
586
587 if (keep) {
588 *newtail = ref;
589 ref->next = NULL;
590 newtail = &ref->next;
591 } else {
592 ref->next = unmatched;
593 unmatched = ref;
594 }
595 }
596
597 if (strict) {
598 for (i = 0; i < nr_sought; i++) {
599 ref = sought[i];
600 if (!is_unmatched_ref(ref))
601 continue;
602
603 add_refs_to_oidset(&tip_oids, unmatched);
604 add_refs_to_oidset(&tip_oids, newlist);
605 break;
606 }
607 }
608
609 /* Append unmatched requests to the list */
610 for (i = 0; i < nr_sought; i++) {
611 ref = sought[i];
612 if (!is_unmatched_ref(ref))
613 continue;
614
615 if (!strict || oidset_contains(&tip_oids, &ref->old_oid)) {
616 ref->match_status = REF_MATCHED;
617 *newtail = copy_ref(ref);
618 newtail = &(*newtail)->next;
619 } else {
620 ref->match_status = REF_UNADVERTISED_NOT_ALLOWED;
621 }
622 }
623
624 oidset_clear(&tip_oids);
625 for (ref = unmatched; ref; ref = next) {
626 next = ref->next;
627 free(ref);
628 }
629
630 *refs = newlist;
631}
632
633static void mark_alternate_complete(struct fetch_negotiator *unused,
634 struct object *obj)
635{
636 mark_complete(&obj->oid);
637}
638
639struct loose_object_iter {
640 struct oidset *loose_object_set;
641 struct ref *refs;
642};
643
644/*
645 * If the number of refs is not larger than the number of loose objects,
646 * this function stops inserting.
647 */
648static int add_loose_objects_to_set(const struct object_id *oid,
649 const char *path,
650 void *data)
651{
652 struct loose_object_iter *iter = data;
653 oidset_insert(iter->loose_object_set, oid);
654 if (iter->refs == NULL)
655 return 1;
656
657 iter->refs = iter->refs->next;
658 return 0;
659}
660
661/*
662 * Mark recent commits available locally and reachable from a local ref as
663 * COMPLETE. If args->no_dependents is false, also mark COMPLETE remote refs as
664 * COMMON_REF (otherwise, we are not planning to participate in negotiation, and
665 * thus do not need COMMON_REF marks).
666 *
667 * The cutoff time for recency is determined by this heuristic: it is the
668 * earliest commit time of the objects in refs that are commits and that we know
669 * the commit time of.
670 */
671static void mark_complete_and_common_ref(struct fetch_negotiator *negotiator,
672 struct fetch_pack_args *args,
673 struct ref **refs)
674{
675 struct ref *ref;
676 int old_save_commit_buffer = save_commit_buffer;
677 timestamp_t cutoff = 0;
678 struct oidset loose_oid_set = OIDSET_INIT;
679 int use_oidset = 0;
680 struct loose_object_iter iter = {&loose_oid_set, *refs};
681
682 /* Enumerate all loose objects or know refs are not so many. */
683 use_oidset = !for_each_loose_object(add_loose_objects_to_set,
684 &iter, 0);
685
686 save_commit_buffer = 0;
687
688 for (ref = *refs; ref; ref = ref->next) {
689 struct object *o;
690 unsigned int flags = OBJECT_INFO_QUICK;
691
692 if (use_oidset &&
693 !oidset_contains(&loose_oid_set, &ref->old_oid)) {
694 /*
695 * I know this does not exist in the loose form,
696 * so check if it exists in a non-loose form.
697 */
698 flags |= OBJECT_INFO_IGNORE_LOOSE;
699 }
700
701 if (!has_object_file_with_flags(&ref->old_oid, flags))
702 continue;
703 o = parse_object(the_repository, &ref->old_oid);
704 if (!o)
705 continue;
706
707 /* We already have it -- which may mean that we were
708 * in sync with the other side at some time after
709 * that (it is OK if we guess wrong here).
710 */
711 if (o->type == OBJ_COMMIT) {
712 struct commit *commit = (struct commit *)o;
713 if (!cutoff || cutoff < commit->date)
714 cutoff = commit->date;
715 }
716 }
717
718 oidset_clear(&loose_oid_set);
719
720 if (!args->deepen) {
721 for_each_ref(mark_complete_oid, NULL);
722 for_each_cached_alternate(NULL, mark_alternate_complete);
723 commit_list_sort_by_date(&complete);
724 if (cutoff)
725 mark_recent_complete_commits(args, cutoff);
726 }
727
728 /*
729 * Mark all complete remote refs as common refs.
730 * Don't mark them common yet; the server has to be told so first.
731 */
732 for (ref = *refs; ref; ref = ref->next) {
733 struct object *o = deref_tag(the_repository,
734 lookup_object(the_repository,
735 ref->old_oid.hash),
736 NULL, 0);
737
738 if (!o || o->type != OBJ_COMMIT || !(o->flags & COMPLETE))
739 continue;
740
741 negotiator->known_common(negotiator,
742 (struct commit *)o);
743 }
744
745 save_commit_buffer = old_save_commit_buffer;
746}
747
748/*
749 * Returns 1 if every object pointed to by the given remote refs is available
750 * locally and reachable from a local ref, and 0 otherwise.
751 */
752static int everything_local(struct fetch_pack_args *args,
753 struct ref **refs)
754{
755 struct ref *ref;
756 int retval;
757
758 for (retval = 1, ref = *refs; ref ; ref = ref->next) {
759 const struct object_id *remote = &ref->old_oid;
760 struct object *o;
761
762 o = lookup_object(the_repository, remote->hash);
763 if (!o || !(o->flags & COMPLETE)) {
764 retval = 0;
765 print_verbose(args, "want %s (%s)", oid_to_hex(remote),
766 ref->name);
767 continue;
768 }
769 print_verbose(args, _("already have %s (%s)"), oid_to_hex(remote),
770 ref->name);
771 }
772
773 return retval;
774}
775
776static int sideband_demux(int in, int out, void *data)
777{
778 int *xd = data;
779 int ret;
780
781 ret = recv_sideband("fetch-pack", xd[0], out);
782 close(out);
783 return ret;
784}
785
786static int get_pack(struct fetch_pack_args *args,
787 int xd[2], char **pack_lockfile)
788{
789 struct async demux;
790 int do_keep = args->keep_pack;
791 const char *cmd_name;
792 struct pack_header header;
793 int pass_header = 0;
794 struct child_process cmd = CHILD_PROCESS_INIT;
795 int ret;
796
797 memset(&demux, 0, sizeof(demux));
798 if (use_sideband) {
799 /* xd[] is talking with upload-pack; subprocess reads from
800 * xd[0], spits out band#2 to stderr, and feeds us band#1
801 * through demux->out.
802 */
803 demux.proc = sideband_demux;
804 demux.data = xd;
805 demux.out = -1;
806 demux.isolate_sigpipe = 1;
807 if (start_async(&demux))
808 die(_("fetch-pack: unable to fork off sideband demultiplexer"));
809 }
810 else
811 demux.out = xd[0];
812
813 if (!args->keep_pack && unpack_limit) {
814
815 if (read_pack_header(demux.out, &header))
816 die(_("protocol error: bad pack header"));
817 pass_header = 1;
818 if (ntohl(header.hdr_entries) < unpack_limit)
819 do_keep = 0;
820 else
821 do_keep = 1;
822 }
823
824 if (alternate_shallow_file) {
825 argv_array_push(&cmd.args, "--shallow-file");
826 argv_array_push(&cmd.args, alternate_shallow_file);
827 }
828
829 if (do_keep || args->from_promisor) {
830 if (pack_lockfile)
831 cmd.out = -1;
832 cmd_name = "index-pack";
833 argv_array_push(&cmd.args, cmd_name);
834 argv_array_push(&cmd.args, "--stdin");
835 if (!args->quiet && !args->no_progress)
836 argv_array_push(&cmd.args, "-v");
837 if (args->use_thin_pack)
838 argv_array_push(&cmd.args, "--fix-thin");
839 if (do_keep && (args->lock_pack || unpack_limit)) {
840 char hostname[HOST_NAME_MAX + 1];
841 if (xgethostname(hostname, sizeof(hostname)))
842 xsnprintf(hostname, sizeof(hostname), "localhost");
843 argv_array_pushf(&cmd.args,
844 "--keep=fetch-pack %"PRIuMAX " on %s",
845 (uintmax_t)getpid(), hostname);
846 }
847 if (args->check_self_contained_and_connected)
848 argv_array_push(&cmd.args, "--check-self-contained-and-connected");
849 if (args->from_promisor)
850 argv_array_push(&cmd.args, "--promisor");
851 }
852 else {
853 cmd_name = "unpack-objects";
854 argv_array_push(&cmd.args, cmd_name);
855 if (args->quiet || args->no_progress)
856 argv_array_push(&cmd.args, "-q");
857 args->check_self_contained_and_connected = 0;
858 }
859
860 if (pass_header)
861 argv_array_pushf(&cmd.args, "--pack_header=%"PRIu32",%"PRIu32,
862 ntohl(header.hdr_version),
863 ntohl(header.hdr_entries));
864 if (fetch_fsck_objects >= 0
865 ? fetch_fsck_objects
866 : transfer_fsck_objects >= 0
867 ? transfer_fsck_objects
868 : 0) {
869 if (args->from_promisor)
870 /*
871 * We cannot use --strict in index-pack because it
872 * checks both broken objects and links, but we only
873 * want to check for broken objects.
874 */
875 argv_array_push(&cmd.args, "--fsck-objects");
876 else
877 argv_array_pushf(&cmd.args, "--strict%s",
878 fsck_msg_types.buf);
879 }
880
881 cmd.in = demux.out;
882 cmd.git_cmd = 1;
883 if (start_command(&cmd))
884 die(_("fetch-pack: unable to fork off %s"), cmd_name);
885 if (do_keep && pack_lockfile) {
886 *pack_lockfile = index_pack_lockfile(cmd.out);
887 close(cmd.out);
888 }
889
890 if (!use_sideband)
891 /* Closed by start_command() */
892 xd[0] = -1;
893
894 ret = finish_command(&cmd);
895 if (!ret || (args->check_self_contained_and_connected && ret == 1))
896 args->self_contained_and_connected =
897 args->check_self_contained_and_connected &&
898 ret == 0;
899 else
900 die(_("%s failed"), cmd_name);
901 if (use_sideband && finish_async(&demux))
902 die(_("error in sideband demultiplexer"));
903 return 0;
904}
905
906static int cmp_ref_by_name(const void *a_, const void *b_)
907{
908 const struct ref *a = *((const struct ref **)a_);
909 const struct ref *b = *((const struct ref **)b_);
910 return strcmp(a->name, b->name);
911}
912
913static struct ref *do_fetch_pack(struct fetch_pack_args *args,
914 int fd[2],
915 const struct ref *orig_ref,
916 struct ref **sought, int nr_sought,
917 struct shallow_info *si,
918 char **pack_lockfile)
919{
920 struct ref *ref = copy_ref_list(orig_ref);
921 struct object_id oid;
922 const char *agent_feature;
923 int agent_len;
924 struct fetch_negotiator negotiator;
925 fetch_negotiator_init(&negotiator, negotiation_algorithm);
926
927 sort_ref_list(&ref, ref_compare_name);
928 QSORT(sought, nr_sought, cmp_ref_by_name);
929
930 if ((args->depth > 0 || is_repository_shallow(the_repository)) && !server_supports("shallow"))
931 die(_("Server does not support shallow clients"));
932 if (args->depth > 0 || args->deepen_since || args->deepen_not)
933 args->deepen = 1;
934 if (server_supports("multi_ack_detailed")) {
935 print_verbose(args, _("Server supports multi_ack_detailed"));
936 multi_ack = 2;
937 if (server_supports("no-done")) {
938 print_verbose(args, _("Server supports no-done"));
939 if (args->stateless_rpc)
940 no_done = 1;
941 }
942 }
943 else if (server_supports("multi_ack")) {
944 print_verbose(args, _("Server supports multi_ack"));
945 multi_ack = 1;
946 }
947 if (server_supports("side-band-64k")) {
948 print_verbose(args, _("Server supports side-band-64k"));
949 use_sideband = 2;
950 }
951 else if (server_supports("side-band")) {
952 print_verbose(args, _("Server supports side-band"));
953 use_sideband = 1;
954 }
955 if (server_supports("allow-tip-sha1-in-want")) {
956 print_verbose(args, _("Server supports allow-tip-sha1-in-want"));
957 allow_unadvertised_object_request |= ALLOW_TIP_SHA1;
958 }
959 if (server_supports("allow-reachable-sha1-in-want")) {
960 print_verbose(args, _("Server supports allow-reachable-sha1-in-want"));
961 allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
962 }
963 if (!server_supports("thin-pack"))
964 args->use_thin_pack = 0;
965 if (!server_supports("no-progress"))
966 args->no_progress = 0;
967 if (!server_supports("include-tag"))
968 args->include_tag = 0;
969 if (server_supports("ofs-delta"))
970 print_verbose(args, _("Server supports ofs-delta"));
971 else
972 prefer_ofs_delta = 0;
973
974 if (server_supports("filter")) {
975 server_supports_filtering = 1;
976 print_verbose(args, _("Server supports filter"));
977 } else if (args->filter_options.choice) {
978 warning("filtering not recognized by server, ignoring");
979 }
980
981 if ((agent_feature = server_feature_value("agent", &agent_len))) {
982 agent_supported = 1;
983 if (agent_len)
984 print_verbose(args, _("Server version is %.*s"),
985 agent_len, agent_feature);
986 }
987 if (server_supports("deepen-since"))
988 deepen_since_ok = 1;
989 else if (args->deepen_since)
990 die(_("Server does not support --shallow-since"));
991 if (server_supports("deepen-not"))
992 deepen_not_ok = 1;
993 else if (args->deepen_not)
994 die(_("Server does not support --shallow-exclude"));
995 if (!server_supports("deepen-relative") && args->deepen_relative)
996 die(_("Server does not support --deepen"));
997
998 if (!args->no_dependents) {
999 mark_complete_and_common_ref(&negotiator, args, &ref);
1000 filter_refs(args, &ref, sought, nr_sought);
1001 if (everything_local(args, &ref)) {
1002 packet_flush(fd[1]);
1003 goto all_done;
1004 }
1005 } else {
1006 filter_refs(args, &ref, sought, nr_sought);
1007 }
1008 if (find_common(&negotiator, args, fd, &oid, ref) < 0)
1009 if (!args->keep_pack)
1010 /* When cloning, it is not unusual to have
1011 * no common commit.
1012 */
1013 warning(_("no common commits"));
1014
1015 if (args->stateless_rpc)
1016 packet_flush(fd[1]);
1017 if (args->deepen)
1018 setup_alternate_shallow(&shallow_lock, &alternate_shallow_file,
1019 NULL);
1020 else if (si->nr_ours || si->nr_theirs)
1021 alternate_shallow_file = setup_temporary_shallow(si->shallow);
1022 else
1023 alternate_shallow_file = NULL;
1024 if (get_pack(args, fd, pack_lockfile))
1025 die(_("git fetch-pack: fetch failed."));
1026
1027 all_done:
1028 negotiator.release(&negotiator);
1029 return ref;
1030}
1031
1032static void add_shallow_requests(struct strbuf *req_buf,
1033 const struct fetch_pack_args *args)
1034{
1035 if (is_repository_shallow(the_repository))
1036 write_shallow_commits(req_buf, 1, NULL);
1037 if (args->depth > 0)
1038 packet_buf_write(req_buf, "deepen %d", args->depth);
1039 if (args->deepen_since) {
1040 timestamp_t max_age = approxidate(args->deepen_since);
1041 packet_buf_write(req_buf, "deepen-since %"PRItime, max_age);
1042 }
1043 if (args->deepen_not) {
1044 int i;
1045 for (i = 0; i < args->deepen_not->nr; i++) {
1046 struct string_list_item *s = args->deepen_not->items + i;
1047 packet_buf_write(req_buf, "deepen-not %s", s->string);
1048 }
1049 }
1050}
1051
1052static void add_wants(int no_dependents, const struct ref *wants, struct strbuf *req_buf)
1053{
1054 int use_ref_in_want = server_supports_feature("fetch", "ref-in-want", 0);
1055
1056 for ( ; wants ; wants = wants->next) {
1057 const struct object_id *remote = &wants->old_oid;
1058 struct object *o;
1059
1060 /*
1061 * If that object is complete (i.e. it is an ancestor of a
1062 * local ref), we tell them we have it but do not have to
1063 * tell them about its ancestors, which they already know
1064 * about.
1065 *
1066 * We use lookup_object here because we are only
1067 * interested in the case we *know* the object is
1068 * reachable and we have already scanned it.
1069 *
1070 * Do this only if args->no_dependents is false (if it is true,
1071 * we cannot trust the object flags).
1072 */
1073 if (!no_dependents &&
1074 ((o = lookup_object(the_repository, remote->hash)) != NULL) &&
1075 (o->flags & COMPLETE)) {
1076 continue;
1077 }
1078
1079 if (!use_ref_in_want || wants->exact_oid)
1080 packet_buf_write(req_buf, "want %s\n", oid_to_hex(remote));
1081 else
1082 packet_buf_write(req_buf, "want-ref %s\n", wants->name);
1083 }
1084}
1085
1086static void add_common(struct strbuf *req_buf, struct oidset *common)
1087{
1088 struct oidset_iter iter;
1089 const struct object_id *oid;
1090 oidset_iter_init(common, &iter);
1091
1092 while ((oid = oidset_iter_next(&iter))) {
1093 packet_buf_write(req_buf, "have %s\n", oid_to_hex(oid));
1094 }
1095}
1096
1097static int add_haves(struct fetch_negotiator *negotiator,
1098 struct strbuf *req_buf,
1099 int *haves_to_send, int *in_vain)
1100{
1101 int ret = 0;
1102 int haves_added = 0;
1103 const struct object_id *oid;
1104
1105 while ((oid = negotiator->next(negotiator))) {
1106 packet_buf_write(req_buf, "have %s\n", oid_to_hex(oid));
1107 if (++haves_added >= *haves_to_send)
1108 break;
1109 }
1110
1111 *in_vain += haves_added;
1112 if (!haves_added || *in_vain >= MAX_IN_VAIN) {
1113 /* Send Done */
1114 packet_buf_write(req_buf, "done\n");
1115 ret = 1;
1116 }
1117
1118 /* Increase haves to send on next round */
1119 *haves_to_send = next_flush(1, *haves_to_send);
1120
1121 return ret;
1122}
1123
1124static int send_fetch_request(struct fetch_negotiator *negotiator, int fd_out,
1125 const struct fetch_pack_args *args,
1126 const struct ref *wants, struct oidset *common,
1127 int *haves_to_send, int *in_vain)
1128{
1129 int ret = 0;
1130 struct strbuf req_buf = STRBUF_INIT;
1131
1132 if (server_supports_v2("fetch", 1))
1133 packet_buf_write(&req_buf, "command=fetch");
1134 if (server_supports_v2("agent", 0))
1135 packet_buf_write(&req_buf, "agent=%s", git_user_agent_sanitized());
1136 if (args->server_options && args->server_options->nr &&
1137 server_supports_v2("server-option", 1)) {
1138 int i;
1139 for (i = 0; i < args->server_options->nr; i++)
1140 packet_write_fmt(fd_out, "server-option=%s",
1141 args->server_options->items[i].string);
1142 }
1143
1144 packet_buf_delim(&req_buf);
1145 if (args->use_thin_pack)
1146 packet_buf_write(&req_buf, "thin-pack");
1147 if (args->no_progress)
1148 packet_buf_write(&req_buf, "no-progress");
1149 if (args->include_tag)
1150 packet_buf_write(&req_buf, "include-tag");
1151 if (prefer_ofs_delta)
1152 packet_buf_write(&req_buf, "ofs-delta");
1153
1154 /* Add shallow-info and deepen request */
1155 if (server_supports_feature("fetch", "shallow", 0))
1156 add_shallow_requests(&req_buf, args);
1157 else if (is_repository_shallow(the_repository) || args->deepen)
1158 die(_("Server does not support shallow requests"));
1159
1160 /* Add filter */
1161 if (server_supports_feature("fetch", "filter", 0) &&
1162 args->filter_options.choice) {
1163 struct strbuf expanded_filter_spec = STRBUF_INIT;
1164 print_verbose(args, _("Server supports filter"));
1165 expand_list_objects_filter_spec(&args->filter_options,
1166 &expanded_filter_spec);
1167 packet_buf_write(&req_buf, "filter %s",
1168 expanded_filter_spec.buf);
1169 strbuf_release(&expanded_filter_spec);
1170 } else if (args->filter_options.choice) {
1171 warning("filtering not recognized by server, ignoring");
1172 }
1173
1174 /* add wants */
1175 add_wants(args->no_dependents, wants, &req_buf);
1176
1177 if (args->no_dependents) {
1178 packet_buf_write(&req_buf, "done");
1179 ret = 1;
1180 } else {
1181 /* Add all of the common commits we've found in previous rounds */
1182 add_common(&req_buf, common);
1183
1184 /* Add initial haves */
1185 ret = add_haves(negotiator, &req_buf, haves_to_send, in_vain);
1186 }
1187
1188 /* Send request */
1189 packet_buf_flush(&req_buf);
1190 write_or_die(fd_out, req_buf.buf, req_buf.len);
1191
1192 strbuf_release(&req_buf);
1193 return ret;
1194}
1195
1196/*
1197 * Processes a section header in a server's response and checks if it matches
1198 * `section`. If the value of `peek` is 1, the header line will be peeked (and
1199 * not consumed); if 0, the line will be consumed and the function will die if
1200 * the section header doesn't match what was expected.
1201 */
1202static int process_section_header(struct packet_reader *reader,
1203 const char *section, int peek)
1204{
1205 int ret;
1206
1207 if (packet_reader_peek(reader) != PACKET_READ_NORMAL)
1208 die(_("error reading section header '%s'"), section);
1209
1210 ret = !strcmp(reader->line, section);
1211
1212 if (!peek) {
1213 if (!ret)
1214 die(_("expected '%s', received '%s'"),
1215 section, reader->line);
1216 packet_reader_read(reader);
1217 }
1218
1219 return ret;
1220}
1221
1222static int process_acks(struct fetch_negotiator *negotiator,
1223 struct packet_reader *reader,
1224 struct oidset *common)
1225{
1226 /* received */
1227 int received_ready = 0;
1228 int received_ack = 0;
1229
1230 process_section_header(reader, "acknowledgments", 0);
1231 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1232 const char *arg;
1233
1234 if (!strcmp(reader->line, "NAK"))
1235 continue;
1236
1237 if (skip_prefix(reader->line, "ACK ", &arg)) {
1238 struct object_id oid;
1239 if (!get_oid_hex(arg, &oid)) {
1240 struct commit *commit;
1241 oidset_insert(common, &oid);
1242 commit = lookup_commit(the_repository, &oid);
1243 negotiator->ack(negotiator, commit);
1244 }
1245 continue;
1246 }
1247
1248 if (!strcmp(reader->line, "ready")) {
1249 received_ready = 1;
1250 continue;
1251 }
1252
1253 die(_("unexpected acknowledgment line: '%s'"), reader->line);
1254 }
1255
1256 if (reader->status != PACKET_READ_FLUSH &&
1257 reader->status != PACKET_READ_DELIM)
1258 die(_("error processing acks: %d"), reader->status);
1259
1260 /*
1261 * If an "acknowledgments" section is sent, a packfile is sent if and
1262 * only if "ready" was sent in this section. The other sections
1263 * ("shallow-info" and "wanted-refs") are sent only if a packfile is
1264 * sent. Therefore, a DELIM is expected if "ready" is sent, and a FLUSH
1265 * otherwise.
1266 */
1267 if (received_ready && reader->status != PACKET_READ_DELIM)
1268 die(_("expected packfile to be sent after 'ready'"));
1269 if (!received_ready && reader->status != PACKET_READ_FLUSH)
1270 die(_("expected no other sections to be sent after no 'ready'"));
1271
1272 /* return 0 if no common, 1 if there are common, or 2 if ready */
1273 return received_ready ? 2 : (received_ack ? 1 : 0);
1274}
1275
1276static void receive_shallow_info(struct fetch_pack_args *args,
1277 struct packet_reader *reader)
1278{
1279 process_section_header(reader, "shallow-info", 0);
1280 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1281 const char *arg;
1282 struct object_id oid;
1283
1284 if (skip_prefix(reader->line, "shallow ", &arg)) {
1285 if (get_oid_hex(arg, &oid))
1286 die(_("invalid shallow line: %s"), reader->line);
1287 register_shallow(the_repository, &oid);
1288 continue;
1289 }
1290 if (skip_prefix(reader->line, "unshallow ", &arg)) {
1291 if (get_oid_hex(arg, &oid))
1292 die(_("invalid unshallow line: %s"), reader->line);
1293 if (!lookup_object(the_repository, oid.hash))
1294 die(_("object not found: %s"), reader->line);
1295 /* make sure that it is parsed as shallow */
1296 if (!parse_object(the_repository, &oid))
1297 die(_("error in object: %s"), reader->line);
1298 if (unregister_shallow(&oid))
1299 die(_("no shallow found: %s"), reader->line);
1300 continue;
1301 }
1302 die(_("expected shallow/unshallow, got %s"), reader->line);
1303 }
1304
1305 if (reader->status != PACKET_READ_FLUSH &&
1306 reader->status != PACKET_READ_DELIM)
1307 die(_("error processing shallow info: %d"), reader->status);
1308
1309 setup_alternate_shallow(&shallow_lock, &alternate_shallow_file, NULL);
1310 args->deepen = 1;
1311}
1312
1313static void receive_wanted_refs(struct packet_reader *reader,
1314 struct ref **sought, int nr_sought)
1315{
1316 process_section_header(reader, "wanted-refs", 0);
1317 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
1318 struct object_id oid;
1319 const char *end;
1320 int i;
1321
1322 if (parse_oid_hex(reader->line, &oid, &end) || *end++ != ' ')
1323 die(_("expected wanted-ref, got '%s'"), reader->line);
1324
1325 for (i = 0; i < nr_sought; i++) {
1326 if (!strcmp(end, sought[i]->name)) {
1327 oidcpy(&sought[i]->old_oid, &oid);
1328 break;
1329 }
1330 }
1331
1332 if (i == nr_sought)
1333 die(_("unexpected wanted-ref: '%s'"), reader->line);
1334 }
1335
1336 if (reader->status != PACKET_READ_DELIM)
1337 die(_("error processing wanted refs: %d"), reader->status);
1338}
1339
1340enum fetch_state {
1341 FETCH_CHECK_LOCAL = 0,
1342 FETCH_SEND_REQUEST,
1343 FETCH_PROCESS_ACKS,
1344 FETCH_GET_PACK,
1345 FETCH_DONE,
1346};
1347
1348static struct ref *do_fetch_pack_v2(struct fetch_pack_args *args,
1349 int fd[2],
1350 const struct ref *orig_ref,
1351 struct ref **sought, int nr_sought,
1352 char **pack_lockfile)
1353{
1354 struct ref *ref = copy_ref_list(orig_ref);
1355 enum fetch_state state = FETCH_CHECK_LOCAL;
1356 struct oidset common = OIDSET_INIT;
1357 struct packet_reader reader;
1358 int in_vain = 0;
1359 int haves_to_send = INITIAL_FLUSH;
1360 struct fetch_negotiator negotiator;
1361 fetch_negotiator_init(&negotiator, negotiation_algorithm);
1362 packet_reader_init(&reader, fd[0], NULL, 0,
1363 PACKET_READ_CHOMP_NEWLINE);
1364
1365 while (state != FETCH_DONE) {
1366 switch (state) {
1367 case FETCH_CHECK_LOCAL:
1368 sort_ref_list(&ref, ref_compare_name);
1369 QSORT(sought, nr_sought, cmp_ref_by_name);
1370
1371 /* v2 supports these by default */
1372 allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
1373 use_sideband = 2;
1374 if (args->depth > 0 || args->deepen_since || args->deepen_not)
1375 args->deepen = 1;
1376
1377 /* Filter 'ref' by 'sought' and those that aren't local */
1378 if (!args->no_dependents) {
1379 mark_complete_and_common_ref(&negotiator, args, &ref);
1380 filter_refs(args, &ref, sought, nr_sought);
1381 if (everything_local(args, &ref))
1382 state = FETCH_DONE;
1383 else
1384 state = FETCH_SEND_REQUEST;
1385
1386 mark_tips(&negotiator, args->negotiation_tips);
1387 for_each_cached_alternate(&negotiator,
1388 insert_one_alternate_object);
1389 } else {
1390 filter_refs(args, &ref, sought, nr_sought);
1391 state = FETCH_SEND_REQUEST;
1392 }
1393 break;
1394 case FETCH_SEND_REQUEST:
1395 if (send_fetch_request(&negotiator, fd[1], args, ref,
1396 &common,
1397 &haves_to_send, &in_vain))
1398 state = FETCH_GET_PACK;
1399 else
1400 state = FETCH_PROCESS_ACKS;
1401 break;
1402 case FETCH_PROCESS_ACKS:
1403 /* Process ACKs/NAKs */
1404 switch (process_acks(&negotiator, &reader, &common)) {
1405 case 2:
1406 state = FETCH_GET_PACK;
1407 break;
1408 case 1:
1409 in_vain = 0;
1410 /* fallthrough */
1411 default:
1412 state = FETCH_SEND_REQUEST;
1413 break;
1414 }
1415 break;
1416 case FETCH_GET_PACK:
1417 /* Check for shallow-info section */
1418 if (process_section_header(&reader, "shallow-info", 1))
1419 receive_shallow_info(args, &reader);
1420
1421 if (process_section_header(&reader, "wanted-refs", 1))
1422 receive_wanted_refs(&reader, sought, nr_sought);
1423
1424 /* get the pack */
1425 process_section_header(&reader, "packfile", 0);
1426 if (get_pack(args, fd, pack_lockfile))
1427 die(_("git fetch-pack: fetch failed."));
1428
1429 state = FETCH_DONE;
1430 break;
1431 case FETCH_DONE:
1432 continue;
1433 }
1434 }
1435
1436 negotiator.release(&negotiator);
1437 oidset_clear(&common);
1438 return ref;
1439}
1440
1441static int fetch_pack_config_cb(const char *var, const char *value, void *cb)
1442{
1443 if (strcmp(var, "fetch.fsck.skiplist") == 0) {
1444 const char *path;
1445
1446 if (git_config_pathname(&path, var, value))
1447 return 1;
1448 strbuf_addf(&fsck_msg_types, "%cskiplist=%s",
1449 fsck_msg_types.len ? ',' : '=', path);
1450 free((char *)path);
1451 return 0;
1452 }
1453
1454 if (skip_prefix(var, "fetch.fsck.", &var)) {
1455 if (is_valid_msg_type(var, value))
1456 strbuf_addf(&fsck_msg_types, "%c%s=%s",
1457 fsck_msg_types.len ? ',' : '=', var, value);
1458 else
1459 warning("Skipping unknown msg id '%s'", var);
1460 return 0;
1461 }
1462
1463 return git_default_config(var, value, cb);
1464}
1465
1466static void fetch_pack_config(void)
1467{
1468 git_config_get_int("fetch.unpacklimit", &fetch_unpack_limit);
1469 git_config_get_int("transfer.unpacklimit", &transfer_unpack_limit);
1470 git_config_get_bool("repack.usedeltabaseoffset", &prefer_ofs_delta);
1471 git_config_get_bool("fetch.fsckobjects", &fetch_fsck_objects);
1472 git_config_get_bool("transfer.fsckobjects", &transfer_fsck_objects);
1473 git_config_get_string("fetch.negotiationalgorithm",
1474 &negotiation_algorithm);
1475
1476 git_config(fetch_pack_config_cb, NULL);
1477}
1478
1479static void fetch_pack_setup(void)
1480{
1481 static int did_setup;
1482 if (did_setup)
1483 return;
1484 fetch_pack_config();
1485 if (0 <= transfer_unpack_limit)
1486 unpack_limit = transfer_unpack_limit;
1487 else if (0 <= fetch_unpack_limit)
1488 unpack_limit = fetch_unpack_limit;
1489 did_setup = 1;
1490}
1491
1492static int remove_duplicates_in_refs(struct ref **ref, int nr)
1493{
1494 struct string_list names = STRING_LIST_INIT_NODUP;
1495 int src, dst;
1496
1497 for (src = dst = 0; src < nr; src++) {
1498 struct string_list_item *item;
1499 item = string_list_insert(&names, ref[src]->name);
1500 if (item->util)
1501 continue; /* already have it */
1502 item->util = ref[src];
1503 if (src != dst)
1504 ref[dst] = ref[src];
1505 dst++;
1506 }
1507 for (src = dst; src < nr; src++)
1508 ref[src] = NULL;
1509 string_list_clear(&names, 0);
1510 return dst;
1511}
1512
1513static void update_shallow(struct fetch_pack_args *args,
1514 struct ref **sought, int nr_sought,
1515 struct shallow_info *si)
1516{
1517 struct oid_array ref = OID_ARRAY_INIT;
1518 int *status;
1519 int i;
1520
1521 if (args->deepen && alternate_shallow_file) {
1522 if (*alternate_shallow_file == '\0') { /* --unshallow */
1523 unlink_or_warn(git_path_shallow(the_repository));
1524 rollback_lock_file(&shallow_lock);
1525 } else
1526 commit_lock_file(&shallow_lock);
1527 return;
1528 }
1529
1530 if (!si->shallow || !si->shallow->nr)
1531 return;
1532
1533 if (args->cloning) {
1534 /*
1535 * remote is shallow, but this is a clone, there are
1536 * no objects in repo to worry about. Accept any
1537 * shallow points that exist in the pack (iow in repo
1538 * after get_pack() and reprepare_packed_git())
1539 */
1540 struct oid_array extra = OID_ARRAY_INIT;
1541 struct object_id *oid = si->shallow->oid;
1542 for (i = 0; i < si->shallow->nr; i++)
1543 if (has_object_file(&oid[i]))
1544 oid_array_append(&extra, &oid[i]);
1545 if (extra.nr) {
1546 setup_alternate_shallow(&shallow_lock,
1547 &alternate_shallow_file,
1548 &extra);
1549 commit_lock_file(&shallow_lock);
1550 }
1551 oid_array_clear(&extra);
1552 return;
1553 }
1554
1555 if (!si->nr_ours && !si->nr_theirs)
1556 return;
1557
1558 remove_nonexistent_theirs_shallow(si);
1559 if (!si->nr_ours && !si->nr_theirs)
1560 return;
1561 for (i = 0; i < nr_sought; i++)
1562 oid_array_append(&ref, &sought[i]->old_oid);
1563 si->ref = &ref;
1564
1565 if (args->update_shallow) {
1566 /*
1567 * remote is also shallow, .git/shallow may be updated
1568 * so all refs can be accepted. Make sure we only add
1569 * shallow roots that are actually reachable from new
1570 * refs.
1571 */
1572 struct oid_array extra = OID_ARRAY_INIT;
1573 struct object_id *oid = si->shallow->oid;
1574 assign_shallow_commits_to_refs(si, NULL, NULL);
1575 if (!si->nr_ours && !si->nr_theirs) {
1576 oid_array_clear(&ref);
1577 return;
1578 }
1579 for (i = 0; i < si->nr_ours; i++)
1580 oid_array_append(&extra, &oid[si->ours[i]]);
1581 for (i = 0; i < si->nr_theirs; i++)
1582 oid_array_append(&extra, &oid[si->theirs[i]]);
1583 setup_alternate_shallow(&shallow_lock,
1584 &alternate_shallow_file,
1585 &extra);
1586 commit_lock_file(&shallow_lock);
1587 oid_array_clear(&extra);
1588 oid_array_clear(&ref);
1589 return;
1590 }
1591
1592 /*
1593 * remote is also shallow, check what ref is safe to update
1594 * without updating .git/shallow
1595 */
1596 status = xcalloc(nr_sought, sizeof(*status));
1597 assign_shallow_commits_to_refs(si, NULL, status);
1598 if (si->nr_ours || si->nr_theirs) {
1599 for (i = 0; i < nr_sought; i++)
1600 if (status[i])
1601 sought[i]->status = REF_STATUS_REJECT_SHALLOW;
1602 }
1603 free(status);
1604 oid_array_clear(&ref);
1605}
1606
1607static int iterate_ref_map(void *cb_data, struct object_id *oid)
1608{
1609 struct ref **rm = cb_data;
1610 struct ref *ref = *rm;
1611
1612 if (!ref)
1613 return -1; /* end of the list */
1614 *rm = ref->next;
1615 oidcpy(oid, &ref->old_oid);
1616 return 0;
1617}
1618
1619struct ref *fetch_pack(struct fetch_pack_args *args,
1620 int fd[], struct child_process *conn,
1621 const struct ref *ref,
1622 const char *dest,
1623 struct ref **sought, int nr_sought,
1624 struct oid_array *shallow,
1625 char **pack_lockfile,
1626 enum protocol_version version)
1627{
1628 struct ref *ref_cpy;
1629 struct shallow_info si;
1630
1631 fetch_pack_setup();
1632 if (nr_sought)
1633 nr_sought = remove_duplicates_in_refs(sought, nr_sought);
1634
1635 if (args->no_dependents && !args->filter_options.choice) {
1636 /*
1637 * The protocol does not support requesting that only the
1638 * wanted objects be sent, so approximate this by setting a
1639 * "blob:none" filter if no filter is already set. This works
1640 * for all object types: note that wanted blobs will still be
1641 * sent because they are directly specified as a "want".
1642 *
1643 * NEEDSWORK: Add an option in the protocol to request that
1644 * only the wanted objects be sent, and implement it.
1645 */
1646 parse_list_objects_filter(&args->filter_options, "blob:none");
1647 }
1648
1649 if (version != protocol_v2 && !ref) {
1650 packet_flush(fd[1]);
1651 die(_("no matching remote head"));
1652 }
1653 prepare_shallow_info(&si, shallow);
1654 if (version == protocol_v2)
1655 ref_cpy = do_fetch_pack_v2(args, fd, ref, sought, nr_sought,
1656 pack_lockfile);
1657 else
1658 ref_cpy = do_fetch_pack(args, fd, ref, sought, nr_sought,
1659 &si, pack_lockfile);
1660 reprepare_packed_git(the_repository);
1661
1662 if (!args->cloning && args->deepen) {
1663 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1664 struct ref *iterator = ref_cpy;
1665 opt.shallow_file = alternate_shallow_file;
1666 if (args->deepen)
1667 opt.is_deepening_fetch = 1;
1668 if (check_connected(iterate_ref_map, &iterator, &opt)) {
1669 error(_("remote did not send all necessary objects"));
1670 free_refs(ref_cpy);
1671 ref_cpy = NULL;
1672 rollback_lock_file(&shallow_lock);
1673 goto cleanup;
1674 }
1675 args->connectivity_checked = 1;
1676 }
1677
1678 update_shallow(args, sought, nr_sought, &si);
1679cleanup:
1680 clear_shallow_info(&si);
1681 return ref_cpy;
1682}
1683
1684int report_unmatched_refs(struct ref **sought, int nr_sought)
1685{
1686 int i, ret = 0;
1687
1688 for (i = 0; i < nr_sought; i++) {
1689 if (!sought[i])
1690 continue;
1691 switch (sought[i]->match_status) {
1692 case REF_MATCHED:
1693 continue;
1694 case REF_NOT_MATCHED:
1695 error(_("no such remote ref %s"), sought[i]->name);
1696 break;
1697 case REF_UNADVERTISED_NOT_ALLOWED:
1698 error(_("Server does not allow request for unadvertised object %s"),
1699 sought[i]->name);
1700 break;
1701 }
1702 ret = 1;
1703 }
1704 return ret;
1705}