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