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