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