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