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