Merge branch 'lm/credential-netrc'
[git/debian.git] / transport.c
blob6785fcceed245769d7d9515a73b7e29c99ee268b
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, transport->server_options);
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;
319 args.server_options = transport->server_options;
321 if (!data->got_remote_heads)
322 refs_tmp = get_refs_via_connect(transport, 0, NULL);
324 switch (data->version) {
325 case protocol_v2:
326 refs = fetch_pack(&args, data->fd, data->conn,
327 refs_tmp ? refs_tmp : transport->remote_refs,
328 dest, to_fetch, nr_heads, &data->shallow,
329 &transport->pack_lockfile, data->version);
330 break;
331 case protocol_v1:
332 case protocol_v0:
333 refs = fetch_pack(&args, data->fd, data->conn,
334 refs_tmp ? refs_tmp : transport->remote_refs,
335 dest, to_fetch, nr_heads, &data->shallow,
336 &transport->pack_lockfile, data->version);
337 break;
338 case protocol_unknown_version:
339 BUG("unknown protocol version");
342 close(data->fd[0]);
343 close(data->fd[1]);
344 if (finish_connect(data->conn))
345 ret = -1;
346 data->conn = NULL;
347 data->got_remote_heads = 0;
348 data->options.self_contained_and_connected =
349 args.self_contained_and_connected;
351 if (refs == NULL)
352 ret = -1;
353 if (report_unmatched_refs(to_fetch, nr_heads))
354 ret = -1;
356 free_refs(refs_tmp);
357 free_refs(refs);
358 free(dest);
359 return ret;
362 static int push_had_errors(struct ref *ref)
364 for (; ref; ref = ref->next) {
365 switch (ref->status) {
366 case REF_STATUS_NONE:
367 case REF_STATUS_UPTODATE:
368 case REF_STATUS_OK:
369 break;
370 default:
371 return 1;
374 return 0;
377 int transport_refs_pushed(struct ref *ref)
379 for (; ref; ref = ref->next) {
380 switch(ref->status) {
381 case REF_STATUS_NONE:
382 case REF_STATUS_UPTODATE:
383 break;
384 default:
385 return 1;
388 return 0;
391 void transport_update_tracking_ref(struct remote *remote, struct ref *ref, int verbose)
393 struct refspec rs;
395 if (ref->status != REF_STATUS_OK && ref->status != REF_STATUS_UPTODATE)
396 return;
398 rs.src = ref->name;
399 rs.dst = NULL;
401 if (!remote_find_tracking(remote, &rs)) {
402 if (verbose)
403 fprintf(stderr, "updating local tracking ref '%s'\n", rs.dst);
404 if (ref->deletion) {
405 delete_ref(NULL, rs.dst, NULL, 0);
406 } else
407 update_ref("update by push", rs.dst, &ref->new_oid,
408 NULL, 0, 0);
409 free(rs.dst);
413 static void print_ref_status(char flag, const char *summary,
414 struct ref *to, struct ref *from, const char *msg,
415 int porcelain, int summary_width)
417 if (porcelain) {
418 if (from)
419 fprintf(stdout, "%c\t%s:%s\t", flag, from->name, to->name);
420 else
421 fprintf(stdout, "%c\t:%s\t", flag, to->name);
422 if (msg)
423 fprintf(stdout, "%s (%s)\n", summary, msg);
424 else
425 fprintf(stdout, "%s\n", summary);
426 } else {
427 const char *red = "", *reset = "";
428 if (push_had_errors(to)) {
429 red = transport_get_color(TRANSPORT_COLOR_REJECTED);
430 reset = transport_get_color(TRANSPORT_COLOR_RESET);
432 fprintf(stderr, " %s%c %-*s%s ", red, flag, summary_width,
433 summary, reset);
434 if (from)
435 fprintf(stderr, "%s -> %s", prettify_refname(from->name), prettify_refname(to->name));
436 else
437 fputs(prettify_refname(to->name), stderr);
438 if (msg) {
439 fputs(" (", stderr);
440 fputs(msg, stderr);
441 fputc(')', stderr);
443 fputc('\n', stderr);
447 static void print_ok_ref_status(struct ref *ref, int porcelain, int summary_width)
449 if (ref->deletion)
450 print_ref_status('-', "[deleted]", ref, NULL, NULL,
451 porcelain, summary_width);
452 else if (is_null_oid(&ref->old_oid))
453 print_ref_status('*',
454 (starts_with(ref->name, "refs/tags/") ? "[new tag]" :
455 "[new branch]"),
456 ref, ref->peer_ref, NULL, porcelain, summary_width);
457 else {
458 struct strbuf quickref = STRBUF_INIT;
459 char type;
460 const char *msg;
462 strbuf_add_unique_abbrev(&quickref, &ref->old_oid,
463 DEFAULT_ABBREV);
464 if (ref->forced_update) {
465 strbuf_addstr(&quickref, "...");
466 type = '+';
467 msg = "forced update";
468 } else {
469 strbuf_addstr(&quickref, "..");
470 type = ' ';
471 msg = NULL;
473 strbuf_add_unique_abbrev(&quickref, &ref->new_oid,
474 DEFAULT_ABBREV);
476 print_ref_status(type, quickref.buf, ref, ref->peer_ref, msg,
477 porcelain, summary_width);
478 strbuf_release(&quickref);
482 static int print_one_push_status(struct ref *ref, const char *dest, int count,
483 int porcelain, int summary_width)
485 if (!count) {
486 char *url = transport_anonymize_url(dest);
487 fprintf(porcelain ? stdout : stderr, "To %s\n", url);
488 free(url);
491 switch(ref->status) {
492 case REF_STATUS_NONE:
493 print_ref_status('X', "[no match]", ref, NULL, NULL,
494 porcelain, summary_width);
495 break;
496 case REF_STATUS_REJECT_NODELETE:
497 print_ref_status('!', "[rejected]", ref, NULL,
498 "remote does not support deleting refs",
499 porcelain, summary_width);
500 break;
501 case REF_STATUS_UPTODATE:
502 print_ref_status('=', "[up to date]", ref,
503 ref->peer_ref, NULL, porcelain, summary_width);
504 break;
505 case REF_STATUS_REJECT_NONFASTFORWARD:
506 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
507 "non-fast-forward", porcelain, summary_width);
508 break;
509 case REF_STATUS_REJECT_ALREADY_EXISTS:
510 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
511 "already exists", porcelain, summary_width);
512 break;
513 case REF_STATUS_REJECT_FETCH_FIRST:
514 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
515 "fetch first", porcelain, summary_width);
516 break;
517 case REF_STATUS_REJECT_NEEDS_FORCE:
518 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
519 "needs force", porcelain, summary_width);
520 break;
521 case REF_STATUS_REJECT_STALE:
522 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
523 "stale info", porcelain, summary_width);
524 break;
525 case REF_STATUS_REJECT_SHALLOW:
526 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
527 "new shallow roots not allowed",
528 porcelain, summary_width);
529 break;
530 case REF_STATUS_REMOTE_REJECT:
531 print_ref_status('!', "[remote rejected]", ref,
532 ref->deletion ? NULL : ref->peer_ref,
533 ref->remote_status, porcelain, summary_width);
534 break;
535 case REF_STATUS_EXPECTING_REPORT:
536 print_ref_status('!', "[remote failure]", ref,
537 ref->deletion ? NULL : ref->peer_ref,
538 "remote failed to report status",
539 porcelain, summary_width);
540 break;
541 case REF_STATUS_ATOMIC_PUSH_FAILED:
542 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
543 "atomic push failed", porcelain, summary_width);
544 break;
545 case REF_STATUS_OK:
546 print_ok_ref_status(ref, porcelain, summary_width);
547 break;
550 return 1;
553 static int measure_abbrev(const struct object_id *oid, int sofar)
555 char hex[GIT_MAX_HEXSZ + 1];
556 int w = find_unique_abbrev_r(hex, oid, DEFAULT_ABBREV);
558 return (w < sofar) ? sofar : w;
561 int transport_summary_width(const struct ref *refs)
563 int maxw = -1;
565 for (; refs; refs = refs->next) {
566 maxw = measure_abbrev(&refs->old_oid, maxw);
567 maxw = measure_abbrev(&refs->new_oid, maxw);
569 if (maxw < 0)
570 maxw = FALLBACK_DEFAULT_ABBREV;
571 return (2 * maxw + 3);
574 void transport_print_push_status(const char *dest, struct ref *refs,
575 int verbose, int porcelain, unsigned int *reject_reasons)
577 struct ref *ref;
578 int n = 0;
579 char *head;
580 int summary_width = transport_summary_width(refs);
582 if (transport_color_config() < 0)
583 warning(_("could not parse transport.color.* config"));
585 head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
587 if (verbose) {
588 for (ref = refs; ref; ref = ref->next)
589 if (ref->status == REF_STATUS_UPTODATE)
590 n += print_one_push_status(ref, dest, n,
591 porcelain, summary_width);
594 for (ref = refs; ref; ref = ref->next)
595 if (ref->status == REF_STATUS_OK)
596 n += print_one_push_status(ref, dest, n,
597 porcelain, summary_width);
599 *reject_reasons = 0;
600 for (ref = refs; ref; ref = ref->next) {
601 if (ref->status != REF_STATUS_NONE &&
602 ref->status != REF_STATUS_UPTODATE &&
603 ref->status != REF_STATUS_OK)
604 n += print_one_push_status(ref, dest, n,
605 porcelain, summary_width);
606 if (ref->status == REF_STATUS_REJECT_NONFASTFORWARD) {
607 if (head != NULL && !strcmp(head, ref->name))
608 *reject_reasons |= REJECT_NON_FF_HEAD;
609 else
610 *reject_reasons |= REJECT_NON_FF_OTHER;
611 } else if (ref->status == REF_STATUS_REJECT_ALREADY_EXISTS) {
612 *reject_reasons |= REJECT_ALREADY_EXISTS;
613 } else if (ref->status == REF_STATUS_REJECT_FETCH_FIRST) {
614 *reject_reasons |= REJECT_FETCH_FIRST;
615 } else if (ref->status == REF_STATUS_REJECT_NEEDS_FORCE) {
616 *reject_reasons |= REJECT_NEEDS_FORCE;
619 free(head);
622 void transport_verify_remote_names(int nr_heads, const char **heads)
624 int i;
626 for (i = 0; i < nr_heads; i++) {
627 const char *local = heads[i];
628 const char *remote = strrchr(heads[i], ':');
630 if (*local == '+')
631 local++;
633 /* A matching refspec is okay. */
634 if (remote == local && remote[1] == '\0')
635 continue;
637 remote = remote ? (remote + 1) : local;
638 if (check_refname_format(remote,
639 REFNAME_ALLOW_ONELEVEL|REFNAME_REFSPEC_PATTERN))
640 die("remote part of refspec is not a valid name in %s",
641 heads[i]);
645 static int git_transport_push(struct transport *transport, struct ref *remote_refs, int flags)
647 struct git_transport_data *data = transport->data;
648 struct send_pack_args args;
649 int ret = 0;
651 if (transport_color_config() < 0)
652 return -1;
654 if (!data->got_remote_heads)
655 get_refs_via_connect(transport, 1, NULL);
657 memset(&args, 0, sizeof(args));
658 args.send_mirror = !!(flags & TRANSPORT_PUSH_MIRROR);
659 args.force_update = !!(flags & TRANSPORT_PUSH_FORCE);
660 args.use_thin_pack = data->options.thin;
661 args.verbose = (transport->verbose > 0);
662 args.quiet = (transport->verbose < 0);
663 args.progress = transport->progress;
664 args.dry_run = !!(flags & TRANSPORT_PUSH_DRY_RUN);
665 args.porcelain = !!(flags & TRANSPORT_PUSH_PORCELAIN);
666 args.atomic = !!(flags & TRANSPORT_PUSH_ATOMIC);
667 args.push_options = transport->push_options;
668 args.url = transport->url;
670 if (flags & TRANSPORT_PUSH_CERT_ALWAYS)
671 args.push_cert = SEND_PACK_PUSH_CERT_ALWAYS;
672 else if (flags & TRANSPORT_PUSH_CERT_IF_ASKED)
673 args.push_cert = SEND_PACK_PUSH_CERT_IF_ASKED;
674 else
675 args.push_cert = SEND_PACK_PUSH_CERT_NEVER;
677 switch (data->version) {
678 case protocol_v2:
679 die("support for protocol v2 not implemented yet");
680 break;
681 case protocol_v1:
682 case protocol_v0:
683 ret = send_pack(&args, data->fd, data->conn, remote_refs,
684 &data->extra_have);
685 break;
686 case protocol_unknown_version:
687 BUG("unknown protocol version");
690 close(data->fd[1]);
691 close(data->fd[0]);
692 ret |= finish_connect(data->conn);
693 data->conn = NULL;
694 data->got_remote_heads = 0;
696 return ret;
699 static int connect_git(struct transport *transport, const char *name,
700 const char *executable, int fd[2])
702 struct git_transport_data *data = transport->data;
703 data->conn = git_connect(data->fd, transport->url,
704 executable, 0);
705 fd[0] = data->fd[0];
706 fd[1] = data->fd[1];
707 return 0;
710 static int disconnect_git(struct transport *transport)
712 struct git_transport_data *data = transport->data;
713 if (data->conn) {
714 if (data->got_remote_heads)
715 packet_flush(data->fd[1]);
716 close(data->fd[0]);
717 close(data->fd[1]);
718 finish_connect(data->conn);
721 free(data);
722 return 0;
725 static struct transport_vtable taken_over_vtable = {
726 NULL,
727 get_refs_via_connect,
728 fetch_refs_via_pack,
729 git_transport_push,
730 NULL,
731 disconnect_git
734 void transport_take_over(struct transport *transport,
735 struct child_process *child)
737 struct git_transport_data *data;
739 if (!transport->smart_options)
740 BUG("taking over transport requires non-NULL "
741 "smart_options field.");
743 data = xcalloc(1, sizeof(*data));
744 data->options = *transport->smart_options;
745 data->conn = child;
746 data->fd[0] = data->conn->out;
747 data->fd[1] = data->conn->in;
748 data->got_remote_heads = 0;
749 transport->data = data;
751 transport->vtable = &taken_over_vtable;
752 transport->smart_options = &(data->options);
754 transport->cannot_reuse = 1;
757 static int is_file(const char *url)
759 struct stat buf;
760 if (stat(url, &buf))
761 return 0;
762 return S_ISREG(buf.st_mode);
765 static int external_specification_len(const char *url)
767 return strchr(url, ':') - url;
770 static const struct string_list *protocol_whitelist(void)
772 static int enabled = -1;
773 static struct string_list allowed = STRING_LIST_INIT_DUP;
775 if (enabled < 0) {
776 const char *v = getenv("GIT_ALLOW_PROTOCOL");
777 if (v) {
778 string_list_split(&allowed, v, ':', -1);
779 string_list_sort(&allowed);
780 enabled = 1;
781 } else {
782 enabled = 0;
786 return enabled ? &allowed : NULL;
789 enum protocol_allow_config {
790 PROTOCOL_ALLOW_NEVER = 0,
791 PROTOCOL_ALLOW_USER_ONLY,
792 PROTOCOL_ALLOW_ALWAYS
795 static enum protocol_allow_config parse_protocol_config(const char *key,
796 const char *value)
798 if (!strcasecmp(value, "always"))
799 return PROTOCOL_ALLOW_ALWAYS;
800 else if (!strcasecmp(value, "never"))
801 return PROTOCOL_ALLOW_NEVER;
802 else if (!strcasecmp(value, "user"))
803 return PROTOCOL_ALLOW_USER_ONLY;
805 die("unknown value for config '%s': %s", key, value);
808 static enum protocol_allow_config get_protocol_config(const char *type)
810 char *key = xstrfmt("protocol.%s.allow", type);
811 char *value;
813 /* first check the per-protocol config */
814 if (!git_config_get_string(key, &value)) {
815 enum protocol_allow_config ret =
816 parse_protocol_config(key, value);
817 free(key);
818 free(value);
819 return ret;
821 free(key);
823 /* if defined, fallback to user-defined default for unknown protocols */
824 if (!git_config_get_string("protocol.allow", &value)) {
825 enum protocol_allow_config ret =
826 parse_protocol_config("protocol.allow", value);
827 free(value);
828 return ret;
831 /* fallback to built-in defaults */
832 /* known safe */
833 if (!strcmp(type, "http") ||
834 !strcmp(type, "https") ||
835 !strcmp(type, "git") ||
836 !strcmp(type, "ssh") ||
837 !strcmp(type, "file"))
838 return PROTOCOL_ALLOW_ALWAYS;
840 /* known scary; err on the side of caution */
841 if (!strcmp(type, "ext"))
842 return PROTOCOL_ALLOW_NEVER;
844 /* unknown; by default let them be used only directly by the user */
845 return PROTOCOL_ALLOW_USER_ONLY;
848 int is_transport_allowed(const char *type, int from_user)
850 const struct string_list *whitelist = protocol_whitelist();
851 if (whitelist)
852 return string_list_has_string(whitelist, type);
854 switch (get_protocol_config(type)) {
855 case PROTOCOL_ALLOW_ALWAYS:
856 return 1;
857 case PROTOCOL_ALLOW_NEVER:
858 return 0;
859 case PROTOCOL_ALLOW_USER_ONLY:
860 if (from_user < 0)
861 from_user = git_env_bool("GIT_PROTOCOL_FROM_USER", 1);
862 return from_user;
865 BUG("invalid protocol_allow_config type");
868 void transport_check_allowed(const char *type)
870 if (!is_transport_allowed(type, -1))
871 die("transport '%s' not allowed", type);
874 static struct transport_vtable bundle_vtable = {
875 NULL,
876 get_refs_from_bundle,
877 fetch_refs_from_bundle,
878 NULL,
879 NULL,
880 close_bundle
883 static struct transport_vtable builtin_smart_vtable = {
884 NULL,
885 get_refs_via_connect,
886 fetch_refs_via_pack,
887 git_transport_push,
888 connect_git,
889 disconnect_git
892 struct transport *transport_get(struct remote *remote, const char *url)
894 const char *helper;
895 struct transport *ret = xcalloc(1, sizeof(*ret));
897 ret->progress = isatty(2);
899 if (!remote)
900 die("No remote provided to transport_get()");
902 ret->got_remote_refs = 0;
903 ret->remote = remote;
904 helper = remote->foreign_vcs;
906 if (!url && remote->url)
907 url = remote->url[0];
908 ret->url = url;
910 /* maybe it is a foreign URL? */
911 if (url) {
912 const char *p = url;
914 while (is_urlschemechar(p == url, *p))
915 p++;
916 if (starts_with(p, "::"))
917 helper = xstrndup(url, p - url);
920 if (helper) {
921 transport_helper_init(ret, helper);
922 } else if (starts_with(url, "rsync:")) {
923 die("git-over-rsync is no longer supported");
924 } else if (url_is_local_not_ssh(url) && is_file(url) && is_bundle(url, 1)) {
925 struct bundle_transport_data *data = xcalloc(1, sizeof(*data));
926 transport_check_allowed("file");
927 ret->data = data;
928 ret->vtable = &bundle_vtable;
929 ret->smart_options = NULL;
930 } else if (!is_url(url)
931 || starts_with(url, "file://")
932 || starts_with(url, "git://")
933 || starts_with(url, "ssh://")
934 || starts_with(url, "git+ssh://") /* deprecated - do not use */
935 || starts_with(url, "ssh+git://") /* deprecated - do not use */
938 * These are builtin smart transports; "allowed" transports
939 * will be checked individually in git_connect.
941 struct git_transport_data *data = xcalloc(1, sizeof(*data));
942 ret->data = data;
943 ret->vtable = &builtin_smart_vtable;
944 ret->smart_options = &(data->options);
946 data->conn = NULL;
947 data->got_remote_heads = 0;
948 } else {
949 /* Unknown protocol in URL. Pass to external handler. */
950 int len = external_specification_len(url);
951 char *handler = xmemdupz(url, len);
952 transport_helper_init(ret, handler);
955 if (ret->smart_options) {
956 ret->smart_options->thin = 1;
957 ret->smart_options->uploadpack = "git-upload-pack";
958 if (remote->uploadpack)
959 ret->smart_options->uploadpack = remote->uploadpack;
960 ret->smart_options->receivepack = "git-receive-pack";
961 if (remote->receivepack)
962 ret->smart_options->receivepack = remote->receivepack;
965 return ret;
968 int transport_set_option(struct transport *transport,
969 const char *name, const char *value)
971 int git_reports = 1, protocol_reports = 1;
973 if (transport->smart_options)
974 git_reports = set_git_option(transport->smart_options,
975 name, value);
977 if (transport->vtable->set_option)
978 protocol_reports = transport->vtable->set_option(transport,
979 name, value);
981 /* If either report is 0, report 0 (success). */
982 if (!git_reports || !protocol_reports)
983 return 0;
984 /* If either reports -1 (invalid value), report -1. */
985 if ((git_reports == -1) || (protocol_reports == -1))
986 return -1;
987 /* Otherwise if both report unknown, report unknown. */
988 return 1;
991 void transport_set_verbosity(struct transport *transport, int verbosity,
992 int force_progress)
994 if (verbosity >= 1)
995 transport->verbose = verbosity <= 3 ? verbosity : 3;
996 if (verbosity < 0)
997 transport->verbose = -1;
1000 * Rules used to determine whether to report progress (processing aborts
1001 * when a rule is satisfied):
1003 * . Report progress, if force_progress is 1 (ie. --progress).
1004 * . Don't report progress, if force_progress is 0 (ie. --no-progress).
1005 * . Don't report progress, if verbosity < 0 (ie. -q/--quiet ).
1006 * . Report progress if isatty(2) is 1.
1008 if (force_progress >= 0)
1009 transport->progress = !!force_progress;
1010 else
1011 transport->progress = verbosity >= 0 && isatty(2);
1014 static void die_with_unpushed_submodules(struct string_list *needs_pushing)
1016 int i;
1018 fprintf(stderr, _("The following submodule paths contain changes that can\n"
1019 "not be found on any remote:\n"));
1020 for (i = 0; i < needs_pushing->nr; i++)
1021 fprintf(stderr, " %s\n", needs_pushing->items[i].string);
1022 fprintf(stderr, _("\nPlease try\n\n"
1023 " git push --recurse-submodules=on-demand\n\n"
1024 "or cd to the path and use\n\n"
1025 " git push\n\n"
1026 "to push them to a remote.\n\n"));
1028 string_list_clear(needs_pushing, 0);
1030 die(_("Aborting."));
1033 static int run_pre_push_hook(struct transport *transport,
1034 struct ref *remote_refs)
1036 int ret = 0, x;
1037 struct ref *r;
1038 struct child_process proc = CHILD_PROCESS_INIT;
1039 struct strbuf buf;
1040 const char *argv[4];
1042 if (!(argv[0] = find_hook("pre-push")))
1043 return 0;
1045 argv[1] = transport->remote->name;
1046 argv[2] = transport->url;
1047 argv[3] = NULL;
1049 proc.argv = argv;
1050 proc.in = -1;
1052 if (start_command(&proc)) {
1053 finish_command(&proc);
1054 return -1;
1057 sigchain_push(SIGPIPE, SIG_IGN);
1059 strbuf_init(&buf, 256);
1061 for (r = remote_refs; r; r = r->next) {
1062 if (!r->peer_ref) continue;
1063 if (r->status == REF_STATUS_REJECT_NONFASTFORWARD) continue;
1064 if (r->status == REF_STATUS_REJECT_STALE) continue;
1065 if (r->status == REF_STATUS_UPTODATE) continue;
1067 strbuf_reset(&buf);
1068 strbuf_addf( &buf, "%s %s %s %s\n",
1069 r->peer_ref->name, oid_to_hex(&r->new_oid),
1070 r->name, oid_to_hex(&r->old_oid));
1072 if (write_in_full(proc.in, buf.buf, buf.len) < 0) {
1073 /* We do not mind if a hook does not read all refs. */
1074 if (errno != EPIPE)
1075 ret = -1;
1076 break;
1080 strbuf_release(&buf);
1082 x = close(proc.in);
1083 if (!ret)
1084 ret = x;
1086 sigchain_pop(SIGPIPE);
1088 x = finish_command(&proc);
1089 if (!ret)
1090 ret = x;
1092 return ret;
1095 int transport_push(struct transport *transport,
1096 int refspec_nr, const char **refspec, int flags,
1097 unsigned int *reject_reasons)
1099 *reject_reasons = 0;
1100 transport_verify_remote_names(refspec_nr, refspec);
1102 if (transport_color_config() < 0)
1103 return -1;
1105 if (transport->vtable->push_refs) {
1106 struct ref *remote_refs;
1107 struct ref *local_refs = get_local_heads();
1108 int match_flags = MATCH_REFS_NONE;
1109 int verbose = (transport->verbose > 0);
1110 int quiet = (transport->verbose < 0);
1111 int porcelain = flags & TRANSPORT_PUSH_PORCELAIN;
1112 int pretend = flags & TRANSPORT_PUSH_DRY_RUN;
1113 int push_ret, ret, err;
1114 struct refspec *tmp_rs;
1115 struct argv_array ref_prefixes = ARGV_ARRAY_INIT;
1116 int i;
1118 if (check_push_refs(local_refs, refspec_nr, refspec) < 0)
1119 return -1;
1121 tmp_rs = parse_push_refspec(refspec_nr, refspec);
1122 for (i = 0; i < refspec_nr; i++) {
1123 const char *prefix = NULL;
1125 if (tmp_rs[i].dst)
1126 prefix = tmp_rs[i].dst;
1127 else if (tmp_rs[i].src && !tmp_rs[i].exact_sha1)
1128 prefix = tmp_rs[i].src;
1130 if (prefix) {
1131 const char *glob = strchr(prefix, '*');
1132 if (glob)
1133 argv_array_pushf(&ref_prefixes, "%.*s",
1134 (int)(glob - prefix),
1135 prefix);
1136 else
1137 expand_ref_prefix(&ref_prefixes, prefix);
1141 remote_refs = transport->vtable->get_refs_list(transport, 1,
1142 &ref_prefixes);
1144 argv_array_clear(&ref_prefixes);
1145 free_refspec(refspec_nr, tmp_rs);
1147 if (flags & TRANSPORT_PUSH_ALL)
1148 match_flags |= MATCH_REFS_ALL;
1149 if (flags & TRANSPORT_PUSH_MIRROR)
1150 match_flags |= MATCH_REFS_MIRROR;
1151 if (flags & TRANSPORT_PUSH_PRUNE)
1152 match_flags |= MATCH_REFS_PRUNE;
1153 if (flags & TRANSPORT_PUSH_FOLLOW_TAGS)
1154 match_flags |= MATCH_REFS_FOLLOW_TAGS;
1156 if (match_push_refs(local_refs, &remote_refs,
1157 refspec_nr, refspec, match_flags)) {
1158 return -1;
1161 if (transport->smart_options &&
1162 transport->smart_options->cas &&
1163 !is_empty_cas(transport->smart_options->cas))
1164 apply_push_cas(transport->smart_options->cas,
1165 transport->remote, remote_refs);
1167 set_ref_status_for_push(remote_refs,
1168 flags & TRANSPORT_PUSH_MIRROR,
1169 flags & TRANSPORT_PUSH_FORCE);
1171 if (!(flags & TRANSPORT_PUSH_NO_HOOK))
1172 if (run_pre_push_hook(transport, remote_refs))
1173 return -1;
1175 if ((flags & (TRANSPORT_RECURSE_SUBMODULES_ON_DEMAND |
1176 TRANSPORT_RECURSE_SUBMODULES_ONLY)) &&
1177 !is_bare_repository()) {
1178 struct ref *ref = remote_refs;
1179 struct oid_array commits = OID_ARRAY_INIT;
1181 for (; ref; ref = ref->next)
1182 if (!is_null_oid(&ref->new_oid))
1183 oid_array_append(&commits,
1184 &ref->new_oid);
1186 if (!push_unpushed_submodules(&commits,
1187 transport->remote,
1188 refspec, refspec_nr,
1189 transport->push_options,
1190 pretend)) {
1191 oid_array_clear(&commits);
1192 die("Failed to push all needed submodules!");
1194 oid_array_clear(&commits);
1197 if (((flags & TRANSPORT_RECURSE_SUBMODULES_CHECK) ||
1198 ((flags & (TRANSPORT_RECURSE_SUBMODULES_ON_DEMAND |
1199 TRANSPORT_RECURSE_SUBMODULES_ONLY)) &&
1200 !pretend)) && !is_bare_repository()) {
1201 struct ref *ref = remote_refs;
1202 struct string_list needs_pushing = STRING_LIST_INIT_DUP;
1203 struct oid_array commits = OID_ARRAY_INIT;
1205 for (; ref; ref = ref->next)
1206 if (!is_null_oid(&ref->new_oid))
1207 oid_array_append(&commits,
1208 &ref->new_oid);
1210 if (find_unpushed_submodules(&commits, transport->remote->name,
1211 &needs_pushing)) {
1212 oid_array_clear(&commits);
1213 die_with_unpushed_submodules(&needs_pushing);
1215 string_list_clear(&needs_pushing, 0);
1216 oid_array_clear(&commits);
1219 if (!(flags & TRANSPORT_RECURSE_SUBMODULES_ONLY))
1220 push_ret = transport->vtable->push_refs(transport, remote_refs, flags);
1221 else
1222 push_ret = 0;
1223 err = push_had_errors(remote_refs);
1224 ret = push_ret | err;
1226 if (!quiet || err)
1227 transport_print_push_status(transport->url, remote_refs,
1228 verbose | porcelain, porcelain,
1229 reject_reasons);
1231 if (flags & TRANSPORT_PUSH_SET_UPSTREAM)
1232 set_upstreams(transport, remote_refs, pretend);
1234 if (!(flags & (TRANSPORT_PUSH_DRY_RUN |
1235 TRANSPORT_RECURSE_SUBMODULES_ONLY))) {
1236 struct ref *ref;
1237 for (ref = remote_refs; ref; ref = ref->next)
1238 transport_update_tracking_ref(transport->remote, ref, verbose);
1241 if (porcelain && !push_ret)
1242 puts("Done");
1243 else if (!quiet && !ret && !transport_refs_pushed(remote_refs))
1244 fprintf(stderr, "Everything up-to-date\n");
1246 return ret;
1248 return 1;
1251 const struct ref *transport_get_remote_refs(struct transport *transport,
1252 const struct argv_array *ref_prefixes)
1254 if (!transport->got_remote_refs) {
1255 transport->remote_refs =
1256 transport->vtable->get_refs_list(transport, 0,
1257 ref_prefixes);
1258 transport->got_remote_refs = 1;
1261 return transport->remote_refs;
1264 int transport_fetch_refs(struct transport *transport, struct ref *refs)
1266 int rc;
1267 int nr_heads = 0, nr_alloc = 0, nr_refs = 0;
1268 struct ref **heads = NULL;
1269 struct ref *rm;
1271 for (rm = refs; rm; rm = rm->next) {
1272 nr_refs++;
1273 if (rm->peer_ref &&
1274 !is_null_oid(&rm->old_oid) &&
1275 !oidcmp(&rm->peer_ref->old_oid, &rm->old_oid))
1276 continue;
1277 ALLOC_GROW(heads, nr_heads + 1, nr_alloc);
1278 heads[nr_heads++] = rm;
1281 if (!nr_heads) {
1283 * When deepening of a shallow repository is requested,
1284 * then local and remote refs are likely to still be equal.
1285 * Just feed them all to the fetch method in that case.
1286 * This condition shouldn't be met in a non-deepening fetch
1287 * (see builtin/fetch.c:quickfetch()).
1289 ALLOC_ARRAY(heads, nr_refs);
1290 for (rm = refs; rm; rm = rm->next)
1291 heads[nr_heads++] = rm;
1294 rc = transport->vtable->fetch(transport, nr_heads, heads);
1296 free(heads);
1297 return rc;
1300 void transport_unlock_pack(struct transport *transport)
1302 if (transport->pack_lockfile) {
1303 unlink_or_warn(transport->pack_lockfile);
1304 FREE_AND_NULL(transport->pack_lockfile);
1308 int transport_connect(struct transport *transport, const char *name,
1309 const char *exec, int fd[2])
1311 if (transport->vtable->connect)
1312 return transport->vtable->connect(transport, name, exec, fd);
1313 else
1314 die("Operation not supported by protocol");
1317 int transport_disconnect(struct transport *transport)
1319 int ret = 0;
1320 if (transport->vtable->disconnect)
1321 ret = transport->vtable->disconnect(transport);
1322 free(transport);
1323 return ret;
1327 * Strip username (and password) from a URL and return
1328 * it in a newly allocated string.
1330 char *transport_anonymize_url(const char *url)
1332 char *scheme_prefix, *anon_part;
1333 size_t anon_len, prefix_len = 0;
1335 anon_part = strchr(url, '@');
1336 if (url_is_local_not_ssh(url) || !anon_part)
1337 goto literal_copy;
1339 anon_len = strlen(++anon_part);
1340 scheme_prefix = strstr(url, "://");
1341 if (!scheme_prefix) {
1342 if (!strchr(anon_part, ':'))
1343 /* cannot be "me@there:/path/name" */
1344 goto literal_copy;
1345 } else {
1346 const char *cp;
1347 /* make sure scheme is reasonable */
1348 for (cp = url; cp < scheme_prefix; cp++) {
1349 switch (*cp) {
1350 /* RFC 1738 2.1 */
1351 case '+': case '.': case '-':
1352 break; /* ok */
1353 default:
1354 if (isalnum(*cp))
1355 break;
1356 /* it isn't */
1357 goto literal_copy;
1360 /* @ past the first slash does not count */
1361 cp = strchr(scheme_prefix + 3, '/');
1362 if (cp && cp < anon_part)
1363 goto literal_copy;
1364 prefix_len = scheme_prefix - url + 3;
1366 return xstrfmt("%.*s%.*s", (int)prefix_len, url,
1367 (int)anon_len, anon_part);
1368 literal_copy:
1369 return xstrdup(url);
1372 static void read_alternate_refs(const char *path,
1373 alternate_ref_fn *cb,
1374 void *data)
1376 struct child_process cmd = CHILD_PROCESS_INIT;
1377 struct strbuf line = STRBUF_INIT;
1378 FILE *fh;
1380 cmd.git_cmd = 1;
1381 argv_array_pushf(&cmd.args, "--git-dir=%s", path);
1382 argv_array_push(&cmd.args, "for-each-ref");
1383 argv_array_push(&cmd.args, "--format=%(objectname) %(refname)");
1384 cmd.env = local_repo_env;
1385 cmd.out = -1;
1387 if (start_command(&cmd))
1388 return;
1390 fh = xfdopen(cmd.out, "r");
1391 while (strbuf_getline_lf(&line, fh) != EOF) {
1392 struct object_id oid;
1394 if (get_oid_hex(line.buf, &oid) ||
1395 line.buf[GIT_SHA1_HEXSZ] != ' ') {
1396 warning("invalid line while parsing alternate refs: %s",
1397 line.buf);
1398 break;
1401 cb(line.buf + GIT_SHA1_HEXSZ + 1, &oid, data);
1404 fclose(fh);
1405 finish_command(&cmd);
1408 struct alternate_refs_data {
1409 alternate_ref_fn *fn;
1410 void *data;
1413 static int refs_from_alternate_cb(struct alternate_object_database *e,
1414 void *data)
1416 struct strbuf path = STRBUF_INIT;
1417 size_t base_len;
1418 struct alternate_refs_data *cb = data;
1420 if (!strbuf_realpath(&path, e->path, 0))
1421 goto out;
1422 if (!strbuf_strip_suffix(&path, "/objects"))
1423 goto out;
1424 base_len = path.len;
1426 /* Is this a git repository with refs? */
1427 strbuf_addstr(&path, "/refs");
1428 if (!is_directory(path.buf))
1429 goto out;
1430 strbuf_setlen(&path, base_len);
1432 read_alternate_refs(path.buf, cb->fn, cb->data);
1434 out:
1435 strbuf_release(&path);
1436 return 0;
1439 void for_each_alternate_ref(alternate_ref_fn fn, void *data)
1441 struct alternate_refs_data cb;
1442 cb.fn = fn;
1443 cb.data = data;
1444 foreach_alt_odb(refs_from_alternate_cb, &cb);