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