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