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