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