Merge branch 'jk/fetch-reachability-error-fix'
[git] / transport.c
1 #include "cache.h"
2 #include "config.h"
3 #include "transport.h"
4 #include "run-command.h"
5 #include "pkt-line.h"
6 #include "fetch-pack.h"
7 #include "remote.h"
8 #include "connect.h"
9 #include "send-pack.h"
10 #include "walker.h"
11 #include "bundle.h"
12 #include "dir.h"
13 #include "refs.h"
14 #include "refspec.h"
15 #include "branch.h"
16 #include "url.h"
17 #include "submodule.h"
18 #include "string-list.h"
19 #include "sha1-array.h"
20 #include "sigchain.h"
21 #include "transport-internal.h"
22 #include "protocol.h"
23 #include "object-store.h"
24 #include "color.h"
25
26 static int transport_use_color = -1;
27 static char transport_colors[][COLOR_MAXLEN] = {
28         GIT_COLOR_RESET,
29         GIT_COLOR_RED           /* REJECTED */
30 };
31
32 enum color_transport {
33         TRANSPORT_COLOR_RESET = 0,
34         TRANSPORT_COLOR_REJECTED = 1
35 };
36
37 static int transport_color_config(void)
38 {
39         const char *keys[] = {
40                 "color.transport.reset",
41                 "color.transport.rejected"
42         }, *key = "color.transport";
43         char *value;
44         int i;
45         static int initialized;
46
47         if (initialized)
48                 return 0;
49         initialized = 1;
50
51         if (!git_config_get_string(key, &value))
52                 transport_use_color = git_config_colorbool(key, value);
53
54         if (!want_color_stderr(transport_use_color))
55                 return 0;
56
57         for (i = 0; i < ARRAY_SIZE(keys); i++)
58                 if (!git_config_get_string(keys[i], &value)) {
59                         if (!value)
60                                 return config_error_nonbool(keys[i]);
61                         if (color_parse(value, transport_colors[i]) < 0)
62                                 return -1;
63                 }
64
65         return 0;
66 }
67
68 static const char *transport_get_color(enum color_transport ix)
69 {
70         if (want_color_stderr(transport_use_color))
71                 return transport_colors[ix];
72         return "";
73 }
74
75 static void set_upstreams(struct transport *transport, struct ref *refs,
76         int pretend)
77 {
78         struct ref *ref;
79         for (ref = refs; ref; ref = ref->next) {
80                 const char *localname;
81                 const char *tmp;
82                 const char *remotename;
83                 int flag = 0;
84                 /*
85                  * Check suitability for tracking. Must be successful /
86                  * already up-to-date ref create/modify (not delete).
87                  */
88                 if (ref->status != REF_STATUS_OK &&
89                         ref->status != REF_STATUS_UPTODATE)
90                         continue;
91                 if (!ref->peer_ref)
92                         continue;
93                 if (is_null_oid(&ref->new_oid))
94                         continue;
95
96                 /* Follow symbolic refs (mainly for HEAD). */
97                 localname = ref->peer_ref->name;
98                 remotename = ref->name;
99                 tmp = resolve_ref_unsafe(localname, RESOLVE_REF_READING,
100                                          NULL, &flag);
101                 if (tmp && flag & REF_ISSYMREF &&
102                         starts_with(tmp, "refs/heads/"))
103                         localname = tmp;
104
105                 /* Both source and destination must be local branches. */
106                 if (!localname || !starts_with(localname, "refs/heads/"))
107                         continue;
108                 if (!remotename || !starts_with(remotename, "refs/heads/"))
109                         continue;
110
111                 if (!pretend)
112                         install_branch_config(BRANCH_CONFIG_VERBOSE,
113                                 localname + 11, transport->remote->name,
114                                 remotename);
115                 else
116                         printf(_("Would set upstream of '%s' to '%s' of '%s'\n"),
117                                 localname + 11, remotename + 11,
118                                 transport->remote->name);
119         }
120 }
121
122 struct bundle_transport_data {
123         int fd;
124         struct bundle_header header;
125 };
126
127 static struct ref *get_refs_from_bundle(struct transport *transport,
128                                         int for_push,
129                                         const struct argv_array *ref_prefixes)
130 {
131         struct bundle_transport_data *data = transport->data;
132         struct ref *result = NULL;
133         int i;
134
135         if (for_push)
136                 return NULL;
137
138         if (data->fd > 0)
139                 close(data->fd);
140         data->fd = read_bundle_header(transport->url, &data->header);
141         if (data->fd < 0)
142                 die(_("could not read bundle '%s'"), transport->url);
143         for (i = 0; i < data->header.references.nr; i++) {
144                 struct ref_list_entry *e = data->header.references.list + i;
145                 struct ref *ref = alloc_ref(e->name);
146                 oidcpy(&ref->old_oid, &e->oid);
147                 ref->next = result;
148                 result = ref;
149         }
150         return result;
151 }
152
153 static int fetch_refs_from_bundle(struct transport *transport,
154                                int nr_heads, struct ref **to_fetch)
155 {
156         struct bundle_transport_data *data = transport->data;
157         return unbundle(the_repository, &data->header, data->fd,
158                         transport->progress ? BUNDLE_VERBOSE : 0);
159 }
160
161 static int close_bundle(struct transport *transport)
162 {
163         struct bundle_transport_data *data = transport->data;
164         if (data->fd > 0)
165                 close(data->fd);
166         free(data);
167         return 0;
168 }
169
170 struct git_transport_data {
171         struct git_transport_options options;
172         struct child_process *conn;
173         int fd[2];
174         unsigned got_remote_heads : 1;
175         enum protocol_version version;
176         struct oid_array extra_have;
177         struct oid_array shallow;
178 };
179
180 static int set_git_option(struct git_transport_options *opts,
181                           const char *name, const char *value)
182 {
183         if (!strcmp(name, TRANS_OPT_UPLOADPACK)) {
184                 opts->uploadpack = value;
185                 return 0;
186         } else if (!strcmp(name, TRANS_OPT_RECEIVEPACK)) {
187                 opts->receivepack = value;
188                 return 0;
189         } else if (!strcmp(name, TRANS_OPT_THIN)) {
190                 opts->thin = !!value;
191                 return 0;
192         } else if (!strcmp(name, TRANS_OPT_FOLLOWTAGS)) {
193                 opts->followtags = !!value;
194                 return 0;
195         } else if (!strcmp(name, TRANS_OPT_KEEP)) {
196                 opts->keep = !!value;
197                 return 0;
198         } else if (!strcmp(name, TRANS_OPT_UPDATE_SHALLOW)) {
199                 opts->update_shallow = !!value;
200                 return 0;
201         } else if (!strcmp(name, TRANS_OPT_DEPTH)) {
202                 if (!value)
203                         opts->depth = 0;
204                 else {
205                         char *end;
206                         opts->depth = strtol(value, &end, 0);
207                         if (*end)
208                                 die(_("transport: invalid depth option '%s'"), value);
209                 }
210                 return 0;
211         } else if (!strcmp(name, TRANS_OPT_DEEPEN_SINCE)) {
212                 opts->deepen_since = value;
213                 return 0;
214         } else if (!strcmp(name, TRANS_OPT_DEEPEN_NOT)) {
215                 opts->deepen_not = (const struct string_list *)value;
216                 return 0;
217         } else if (!strcmp(name, TRANS_OPT_DEEPEN_RELATIVE)) {
218                 opts->deepen_relative = !!value;
219                 return 0;
220         } else if (!strcmp(name, TRANS_OPT_FROM_PROMISOR)) {
221                 opts->from_promisor = !!value;
222                 return 0;
223         } else if (!strcmp(name, TRANS_OPT_NO_DEPENDENTS)) {
224                 opts->no_dependents = !!value;
225                 return 0;
226         } else if (!strcmp(name, TRANS_OPT_LIST_OBJECTS_FILTER)) {
227                 parse_list_objects_filter(&opts->filter_options, value);
228                 return 0;
229         }
230         return 1;
231 }
232
233 static int connect_setup(struct transport *transport, int for_push)
234 {
235         struct git_transport_data *data = transport->data;
236         int flags = transport->verbose > 0 ? CONNECT_VERBOSE : 0;
237
238         if (data->conn)
239                 return 0;
240
241         switch (transport->family) {
242         case TRANSPORT_FAMILY_ALL: break;
243         case TRANSPORT_FAMILY_IPV4: flags |= CONNECT_IPV4; break;
244         case TRANSPORT_FAMILY_IPV6: flags |= CONNECT_IPV6; break;
245         }
246
247         data->conn = git_connect(data->fd, transport->url,
248                                  for_push ? data->options.receivepack :
249                                  data->options.uploadpack,
250                                  flags);
251
252         return 0;
253 }
254
255 /*
256  * Obtains the protocol version from the transport and writes it to
257  * transport->data->version, first connecting if not already connected.
258  *
259  * If the protocol version is one that allows skipping the listing of remote
260  * refs, and must_list_refs is 0, the listing of remote refs is skipped and
261  * this function returns NULL. Otherwise, this function returns the list of
262  * remote refs.
263  */
264 static struct ref *handshake(struct transport *transport, int for_push,
265                              const struct argv_array *ref_prefixes,
266                              int must_list_refs)
267 {
268         struct git_transport_data *data = transport->data;
269         struct ref *refs = NULL;
270         struct packet_reader reader;
271
272         connect_setup(transport, for_push);
273
274         packet_reader_init(&reader, data->fd[0], NULL, 0,
275                            PACKET_READ_CHOMP_NEWLINE |
276                            PACKET_READ_GENTLE_ON_EOF |
277                            PACKET_READ_DIE_ON_ERR_PACKET);
278
279         data->version = discover_version(&reader);
280         switch (data->version) {
281         case protocol_v2:
282                 if (must_list_refs)
283                         get_remote_refs(data->fd[1], &reader, &refs, for_push,
284                                         ref_prefixes,
285                                         transport->server_options);
286                 break;
287         case protocol_v1:
288         case protocol_v0:
289                 get_remote_heads(&reader, &refs,
290                                  for_push ? REF_NORMAL : 0,
291                                  &data->extra_have,
292                                  &data->shallow);
293                 break;
294         case protocol_unknown_version:
295                 BUG("unknown protocol version");
296         }
297         data->got_remote_heads = 1;
298
299         if (reader.line_peeked)
300                 BUG("buffer must be empty at the end of handshake()");
301
302         return refs;
303 }
304
305 static struct ref *get_refs_via_connect(struct transport *transport, int for_push,
306                                         const struct argv_array *ref_prefixes)
307 {
308         return handshake(transport, for_push, ref_prefixes, 1);
309 }
310
311 static int fetch_refs_via_pack(struct transport *transport,
312                                int nr_heads, struct ref **to_fetch)
313 {
314         int ret = 0;
315         struct git_transport_data *data = transport->data;
316         struct ref *refs = NULL;
317         struct fetch_pack_args args;
318         struct ref *refs_tmp = NULL;
319
320         memset(&args, 0, sizeof(args));
321         args.uploadpack = data->options.uploadpack;
322         args.keep_pack = data->options.keep;
323         args.lock_pack = 1;
324         args.use_thin_pack = data->options.thin;
325         args.include_tag = data->options.followtags;
326         args.verbose = (transport->verbose > 1);
327         args.quiet = (transport->verbose < 0);
328         args.no_progress = !transport->progress;
329         args.depth = data->options.depth;
330         args.deepen_since = data->options.deepen_since;
331         args.deepen_not = data->options.deepen_not;
332         args.deepen_relative = data->options.deepen_relative;
333         args.check_self_contained_and_connected =
334                 data->options.check_self_contained_and_connected;
335         args.cloning = transport->cloning;
336         args.update_shallow = data->options.update_shallow;
337         args.from_promisor = data->options.from_promisor;
338         args.no_dependents = data->options.no_dependents;
339         args.filter_options = data->options.filter_options;
340         args.stateless_rpc = transport->stateless_rpc;
341         args.server_options = transport->server_options;
342         args.negotiation_tips = data->options.negotiation_tips;
343
344         if (!data->got_remote_heads) {
345                 int i;
346                 int must_list_refs = 0;
347                 for (i = 0; i < nr_heads; i++) {
348                         if (!to_fetch[i]->exact_oid) {
349                                 must_list_refs = 1;
350                                 break;
351                         }
352                 }
353                 refs_tmp = handshake(transport, 0, NULL, must_list_refs);
354         }
355
356         switch (data->version) {
357         case protocol_v2:
358                 refs = fetch_pack(&args, data->fd,
359                                   refs_tmp ? refs_tmp : transport->remote_refs,
360                                   to_fetch, nr_heads, &data->shallow,
361                                   &transport->pack_lockfile, data->version);
362                 break;
363         case protocol_v1:
364         case protocol_v0:
365                 refs = fetch_pack(&args, data->fd,
366                                   refs_tmp ? refs_tmp : transport->remote_refs,
367                                   to_fetch, nr_heads, &data->shallow,
368                                   &transport->pack_lockfile, data->version);
369                 break;
370         case protocol_unknown_version:
371                 BUG("unknown protocol version");
372         }
373
374         close(data->fd[0]);
375         close(data->fd[1]);
376         if (finish_connect(data->conn))
377                 ret = -1;
378         data->conn = NULL;
379         data->got_remote_heads = 0;
380         data->options.self_contained_and_connected =
381                 args.self_contained_and_connected;
382         data->options.connectivity_checked = args.connectivity_checked;
383
384         if (refs == NULL)
385                 ret = -1;
386         if (report_unmatched_refs(to_fetch, nr_heads))
387                 ret = -1;
388
389         free_refs(refs_tmp);
390         free_refs(refs);
391         return ret;
392 }
393
394 static int push_had_errors(struct ref *ref)
395 {
396         for (; ref; ref = ref->next) {
397                 switch (ref->status) {
398                 case REF_STATUS_NONE:
399                 case REF_STATUS_UPTODATE:
400                 case REF_STATUS_OK:
401                         break;
402                 default:
403                         return 1;
404                 }
405         }
406         return 0;
407 }
408
409 int transport_refs_pushed(struct ref *ref)
410 {
411         for (; ref; ref = ref->next) {
412                 switch(ref->status) {
413                 case REF_STATUS_NONE:
414                 case REF_STATUS_UPTODATE:
415                         break;
416                 default:
417                         return 1;
418                 }
419         }
420         return 0;
421 }
422
423 void transport_update_tracking_ref(struct remote *remote, struct ref *ref, int verbose)
424 {
425         struct refspec_item rs;
426
427         if (ref->status != REF_STATUS_OK && ref->status != REF_STATUS_UPTODATE)
428                 return;
429
430         rs.src = ref->name;
431         rs.dst = NULL;
432
433         if (!remote_find_tracking(remote, &rs)) {
434                 if (verbose)
435                         fprintf(stderr, "updating local tracking ref '%s'\n", rs.dst);
436                 if (ref->deletion) {
437                         delete_ref(NULL, rs.dst, NULL, 0);
438                 } else
439                         update_ref("update by push", rs.dst, &ref->new_oid,
440                                    NULL, 0, 0);
441                 free(rs.dst);
442         }
443 }
444
445 static void print_ref_status(char flag, const char *summary,
446                              struct ref *to, struct ref *from, const char *msg,
447                              int porcelain, int summary_width)
448 {
449         if (porcelain) {
450                 if (from)
451                         fprintf(stdout, "%c\t%s:%s\t", flag, from->name, to->name);
452                 else
453                         fprintf(stdout, "%c\t:%s\t", flag, to->name);
454                 if (msg)
455                         fprintf(stdout, "%s (%s)\n", summary, msg);
456                 else
457                         fprintf(stdout, "%s\n", summary);
458         } else {
459                 const char *red = "", *reset = "";
460                 if (push_had_errors(to)) {
461                         red = transport_get_color(TRANSPORT_COLOR_REJECTED);
462                         reset = transport_get_color(TRANSPORT_COLOR_RESET);
463                 }
464                 fprintf(stderr, " %s%c %-*s%s ", red, flag, summary_width,
465                         summary, reset);
466                 if (from)
467                         fprintf(stderr, "%s -> %s", prettify_refname(from->name), prettify_refname(to->name));
468                 else
469                         fputs(prettify_refname(to->name), stderr);
470                 if (msg) {
471                         fputs(" (", stderr);
472                         fputs(msg, stderr);
473                         fputc(')', stderr);
474                 }
475                 fputc('\n', stderr);
476         }
477 }
478
479 static void print_ok_ref_status(struct ref *ref, int porcelain, int summary_width)
480 {
481         if (ref->deletion)
482                 print_ref_status('-', "[deleted]", ref, NULL, NULL,
483                                  porcelain, summary_width);
484         else if (is_null_oid(&ref->old_oid))
485                 print_ref_status('*',
486                         (starts_with(ref->name, "refs/tags/") ? "[new tag]" :
487                         "[new branch]"),
488                         ref, ref->peer_ref, NULL, porcelain, summary_width);
489         else {
490                 struct strbuf quickref = STRBUF_INIT;
491                 char type;
492                 const char *msg;
493
494                 strbuf_add_unique_abbrev(&quickref, &ref->old_oid,
495                                          DEFAULT_ABBREV);
496                 if (ref->forced_update) {
497                         strbuf_addstr(&quickref, "...");
498                         type = '+';
499                         msg = "forced update";
500                 } else {
501                         strbuf_addstr(&quickref, "..");
502                         type = ' ';
503                         msg = NULL;
504                 }
505                 strbuf_add_unique_abbrev(&quickref, &ref->new_oid,
506                                          DEFAULT_ABBREV);
507
508                 print_ref_status(type, quickref.buf, ref, ref->peer_ref, msg,
509                                  porcelain, summary_width);
510                 strbuf_release(&quickref);
511         }
512 }
513
514 static int print_one_push_status(struct ref *ref, const char *dest, int count,
515                                  int porcelain, int summary_width)
516 {
517         if (!count) {
518                 char *url = transport_anonymize_url(dest);
519                 fprintf(porcelain ? stdout : stderr, "To %s\n", url);
520                 free(url);
521         }
522
523         switch(ref->status) {
524         case REF_STATUS_NONE:
525                 print_ref_status('X', "[no match]", ref, NULL, NULL,
526                                  porcelain, summary_width);
527                 break;
528         case REF_STATUS_REJECT_NODELETE:
529                 print_ref_status('!', "[rejected]", ref, NULL,
530                                  "remote does not support deleting refs",
531                                  porcelain, summary_width);
532                 break;
533         case REF_STATUS_UPTODATE:
534                 print_ref_status('=', "[up to date]", ref,
535                                  ref->peer_ref, NULL, porcelain, summary_width);
536                 break;
537         case REF_STATUS_REJECT_NONFASTFORWARD:
538                 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
539                                  "non-fast-forward", porcelain, summary_width);
540                 break;
541         case REF_STATUS_REJECT_ALREADY_EXISTS:
542                 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
543                                  "already exists", porcelain, summary_width);
544                 break;
545         case REF_STATUS_REJECT_FETCH_FIRST:
546                 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
547                                  "fetch first", porcelain, summary_width);
548                 break;
549         case REF_STATUS_REJECT_NEEDS_FORCE:
550                 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
551                                  "needs force", porcelain, summary_width);
552                 break;
553         case REF_STATUS_REJECT_STALE:
554                 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
555                                  "stale info", porcelain, summary_width);
556                 break;
557         case REF_STATUS_REJECT_SHALLOW:
558                 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
559                                  "new shallow roots not allowed",
560                                  porcelain, summary_width);
561                 break;
562         case REF_STATUS_REMOTE_REJECT:
563                 print_ref_status('!', "[remote rejected]", ref,
564                                  ref->deletion ? NULL : ref->peer_ref,
565                                  ref->remote_status, porcelain, summary_width);
566                 break;
567         case REF_STATUS_EXPECTING_REPORT:
568                 print_ref_status('!', "[remote failure]", ref,
569                                  ref->deletion ? NULL : ref->peer_ref,
570                                  "remote failed to report status",
571                                  porcelain, summary_width);
572                 break;
573         case REF_STATUS_ATOMIC_PUSH_FAILED:
574                 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
575                                  "atomic push failed", porcelain, summary_width);
576                 break;
577         case REF_STATUS_OK:
578                 print_ok_ref_status(ref, porcelain, summary_width);
579                 break;
580         }
581
582         return 1;
583 }
584
585 static int measure_abbrev(const struct object_id *oid, int sofar)
586 {
587         char hex[GIT_MAX_HEXSZ + 1];
588         int w = find_unique_abbrev_r(hex, oid, DEFAULT_ABBREV);
589
590         return (w < sofar) ? sofar : w;
591 }
592
593 int transport_summary_width(const struct ref *refs)
594 {
595         int maxw = -1;
596
597         for (; refs; refs = refs->next) {
598                 maxw = measure_abbrev(&refs->old_oid, maxw);
599                 maxw = measure_abbrev(&refs->new_oid, maxw);
600         }
601         if (maxw < 0)
602                 maxw = FALLBACK_DEFAULT_ABBREV;
603         return (2 * maxw + 3);
604 }
605
606 void transport_print_push_status(const char *dest, struct ref *refs,
607                                   int verbose, int porcelain, unsigned int *reject_reasons)
608 {
609         struct ref *ref;
610         int n = 0;
611         char *head;
612         int summary_width = transport_summary_width(refs);
613
614         if (transport_color_config() < 0)
615                 warning(_("could not parse transport.color.* config"));
616
617         head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
618
619         if (verbose) {
620                 for (ref = refs; ref; ref = ref->next)
621                         if (ref->status == REF_STATUS_UPTODATE)
622                                 n += print_one_push_status(ref, dest, n,
623                                                            porcelain, summary_width);
624         }
625
626         for (ref = refs; ref; ref = ref->next)
627                 if (ref->status == REF_STATUS_OK)
628                         n += print_one_push_status(ref, dest, n,
629                                                    porcelain, summary_width);
630
631         *reject_reasons = 0;
632         for (ref = refs; ref; ref = ref->next) {
633                 if (ref->status != REF_STATUS_NONE &&
634                     ref->status != REF_STATUS_UPTODATE &&
635                     ref->status != REF_STATUS_OK)
636                         n += print_one_push_status(ref, dest, n,
637                                                    porcelain, summary_width);
638                 if (ref->status == REF_STATUS_REJECT_NONFASTFORWARD) {
639                         if (head != NULL && !strcmp(head, ref->name))
640                                 *reject_reasons |= REJECT_NON_FF_HEAD;
641                         else
642                                 *reject_reasons |= REJECT_NON_FF_OTHER;
643                 } else if (ref->status == REF_STATUS_REJECT_ALREADY_EXISTS) {
644                         *reject_reasons |= REJECT_ALREADY_EXISTS;
645                 } else if (ref->status == REF_STATUS_REJECT_FETCH_FIRST) {
646                         *reject_reasons |= REJECT_FETCH_FIRST;
647                 } else if (ref->status == REF_STATUS_REJECT_NEEDS_FORCE) {
648                         *reject_reasons |= REJECT_NEEDS_FORCE;
649                 }
650         }
651         free(head);
652 }
653
654 static int git_transport_push(struct transport *transport, struct ref *remote_refs, int flags)
655 {
656         struct git_transport_data *data = transport->data;
657         struct send_pack_args args;
658         int ret = 0;
659
660         if (transport_color_config() < 0)
661                 return -1;
662
663         if (!data->got_remote_heads)
664                 get_refs_via_connect(transport, 1, NULL);
665
666         memset(&args, 0, sizeof(args));
667         args.send_mirror = !!(flags & TRANSPORT_PUSH_MIRROR);
668         args.force_update = !!(flags & TRANSPORT_PUSH_FORCE);
669         args.use_thin_pack = data->options.thin;
670         args.verbose = (transport->verbose > 0);
671         args.quiet = (transport->verbose < 0);
672         args.progress = transport->progress;
673         args.dry_run = !!(flags & TRANSPORT_PUSH_DRY_RUN);
674         args.porcelain = !!(flags & TRANSPORT_PUSH_PORCELAIN);
675         args.atomic = !!(flags & TRANSPORT_PUSH_ATOMIC);
676         args.push_options = transport->push_options;
677         args.url = transport->url;
678
679         if (flags & TRANSPORT_PUSH_CERT_ALWAYS)
680                 args.push_cert = SEND_PACK_PUSH_CERT_ALWAYS;
681         else if (flags & TRANSPORT_PUSH_CERT_IF_ASKED)
682                 args.push_cert = SEND_PACK_PUSH_CERT_IF_ASKED;
683         else
684                 args.push_cert = SEND_PACK_PUSH_CERT_NEVER;
685
686         switch (data->version) {
687         case protocol_v2:
688                 die(_("support for protocol v2 not implemented yet"));
689                 break;
690         case protocol_v1:
691         case protocol_v0:
692                 ret = send_pack(&args, data->fd, data->conn, remote_refs,
693                                 &data->extra_have);
694                 break;
695         case protocol_unknown_version:
696                 BUG("unknown protocol version");
697         }
698
699         close(data->fd[1]);
700         close(data->fd[0]);
701         ret |= finish_connect(data->conn);
702         data->conn = NULL;
703         data->got_remote_heads = 0;
704
705         return ret;
706 }
707
708 static int connect_git(struct transport *transport, const char *name,
709                        const char *executable, int fd[2])
710 {
711         struct git_transport_data *data = transport->data;
712         data->conn = git_connect(data->fd, transport->url,
713                                  executable, 0);
714         fd[0] = data->fd[0];
715         fd[1] = data->fd[1];
716         return 0;
717 }
718
719 static int disconnect_git(struct transport *transport)
720 {
721         struct git_transport_data *data = transport->data;
722         if (data->conn) {
723                 if (data->got_remote_heads)
724                         packet_flush(data->fd[1]);
725                 close(data->fd[0]);
726                 close(data->fd[1]);
727                 finish_connect(data->conn);
728         }
729
730         free(data);
731         return 0;
732 }
733
734 static struct transport_vtable taken_over_vtable = {
735         1,
736         NULL,
737         get_refs_via_connect,
738         fetch_refs_via_pack,
739         git_transport_push,
740         NULL,
741         disconnect_git
742 };
743
744 void transport_take_over(struct transport *transport,
745                          struct child_process *child)
746 {
747         struct git_transport_data *data;
748
749         if (!transport->smart_options)
750                 BUG("taking over transport requires non-NULL "
751                     "smart_options field.");
752
753         data = xcalloc(1, sizeof(*data));
754         data->options = *transport->smart_options;
755         data->conn = child;
756         data->fd[0] = data->conn->out;
757         data->fd[1] = data->conn->in;
758         data->got_remote_heads = 0;
759         transport->data = data;
760
761         transport->vtable = &taken_over_vtable;
762         transport->smart_options = &(data->options);
763
764         transport->cannot_reuse = 1;
765 }
766
767 static int is_file(const char *url)
768 {
769         struct stat buf;
770         if (stat(url, &buf))
771                 return 0;
772         return S_ISREG(buf.st_mode);
773 }
774
775 static int external_specification_len(const char *url)
776 {
777         return strchr(url, ':') - url;
778 }
779
780 static const struct string_list *protocol_whitelist(void)
781 {
782         static int enabled = -1;
783         static struct string_list allowed = STRING_LIST_INIT_DUP;
784
785         if (enabled < 0) {
786                 const char *v = getenv("GIT_ALLOW_PROTOCOL");
787                 if (v) {
788                         string_list_split(&allowed, v, ':', -1);
789                         string_list_sort(&allowed);
790                         enabled = 1;
791                 } else {
792                         enabled = 0;
793                 }
794         }
795
796         return enabled ? &allowed : NULL;
797 }
798
799 enum protocol_allow_config {
800         PROTOCOL_ALLOW_NEVER = 0,
801         PROTOCOL_ALLOW_USER_ONLY,
802         PROTOCOL_ALLOW_ALWAYS
803 };
804
805 static enum protocol_allow_config parse_protocol_config(const char *key,
806                                                         const char *value)
807 {
808         if (!strcasecmp(value, "always"))
809                 return PROTOCOL_ALLOW_ALWAYS;
810         else if (!strcasecmp(value, "never"))
811                 return PROTOCOL_ALLOW_NEVER;
812         else if (!strcasecmp(value, "user"))
813                 return PROTOCOL_ALLOW_USER_ONLY;
814
815         die(_("unknown value for config '%s': %s"), key, value);
816 }
817
818 static enum protocol_allow_config get_protocol_config(const char *type)
819 {
820         char *key = xstrfmt("protocol.%s.allow", type);
821         char *value;
822
823         /* first check the per-protocol config */
824         if (!git_config_get_string(key, &value)) {
825                 enum protocol_allow_config ret =
826                         parse_protocol_config(key, value);
827                 free(key);
828                 free(value);
829                 return ret;
830         }
831         free(key);
832
833         /* if defined, fallback to user-defined default for unknown protocols */
834         if (!git_config_get_string("protocol.allow", &value)) {
835                 enum protocol_allow_config ret =
836                         parse_protocol_config("protocol.allow", value);
837                 free(value);
838                 return ret;
839         }
840
841         /* fallback to built-in defaults */
842         /* known safe */
843         if (!strcmp(type, "http") ||
844             !strcmp(type, "https") ||
845             !strcmp(type, "git") ||
846             !strcmp(type, "ssh") ||
847             !strcmp(type, "file"))
848                 return PROTOCOL_ALLOW_ALWAYS;
849
850         /* known scary; err on the side of caution */
851         if (!strcmp(type, "ext"))
852                 return PROTOCOL_ALLOW_NEVER;
853
854         /* unknown; by default let them be used only directly by the user */
855         return PROTOCOL_ALLOW_USER_ONLY;
856 }
857
858 int is_transport_allowed(const char *type, int from_user)
859 {
860         const struct string_list *whitelist = protocol_whitelist();
861         if (whitelist)
862                 return string_list_has_string(whitelist, type);
863
864         switch (get_protocol_config(type)) {
865         case PROTOCOL_ALLOW_ALWAYS:
866                 return 1;
867         case PROTOCOL_ALLOW_NEVER:
868                 return 0;
869         case PROTOCOL_ALLOW_USER_ONLY:
870                 if (from_user < 0)
871                         from_user = git_env_bool("GIT_PROTOCOL_FROM_USER", 1);
872                 return from_user;
873         }
874
875         BUG("invalid protocol_allow_config type");
876 }
877
878 void transport_check_allowed(const char *type)
879 {
880         if (!is_transport_allowed(type, -1))
881                 die(_("transport '%s' not allowed"), type);
882 }
883
884 static struct transport_vtable bundle_vtable = {
885         0,
886         NULL,
887         get_refs_from_bundle,
888         fetch_refs_from_bundle,
889         NULL,
890         NULL,
891         close_bundle
892 };
893
894 static struct transport_vtable builtin_smart_vtable = {
895         1,
896         NULL,
897         get_refs_via_connect,
898         fetch_refs_via_pack,
899         git_transport_push,
900         connect_git,
901         disconnect_git
902 };
903
904 struct transport *transport_get(struct remote *remote, const char *url)
905 {
906         const char *helper;
907         struct transport *ret = xcalloc(1, sizeof(*ret));
908
909         ret->progress = isatty(2);
910
911         if (!remote)
912                 BUG("No remote provided to transport_get()");
913
914         ret->got_remote_refs = 0;
915         ret->remote = remote;
916         helper = remote->foreign_vcs;
917
918         if (!url && remote->url)
919                 url = remote->url[0];
920         ret->url = url;
921
922         /* maybe it is a foreign URL? */
923         if (url) {
924                 const char *p = url;
925
926                 while (is_urlschemechar(p == url, *p))
927                         p++;
928                 if (starts_with(p, "::"))
929                         helper = xstrndup(url, p - url);
930         }
931
932         if (helper) {
933                 transport_helper_init(ret, helper);
934         } else if (starts_with(url, "rsync:")) {
935                 die(_("git-over-rsync is no longer supported"));
936         } else if (url_is_local_not_ssh(url) && is_file(url) && is_bundle(url, 1)) {
937                 struct bundle_transport_data *data = xcalloc(1, sizeof(*data));
938                 transport_check_allowed("file");
939                 ret->data = data;
940                 ret->vtable = &bundle_vtable;
941                 ret->smart_options = NULL;
942         } else if (!is_url(url)
943                 || starts_with(url, "file://")
944                 || starts_with(url, "git://")
945                 || starts_with(url, "ssh://")
946                 || starts_with(url, "git+ssh://") /* deprecated - do not use */
947                 || starts_with(url, "ssh+git://") /* deprecated - do not use */
948                 ) {
949                 /*
950                  * These are builtin smart transports; "allowed" transports
951                  * will be checked individually in git_connect.
952                  */
953                 struct git_transport_data *data = xcalloc(1, sizeof(*data));
954                 ret->data = data;
955                 ret->vtable = &builtin_smart_vtable;
956                 ret->smart_options = &(data->options);
957
958                 data->conn = NULL;
959                 data->got_remote_heads = 0;
960         } else {
961                 /* Unknown protocol in URL. Pass to external handler. */
962                 int len = external_specification_len(url);
963                 char *handler = xmemdupz(url, len);
964                 transport_helper_init(ret, handler);
965         }
966
967         if (ret->smart_options) {
968                 ret->smart_options->thin = 1;
969                 ret->smart_options->uploadpack = "git-upload-pack";
970                 if (remote->uploadpack)
971                         ret->smart_options->uploadpack = remote->uploadpack;
972                 ret->smart_options->receivepack = "git-receive-pack";
973                 if (remote->receivepack)
974                         ret->smart_options->receivepack = remote->receivepack;
975         }
976
977         return ret;
978 }
979
980 int transport_set_option(struct transport *transport,
981                          const char *name, const char *value)
982 {
983         int git_reports = 1, protocol_reports = 1;
984
985         if (transport->smart_options)
986                 git_reports = set_git_option(transport->smart_options,
987                                              name, value);
988
989         if (transport->vtable->set_option)
990                 protocol_reports = transport->vtable->set_option(transport,
991                                                                  name, value);
992
993         /* If either report is 0, report 0 (success). */
994         if (!git_reports || !protocol_reports)
995                 return 0;
996         /* If either reports -1 (invalid value), report -1. */
997         if ((git_reports == -1) || (protocol_reports == -1))
998                 return -1;
999         /* Otherwise if both report unknown, report unknown. */
1000         return 1;
1001 }
1002
1003 void transport_set_verbosity(struct transport *transport, int verbosity,
1004         int force_progress)
1005 {
1006         if (verbosity >= 1)
1007                 transport->verbose = verbosity <= 3 ? verbosity : 3;
1008         if (verbosity < 0)
1009                 transport->verbose = -1;
1010
1011         /**
1012          * Rules used to determine whether to report progress (processing aborts
1013          * when a rule is satisfied):
1014          *
1015          *   . Report progress, if force_progress is 1 (ie. --progress).
1016          *   . Don't report progress, if force_progress is 0 (ie. --no-progress).
1017          *   . Don't report progress, if verbosity < 0 (ie. -q/--quiet ).
1018          *   . Report progress if isatty(2) is 1.
1019          **/
1020         if (force_progress >= 0)
1021                 transport->progress = !!force_progress;
1022         else
1023                 transport->progress = verbosity >= 0 && isatty(2);
1024 }
1025
1026 static void die_with_unpushed_submodules(struct string_list *needs_pushing)
1027 {
1028         int i;
1029
1030         fprintf(stderr, _("The following submodule paths contain changes that can\n"
1031                         "not be found on any remote:\n"));
1032         for (i = 0; i < needs_pushing->nr; i++)
1033                 fprintf(stderr, "  %s\n", needs_pushing->items[i].string);
1034         fprintf(stderr, _("\nPlease try\n\n"
1035                           "     git push --recurse-submodules=on-demand\n\n"
1036                           "or cd to the path and use\n\n"
1037                           "     git push\n\n"
1038                           "to push them to a remote.\n\n"));
1039
1040         string_list_clear(needs_pushing, 0);
1041
1042         die(_("Aborting."));
1043 }
1044
1045 static int run_pre_push_hook(struct transport *transport,
1046                              struct ref *remote_refs)
1047 {
1048         int ret = 0, x;
1049         struct ref *r;
1050         struct child_process proc = CHILD_PROCESS_INIT;
1051         struct strbuf buf;
1052         const char *argv[4];
1053
1054         if (!(argv[0] = find_hook("pre-push")))
1055                 return 0;
1056
1057         argv[1] = transport->remote->name;
1058         argv[2] = transport->url;
1059         argv[3] = NULL;
1060
1061         proc.argv = argv;
1062         proc.in = -1;
1063         proc.trace2_hook_name = "pre-push";
1064
1065         if (start_command(&proc)) {
1066                 finish_command(&proc);
1067                 return -1;
1068         }
1069
1070         sigchain_push(SIGPIPE, SIG_IGN);
1071
1072         strbuf_init(&buf, 256);
1073
1074         for (r = remote_refs; r; r = r->next) {
1075                 if (!r->peer_ref) continue;
1076                 if (r->status == REF_STATUS_REJECT_NONFASTFORWARD) continue;
1077                 if (r->status == REF_STATUS_REJECT_STALE) continue;
1078                 if (r->status == REF_STATUS_UPTODATE) continue;
1079
1080                 strbuf_reset(&buf);
1081                 strbuf_addf( &buf, "%s %s %s %s\n",
1082                          r->peer_ref->name, oid_to_hex(&r->new_oid),
1083                          r->name, oid_to_hex(&r->old_oid));
1084
1085                 if (write_in_full(proc.in, buf.buf, buf.len) < 0) {
1086                         /* We do not mind if a hook does not read all refs. */
1087                         if (errno != EPIPE)
1088                                 ret = -1;
1089                         break;
1090                 }
1091         }
1092
1093         strbuf_release(&buf);
1094
1095         x = close(proc.in);
1096         if (!ret)
1097                 ret = x;
1098
1099         sigchain_pop(SIGPIPE);
1100
1101         x = finish_command(&proc);
1102         if (!ret)
1103                 ret = x;
1104
1105         return ret;
1106 }
1107
1108 int transport_push(struct repository *r,
1109                    struct transport *transport,
1110                    struct refspec *rs, int flags,
1111                    unsigned int *reject_reasons)
1112 {
1113         *reject_reasons = 0;
1114
1115         if (transport_color_config() < 0)
1116                 return -1;
1117
1118         if (transport->vtable->push_refs) {
1119                 struct ref *remote_refs;
1120                 struct ref *local_refs = get_local_heads();
1121                 int match_flags = MATCH_REFS_NONE;
1122                 int verbose = (transport->verbose > 0);
1123                 int quiet = (transport->verbose < 0);
1124                 int porcelain = flags & TRANSPORT_PUSH_PORCELAIN;
1125                 int pretend = flags & TRANSPORT_PUSH_DRY_RUN;
1126                 int push_ret, ret, err;
1127                 struct argv_array ref_prefixes = ARGV_ARRAY_INIT;
1128
1129                 if (check_push_refs(local_refs, rs) < 0)
1130                         return -1;
1131
1132                 refspec_ref_prefixes(rs, &ref_prefixes);
1133
1134                 remote_refs = transport->vtable->get_refs_list(transport, 1,
1135                                                                &ref_prefixes);
1136
1137                 argv_array_clear(&ref_prefixes);
1138
1139                 if (flags & TRANSPORT_PUSH_ALL)
1140                         match_flags |= MATCH_REFS_ALL;
1141                 if (flags & TRANSPORT_PUSH_MIRROR)
1142                         match_flags |= MATCH_REFS_MIRROR;
1143                 if (flags & TRANSPORT_PUSH_PRUNE)
1144                         match_flags |= MATCH_REFS_PRUNE;
1145                 if (flags & TRANSPORT_PUSH_FOLLOW_TAGS)
1146                         match_flags |= MATCH_REFS_FOLLOW_TAGS;
1147
1148                 if (match_push_refs(local_refs, &remote_refs, rs, match_flags))
1149                         return -1;
1150
1151                 if (transport->smart_options &&
1152                     transport->smart_options->cas &&
1153                     !is_empty_cas(transport->smart_options->cas))
1154                         apply_push_cas(transport->smart_options->cas,
1155                                        transport->remote, remote_refs);
1156
1157                 set_ref_status_for_push(remote_refs,
1158                         flags & TRANSPORT_PUSH_MIRROR,
1159                         flags & TRANSPORT_PUSH_FORCE);
1160
1161                 if (!(flags & TRANSPORT_PUSH_NO_HOOK))
1162                         if (run_pre_push_hook(transport, remote_refs))
1163                                 return -1;
1164
1165                 if ((flags & (TRANSPORT_RECURSE_SUBMODULES_ON_DEMAND |
1166                               TRANSPORT_RECURSE_SUBMODULES_ONLY)) &&
1167                     !is_bare_repository()) {
1168                         struct ref *ref = remote_refs;
1169                         struct oid_array commits = OID_ARRAY_INIT;
1170
1171                         for (; ref; ref = ref->next)
1172                                 if (!is_null_oid(&ref->new_oid))
1173                                         oid_array_append(&commits,
1174                                                           &ref->new_oid);
1175
1176                         if (!push_unpushed_submodules(r,
1177                                                       &commits,
1178                                                       transport->remote,
1179                                                       rs,
1180                                                       transport->push_options,
1181                                                       pretend)) {
1182                                 oid_array_clear(&commits);
1183                                 die(_("failed to push all needed submodules"));
1184                         }
1185                         oid_array_clear(&commits);
1186                 }
1187
1188                 if (((flags & TRANSPORT_RECURSE_SUBMODULES_CHECK) ||
1189                      ((flags & (TRANSPORT_RECURSE_SUBMODULES_ON_DEMAND |
1190                                 TRANSPORT_RECURSE_SUBMODULES_ONLY)) &&
1191                       !pretend)) && !is_bare_repository()) {
1192                         struct ref *ref = remote_refs;
1193                         struct string_list needs_pushing = STRING_LIST_INIT_DUP;
1194                         struct oid_array commits = OID_ARRAY_INIT;
1195
1196                         for (; ref; ref = ref->next)
1197                                 if (!is_null_oid(&ref->new_oid))
1198                                         oid_array_append(&commits,
1199                                                           &ref->new_oid);
1200
1201                         if (find_unpushed_submodules(r,
1202                                                      &commits,
1203                                                      transport->remote->name,
1204                                                      &needs_pushing)) {
1205                                 oid_array_clear(&commits);
1206                                 die_with_unpushed_submodules(&needs_pushing);
1207                         }
1208                         string_list_clear(&needs_pushing, 0);
1209                         oid_array_clear(&commits);
1210                 }
1211
1212                 if (!(flags & TRANSPORT_RECURSE_SUBMODULES_ONLY))
1213                         push_ret = transport->vtable->push_refs(transport, remote_refs, flags);
1214                 else
1215                         push_ret = 0;
1216                 err = push_had_errors(remote_refs);
1217                 ret = push_ret | err;
1218
1219                 if (!quiet || err)
1220                         transport_print_push_status(transport->url, remote_refs,
1221                                         verbose | porcelain, porcelain,
1222                                         reject_reasons);
1223
1224                 if (flags & TRANSPORT_PUSH_SET_UPSTREAM)
1225                         set_upstreams(transport, remote_refs, pretend);
1226
1227                 if (!(flags & (TRANSPORT_PUSH_DRY_RUN |
1228                                TRANSPORT_RECURSE_SUBMODULES_ONLY))) {
1229                         struct ref *ref;
1230                         for (ref = remote_refs; ref; ref = ref->next)
1231                                 transport_update_tracking_ref(transport->remote, ref, verbose);
1232                 }
1233
1234                 if (porcelain && !push_ret)
1235                         puts("Done");
1236                 else if (!quiet && !ret && !transport_refs_pushed(remote_refs))
1237                         fprintf(stderr, "Everything up-to-date\n");
1238
1239                 return ret;
1240         }
1241         return 1;
1242 }
1243
1244 const struct ref *transport_get_remote_refs(struct transport *transport,
1245                                             const struct argv_array *ref_prefixes)
1246 {
1247         if (!transport->got_remote_refs) {
1248                 transport->remote_refs =
1249                         transport->vtable->get_refs_list(transport, 0,
1250                                                          ref_prefixes);
1251                 transport->got_remote_refs = 1;
1252         }
1253
1254         return transport->remote_refs;
1255 }
1256
1257 int transport_fetch_refs(struct transport *transport, struct ref *refs)
1258 {
1259         int rc;
1260         int nr_heads = 0, nr_alloc = 0, nr_refs = 0;
1261         struct ref **heads = NULL;
1262         struct ref *rm;
1263
1264         if (!transport->vtable->fetch_without_list)
1265                 /*
1266                  * Some transports (e.g. the built-in bundle transport and the
1267                  * transport helper interface) do not work when fetching is
1268                  * done immediately after transport creation. List the remote
1269                  * refs anyway (if not already listed) as a workaround.
1270                  */
1271                 transport_get_remote_refs(transport, NULL);
1272
1273         for (rm = refs; rm; rm = rm->next) {
1274                 nr_refs++;
1275                 if (rm->peer_ref &&
1276                     !is_null_oid(&rm->old_oid) &&
1277                     oideq(&rm->peer_ref->old_oid, &rm->old_oid))
1278                         continue;
1279                 ALLOC_GROW(heads, nr_heads + 1, nr_alloc);
1280                 heads[nr_heads++] = rm;
1281         }
1282
1283         if (!nr_heads) {
1284                 /*
1285                  * When deepening of a shallow repository is requested,
1286                  * then local and remote refs are likely to still be equal.
1287                  * Just feed them all to the fetch method in that case.
1288                  * This condition shouldn't be met in a non-deepening fetch
1289                  * (see builtin/fetch.c:quickfetch()).
1290                  */
1291                 ALLOC_ARRAY(heads, nr_refs);
1292                 for (rm = refs; rm; rm = rm->next)
1293                         heads[nr_heads++] = rm;
1294         }
1295
1296         rc = transport->vtable->fetch(transport, nr_heads, heads);
1297
1298         free(heads);
1299         return rc;
1300 }
1301
1302 void transport_unlock_pack(struct transport *transport)
1303 {
1304         if (transport->pack_lockfile) {
1305                 unlink_or_warn(transport->pack_lockfile);
1306                 FREE_AND_NULL(transport->pack_lockfile);
1307         }
1308 }
1309
1310 int transport_connect(struct transport *transport, const char *name,
1311                       const char *exec, int fd[2])
1312 {
1313         if (transport->vtable->connect)
1314                 return transport->vtable->connect(transport, name, exec, fd);
1315         else
1316                 die(_("operation not supported by protocol"));
1317 }
1318
1319 int transport_disconnect(struct transport *transport)
1320 {
1321         int ret = 0;
1322         if (transport->vtable->disconnect)
1323                 ret = transport->vtable->disconnect(transport);
1324         free(transport);
1325         return ret;
1326 }
1327
1328 /*
1329  * Strip username (and password) from a URL and return
1330  * it in a newly allocated string.
1331  */
1332 char *transport_anonymize_url(const char *url)
1333 {
1334         char *scheme_prefix, *anon_part;
1335         size_t anon_len, prefix_len = 0;
1336
1337         anon_part = strchr(url, '@');
1338         if (url_is_local_not_ssh(url) || !anon_part)
1339                 goto literal_copy;
1340
1341         anon_len = strlen(++anon_part);
1342         scheme_prefix = strstr(url, "://");
1343         if (!scheme_prefix) {
1344                 if (!strchr(anon_part, ':'))
1345                         /* cannot be "me@there:/path/name" */
1346                         goto literal_copy;
1347         } else {
1348                 const char *cp;
1349                 /* make sure scheme is reasonable */
1350                 for (cp = url; cp < scheme_prefix; cp++) {
1351                         switch (*cp) {
1352                                 /* RFC 1738 2.1 */
1353                         case '+': case '.': case '-':
1354                                 break; /* ok */
1355                         default:
1356                                 if (isalnum(*cp))
1357                                         break;
1358                                 /* it isn't */
1359                                 goto literal_copy;
1360                         }
1361                 }
1362                 /* @ past the first slash does not count */
1363                 cp = strchr(scheme_prefix + 3, '/');
1364                 if (cp && cp < anon_part)
1365                         goto literal_copy;
1366                 prefix_len = scheme_prefix - url + 3;
1367         }
1368         return xstrfmt("%.*s%.*s", (int)prefix_len, url,
1369                        (int)anon_len, anon_part);
1370 literal_copy:
1371         return xstrdup(url);
1372 }
1373
1374 static void fill_alternate_refs_command(struct child_process *cmd,
1375                                         const char *repo_path)
1376 {
1377         const char *value;
1378
1379         if (!git_config_get_value("core.alternateRefsCommand", &value)) {
1380                 cmd->use_shell = 1;
1381
1382                 argv_array_push(&cmd->args, value);
1383                 argv_array_push(&cmd->args, repo_path);
1384         } else {
1385                 cmd->git_cmd = 1;
1386
1387                 argv_array_pushf(&cmd->args, "--git-dir=%s", repo_path);
1388                 argv_array_push(&cmd->args, "for-each-ref");
1389                 argv_array_push(&cmd->args, "--format=%(objectname)");
1390
1391                 if (!git_config_get_value("core.alternateRefsPrefixes", &value)) {
1392                         argv_array_push(&cmd->args, "--");
1393                         argv_array_split(&cmd->args, value);
1394                 }
1395         }
1396
1397         cmd->env = local_repo_env;
1398         cmd->out = -1;
1399 }
1400
1401 static void read_alternate_refs(const char *path,
1402                                 alternate_ref_fn *cb,
1403                                 void *data)
1404 {
1405         struct child_process cmd = CHILD_PROCESS_INIT;
1406         struct strbuf line = STRBUF_INIT;
1407         FILE *fh;
1408
1409         fill_alternate_refs_command(&cmd, path);
1410
1411         if (start_command(&cmd))
1412                 return;
1413
1414         fh = xfdopen(cmd.out, "r");
1415         while (strbuf_getline_lf(&line, fh) != EOF) {
1416                 struct object_id oid;
1417                 const char *p;
1418
1419                 if (parse_oid_hex(line.buf, &oid, &p) || *p) {
1420                         warning(_("invalid line while parsing alternate refs: %s"),
1421                                 line.buf);
1422                         break;
1423                 }
1424
1425                 cb(&oid, data);
1426         }
1427
1428         fclose(fh);
1429         finish_command(&cmd);
1430 }
1431
1432 struct alternate_refs_data {
1433         alternate_ref_fn *fn;
1434         void *data;
1435 };
1436
1437 static int refs_from_alternate_cb(struct object_directory *e,
1438                                   void *data)
1439 {
1440         struct strbuf path = STRBUF_INIT;
1441         size_t base_len;
1442         struct alternate_refs_data *cb = data;
1443
1444         if (!strbuf_realpath(&path, e->path, 0))
1445                 goto out;
1446         if (!strbuf_strip_suffix(&path, "/objects"))
1447                 goto out;
1448         base_len = path.len;
1449
1450         /* Is this a git repository with refs? */
1451         strbuf_addstr(&path, "/refs");
1452         if (!is_directory(path.buf))
1453                 goto out;
1454         strbuf_setlen(&path, base_len);
1455
1456         read_alternate_refs(path.buf, cb->fn, cb->data);
1457
1458 out:
1459         strbuf_release(&path);
1460         return 0;
1461 }
1462
1463 void for_each_alternate_ref(alternate_ref_fn fn, void *data)
1464 {
1465         struct alternate_refs_data cb;
1466         cb.fn = fn;
1467         cb.data = data;
1468         foreach_alt_odb(refs_from_alternate_cb, &cb);
1469 }