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