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