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