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