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