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