transport.c 32.5 KB
Newer Older
1 2 3
#include "cache.h"
#include "transport.h"
#include "run-command.h"
4 5
#include "pkt-line.h"
#include "fetch-pack.h"
6 7
#include "remote.h"
#include "connect.h"
D
Daniel Barkalow 已提交
8
#include "send-pack.h"
9
#include "walker.h"
J
Johannes Schindelin 已提交
10
#include "bundle.h"
11 12
#include "dir.h"
#include "refs.h"
I
Ilari Liusvaara 已提交
13
#include "branch.h"
J
Jeff King 已提交
14
#include "url.h"
15
#include "submodule.h"
16
#include "string-list.h"
17
#include "sha1-array.h"
18
#include "sigchain.h"
19

I
Ilari Liusvaara 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
static void set_upstreams(struct transport *transport, struct ref *refs,
	int pretend)
{
	struct ref *ref;
	for (ref = refs; ref; ref = ref->next) {
		const char *localname;
		const char *tmp;
		const char *remotename;
		unsigned char sha[20];
		int flag = 0;
		/*
		 * Check suitability for tracking. Must be successful /
		 * already up-to-date ref create/modify (not delete).
		 */
		if (ref->status != REF_STATUS_OK &&
			ref->status != REF_STATUS_UPTODATE)
			continue;
		if (!ref->peer_ref)
			continue;
39
		if (is_null_oid(&ref->new_oid))
I
Ilari Liusvaara 已提交
40 41 42 43 44
			continue;

		/* Follow symbolic refs (mainly for HEAD). */
		localname = ref->peer_ref->name;
		remotename = ref->name;
45 46
		tmp = resolve_ref_unsafe(localname, RESOLVE_REF_READING,
					 sha, &flag);
I
Ilari Liusvaara 已提交
47
		if (tmp && flag & REF_ISSYMREF &&
48
			starts_with(tmp, "refs/heads/"))
I
Ilari Liusvaara 已提交
49 50 51
			localname = tmp;

		/* Both source and destination must be local branches. */
52
		if (!localname || !starts_with(localname, "refs/heads/"))
I
Ilari Liusvaara 已提交
53
			continue;
54
		if (!remotename || !starts_with(remotename, "refs/heads/"))
I
Ilari Liusvaara 已提交
55 56 57 58 59 60 61
			continue;

		if (!pretend)
			install_branch_config(BRANCH_CONFIG_VERBOSE,
				localname + 11, transport->remote->name,
				remotename);
		else
62
			printf(_("Would set upstream of '%s' to '%s' of '%s'\n"),
I
Ilari Liusvaara 已提交
63 64 65 66 67
				localname + 11, remotename + 11,
				transport->remote->name);
	}
}

J
Johannes Schindelin 已提交
68 69 70 71 72
struct bundle_transport_data {
	int fd;
	struct bundle_header header;
};

73
static struct ref *get_refs_from_bundle(struct transport *transport, int for_push)
J
Johannes Schindelin 已提交
74 75 76 77 78
{
	struct bundle_transport_data *data = transport->data;
	struct ref *result = NULL;
	int i;

79 80 81
	if (for_push)
		return NULL;

J
Johannes Schindelin 已提交
82 83 84 85 86 87 88
	if (data->fd > 0)
		close(data->fd);
	data->fd = read_bundle_header(transport->url, &data->header);
	if (data->fd < 0)
		die ("Could not read bundle '%s'.", transport->url);
	for (i = 0; i < data->header.references.nr; i++) {
		struct ref_list_entry *e = data->header.references.list + i;
89
		struct ref *ref = alloc_ref(e->name);
90
		hashcpy(ref->old_oid.hash, e->sha1);
J
Johannes Schindelin 已提交
91 92 93 94 95 96
		ref->next = result;
		result = ref;
	}
	return result;
}

97
static int fetch_refs_from_bundle(struct transport *transport,
D
Daniel Barkalow 已提交
98
			       int nr_heads, struct ref **to_fetch)
J
Johannes Schindelin 已提交
99 100
{
	struct bundle_transport_data *data = transport->data;
101 102
	return unbundle(&data->header, data->fd,
			transport->progress ? BUNDLE_VERBOSE : 0);
J
Johannes Schindelin 已提交
103 104 105 106 107 108 109
}

static int close_bundle(struct transport *transport)
{
	struct bundle_transport_data *data = transport->data;
	if (data->fd > 0)
		close(data->fd);
110
	free(data);
J
Johannes Schindelin 已提交
111 112 113
	return 0;
}

114
struct git_transport_data {
115
	struct git_transport_options options;
116 117
	struct child_process *conn;
	int fd[2];
I
Ilari Liusvaara 已提交
118
	unsigned got_remote_heads : 1;
119
	struct sha1_array extra_have;
120
	struct sha1_array shallow;
121 122
};

123
static int set_git_option(struct git_transport_options *opts,
124 125
			  const char *name, const char *value)
{
126
	if (!strcmp(name, TRANS_OPT_UPLOADPACK)) {
127
		opts->uploadpack = value;
128 129
		return 0;
	} else if (!strcmp(name, TRANS_OPT_RECEIVEPACK)) {
130
		opts->receivepack = value;
131 132
		return 0;
	} else if (!strcmp(name, TRANS_OPT_THIN)) {
133
		opts->thin = !!value;
134
		return 0;
135
	} else if (!strcmp(name, TRANS_OPT_FOLLOWTAGS)) {
136
		opts->followtags = !!value;
137
		return 0;
138
	} else if (!strcmp(name, TRANS_OPT_KEEP)) {
139
		opts->keep = !!value;
140
		return 0;
141 142 143
	} else if (!strcmp(name, TRANS_OPT_UPDATE_SHALLOW)) {
		opts->update_shallow = !!value;
		return 0;
144 145
	} else if (!strcmp(name, TRANS_OPT_DEPTH)) {
		if (!value)
146
			opts->depth = 0;
147 148 149 150
		else {
			char *end;
			opts->depth = strtol(value, &end, 0);
			if (*end)
151
				die(_("transport: invalid depth option '%s'"), value);
152
		}
153
		return 0;
154 155 156
	} else if (!strcmp(name, TRANS_OPT_DEEPEN_SINCE)) {
		opts->deepen_since = value;
		return 0;
157 158 159
	} else if (!strcmp(name, TRANS_OPT_DEEPEN_NOT)) {
		opts->deepen_not = (const struct string_list *)value;
		return 0;
160 161 162
	} else if (!strcmp(name, TRANS_OPT_DEEPEN_RELATIVE)) {
		opts->deepen_relative = !!value;
		return 0;
163 164 165 166
	}
	return 1;
}

167
static int connect_setup(struct transport *transport, int for_push)
168 169
{
	struct git_transport_data *data = transport->data;
170
	int flags = transport->verbose > 0 ? CONNECT_VERBOSE : 0;
I
Ilari Liusvaara 已提交
171 172 173 174

	if (data->conn)
		return 0;

175 176 177 178 179 180
	switch (transport->family) {
	case TRANSPORT_FAMILY_ALL: break;
	case TRANSPORT_FAMILY_IPV4: flags |= CONNECT_IPV4; break;
	case TRANSPORT_FAMILY_IPV6: flags |= CONNECT_IPV6; break;
	}

181 182 183
	data->conn = git_connect(data->fd, transport->url,
				 for_push ? data->options.receivepack :
				 data->options.uploadpack,
184
				 flags);
I
Ilari Liusvaara 已提交
185

186 187 188
	return 0;
}

189
static struct ref *get_refs_via_connect(struct transport *transport, int for_push)
190 191 192 193
{
	struct git_transport_data *data = transport->data;
	struct ref *refs;

194
	connect_setup(transport, for_push);
195
	get_remote_heads(data->fd[0], NULL, 0, &refs,
196 197
			 for_push ? REF_NORMAL : 0,
			 &data->extra_have,
198
			 &data->shallow);
I
Ilari Liusvaara 已提交
199
	data->got_remote_heads = 1;
200 201 202 203

	return refs;
}

204
static int fetch_refs_via_pack(struct transport *transport,
D
Daniel Barkalow 已提交
205
			       int nr_heads, struct ref **to_fetch)
206 207
{
	struct git_transport_data *data = transport->data;
208
	struct ref *refs;
209 210
	char *dest = xstrdup(transport->url);
	struct fetch_pack_args args;
211
	struct ref *refs_tmp = NULL;
212

213
	memset(&args, 0, sizeof(args));
214 215
	args.uploadpack = data->options.uploadpack;
	args.keep_pack = data->options.keep;
216
	args.lock_pack = 1;
217 218
	args.use_thin_pack = data->options.thin;
	args.include_tag = data->options.followtags;
J
Jeff King 已提交
219
	args.verbose = (transport->verbose > 1);
220
	args.quiet = (transport->verbose < 0);
221
	args.no_progress = !transport->progress;
222
	args.depth = data->options.depth;
223
	args.deepen_since = data->options.deepen_since;
224
	args.deepen_not = data->options.deepen_not;
225
	args.deepen_relative = data->options.deepen_relative;
226 227
	args.check_self_contained_and_connected =
		data->options.check_self_contained_and_connected;
228
	args.cloning = transport->cloning;
229
	args.update_shallow = data->options.update_shallow;
230

I
Ilari Liusvaara 已提交
231
	if (!data->got_remote_heads) {
232
		connect_setup(transport, 0);
233
		get_remote_heads(data->fd[0], NULL, 0, &refs_tmp, 0,
234
				 NULL, &data->shallow);
I
Ilari Liusvaara 已提交
235
		data->got_remote_heads = 1;
236 237
	}

238 239
	refs = fetch_pack(&args, data->fd, data->conn,
			  refs_tmp ? refs_tmp : transport->remote_refs,
240
			  dest, to_fetch, nr_heads, &data->shallow,
241
			  &transport->pack_lockfile);
242 243
	close(data->fd[0]);
	close(data->fd[1]);
244 245
	if (finish_connect(data->conn)) {
		free_refs(refs);
246
		refs = NULL;
247
	}
248
	data->conn = NULL;
I
Ilari Liusvaara 已提交
249
	data->got_remote_heads = 0;
250 251
	data->options.self_contained_and_connected =
		args.self_contained_and_connected;
252

253
	free_refs(refs_tmp);
254
	free_refs(refs);
255
	free(dest);
256
	return (refs ? 0 : -1);
257 258
}

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
static int push_had_errors(struct ref *ref)
{
	for (; ref; ref = ref->next) {
		switch (ref->status) {
		case REF_STATUS_NONE:
		case REF_STATUS_UPTODATE:
		case REF_STATUS_OK:
			break;
		default:
			return 1;
		}
	}
	return 0;
}

274
int transport_refs_pushed(struct ref *ref)
275 276 277 278 279 280 281 282 283 284 285 286 287
{
	for (; ref; ref = ref->next) {
		switch(ref->status) {
		case REF_STATUS_NONE:
		case REF_STATUS_UPTODATE:
			break;
		default:
			return 1;
		}
	}
	return 0;
}

288
void transport_update_tracking_ref(struct remote *remote, struct ref *ref, int verbose)
289 290 291 292 293 294 295 296 297 298 299 300 301
{
	struct refspec rs;

	if (ref->status != REF_STATUS_OK && ref->status != REF_STATUS_UPTODATE)
		return;

	rs.src = ref->name;
	rs.dst = NULL;

	if (!remote_find_tracking(remote, &rs)) {
		if (verbose)
			fprintf(stderr, "updating local tracking ref '%s'\n", rs.dst);
		if (ref->deletion) {
302
			delete_ref(NULL, rs.dst, NULL, 0);
303 304
		} else
			update_ref("update by push", rs.dst,
305
					ref->new_oid.hash, NULL, 0, 0);
306 307 308 309
		free(rs.dst);
	}
}

310 311 312
static void print_ref_status(char flag, const char *summary,
			     struct ref *to, struct ref *from, const char *msg,
			     int porcelain, int summary_width)
313
{
314 315 316 317 318 319 320 321 322 323
	if (porcelain) {
		if (from)
			fprintf(stdout, "%c\t%s:%s\t", flag, from->name, to->name);
		else
			fprintf(stdout, "%c\t:%s\t", flag, to->name);
		if (msg)
			fprintf(stdout, "%s (%s)\n", summary, msg);
		else
			fprintf(stdout, "%s\n", summary);
	} else {
324
		fprintf(stderr, " %c %-*s ", flag, summary_width, summary);
325 326 327 328 329 330 331 332 333 334
		if (from)
			fprintf(stderr, "%s -> %s", prettify_refname(from->name), prettify_refname(to->name));
		else
			fputs(prettify_refname(to->name), stderr);
		if (msg) {
			fputs(" (", stderr);
			fputs(msg, stderr);
			fputc(')', stderr);
		}
		fputc('\n', stderr);
335 336 337
	}
}

338
static void print_ok_ref_status(struct ref *ref, int porcelain, int summary_width)
339 340
{
	if (ref->deletion)
341 342
		print_ref_status('-', "[deleted]", ref, NULL, NULL,
				 porcelain, summary_width);
343
	else if (is_null_oid(&ref->old_oid))
344
		print_ref_status('*',
345
			(starts_with(ref->name, "refs/tags/") ? "[new tag]" :
346
			"[new branch]"),
347
			ref, ref->peer_ref, NULL, porcelain, summary_width);
348
	else {
349
		struct strbuf quickref = STRBUF_INIT;
350 351 352
		char type;
		const char *msg;

353 354
		strbuf_add_unique_abbrev(&quickref, ref->old_oid.hash,
					 DEFAULT_ABBREV);
355
		if (ref->forced_update) {
356
			strbuf_addstr(&quickref, "...");
357 358 359
			type = '+';
			msg = "forced update";
		} else {
360
			strbuf_addstr(&quickref, "..");
361 362 363
			type = ' ';
			msg = NULL;
		}
364 365
		strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash,
					 DEFAULT_ABBREV);
366

367 368
		print_ref_status(type, quickref.buf, ref, ref->peer_ref, msg,
				 porcelain, summary_width);
369
		strbuf_release(&quickref);
370 371 372
	}
}

373 374
static int print_one_push_status(struct ref *ref, const char *dest, int count,
				 int porcelain, int summary_width)
375
{
J
Jeff King 已提交
376 377 378 379 380
	if (!count) {
		char *url = transport_anonymize_url(dest);
		fprintf(porcelain ? stdout : stderr, "To %s\n", url);
		free(url);
	}
381 382 383

	switch(ref->status) {
	case REF_STATUS_NONE:
384 385
		print_ref_status('X', "[no match]", ref, NULL, NULL,
				 porcelain, summary_width);
386 387 388
		break;
	case REF_STATUS_REJECT_NODELETE:
		print_ref_status('!', "[rejected]", ref, NULL,
389 390
				 "remote does not support deleting refs",
				 porcelain, summary_width);
391 392 393
		break;
	case REF_STATUS_UPTODATE:
		print_ref_status('=', "[up to date]", ref,
394
				 ref->peer_ref, NULL, porcelain, summary_width);
395 396 397
		break;
	case REF_STATUS_REJECT_NONFASTFORWARD:
		print_ref_status('!', "[rejected]", ref, ref->peer_ref,
398
				 "non-fast-forward", porcelain, summary_width);
399
		break;
400 401
	case REF_STATUS_REJECT_ALREADY_EXISTS:
		print_ref_status('!', "[rejected]", ref, ref->peer_ref,
402
				 "already exists", porcelain, summary_width);
403
		break;
404 405
	case REF_STATUS_REJECT_FETCH_FIRST:
		print_ref_status('!', "[rejected]", ref, ref->peer_ref,
406
				 "fetch first", porcelain, summary_width);
407 408 409
		break;
	case REF_STATUS_REJECT_NEEDS_FORCE:
		print_ref_status('!', "[rejected]", ref, ref->peer_ref,
410
				 "needs force", porcelain, summary_width);
411
		break;
412 413
	case REF_STATUS_REJECT_STALE:
		print_ref_status('!', "[rejected]", ref, ref->peer_ref,
414
				 "stale info", porcelain, summary_width);
415
		break;
416 417
	case REF_STATUS_REJECT_SHALLOW:
		print_ref_status('!', "[rejected]", ref, ref->peer_ref,
418 419
				 "new shallow roots not allowed",
				 porcelain, summary_width);
420
		break;
421 422
	case REF_STATUS_REMOTE_REJECT:
		print_ref_status('!', "[remote rejected]", ref,
423 424
				 ref->deletion ? NULL : ref->peer_ref,
				 ref->remote_status, porcelain, summary_width);
425 426 427
		break;
	case REF_STATUS_EXPECTING_REPORT:
		print_ref_status('!', "[remote failure]", ref,
428 429 430
				 ref->deletion ? NULL : ref->peer_ref,
				 "remote failed to report status",
				 porcelain, summary_width);
431
		break;
432 433
	case REF_STATUS_ATOMIC_PUSH_FAILED:
		print_ref_status('!', "[rejected]", ref, ref->peer_ref,
434
				 "atomic push failed", porcelain, summary_width);
435
		break;
436
	case REF_STATUS_OK:
437
		print_ok_ref_status(ref, porcelain, summary_width);
438 439 440 441 442 443
		break;
	}

	return 1;
}

444 445 446 447 448 449 450 451
static int measure_abbrev(const struct object_id *oid, int sofar)
{
	char hex[GIT_SHA1_HEXSZ + 1];
	int w = find_unique_abbrev_r(hex, oid->hash, DEFAULT_ABBREV);

	return (w < sofar) ? sofar : w;
}

452 453
int transport_summary_width(const struct ref *refs)
{
454 455 456 457 458 459 460 461 462
	int maxw = -1;

	for (; refs; refs = refs->next) {
		maxw = measure_abbrev(&refs->old_oid, maxw);
		maxw = measure_abbrev(&refs->new_oid, maxw);
	}
	if (maxw < 0)
		maxw = FALLBACK_DEFAULT_ABBREV;
	return (2 * maxw + 3);
463 464
}

465
void transport_print_push_status(const char *dest, struct ref *refs,
466
				  int verbose, int porcelain, unsigned int *reject_reasons)
467 468 469
{
	struct ref *ref;
	int n = 0;
470 471
	unsigned char head_sha1[20];
	char *head;
472
	int summary_width = transport_summary_width(refs);
473

474
	head = resolve_refdup("HEAD", RESOLVE_REF_READING, head_sha1, NULL);
475 476 477 478

	if (verbose) {
		for (ref = refs; ref; ref = ref->next)
			if (ref->status == REF_STATUS_UPTODATE)
479 480
				n += print_one_push_status(ref, dest, n,
							   porcelain, summary_width);
481 482 483 484
	}

	for (ref = refs; ref; ref = ref->next)
		if (ref->status == REF_STATUS_OK)
485 486
			n += print_one_push_status(ref, dest, n,
						   porcelain, summary_width);
487

488
	*reject_reasons = 0;
489 490 491 492
	for (ref = refs; ref; ref = ref->next) {
		if (ref->status != REF_STATUS_NONE &&
		    ref->status != REF_STATUS_UPTODATE &&
		    ref->status != REF_STATUS_OK)
493 494
			n += print_one_push_status(ref, dest, n,
						   porcelain, summary_width);
495
		if (ref->status == REF_STATUS_REJECT_NONFASTFORWARD) {
496
			if (head != NULL && !strcmp(head, ref->name))
497
				*reject_reasons |= REJECT_NON_FF_HEAD;
498
			else
499
				*reject_reasons |= REJECT_NON_FF_OTHER;
500 501
		} else if (ref->status == REF_STATUS_REJECT_ALREADY_EXISTS) {
			*reject_reasons |= REJECT_ALREADY_EXISTS;
502 503 504 505
		} else if (ref->status == REF_STATUS_REJECT_FETCH_FIRST) {
			*reject_reasons |= REJECT_FETCH_FIRST;
		} else if (ref->status == REF_STATUS_REJECT_NEEDS_FORCE) {
			*reject_reasons |= REJECT_NEEDS_FORCE;
506
		}
507
	}
508
	free(head);
509 510
}

511
void transport_verify_remote_names(int nr_heads, const char **heads)
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
{
	int i;

	for (i = 0; i < nr_heads; i++) {
		const char *local = heads[i];
		const char *remote = strrchr(heads[i], ':');

		if (*local == '+')
			local++;

		/* A matching refspec is okay.  */
		if (remote == local && remote[1] == '\0')
			continue;

		remote = remote ? (remote + 1) : local;
527 528 529 530
		if (check_refname_format(remote,
				REFNAME_ALLOW_ONELEVEL|REFNAME_REFSPEC_PATTERN))
			die("remote part of refspec is not a valid name in %s",
				heads[i]);
531 532 533 534
	}
}

static int git_transport_push(struct transport *transport, struct ref *remote_refs, int flags)
535
{
536
	struct git_transport_data *data = transport->data;
D
Daniel Barkalow 已提交
537
	struct send_pack_args args;
538 539
	int ret;

I
Ilari Liusvaara 已提交
540
	if (!data->got_remote_heads) {
541
		struct ref *tmp_refs;
542
		connect_setup(transport, 1);
543

544 545
		get_remote_heads(data->fd[0], NULL, 0, &tmp_refs, REF_NORMAL,
				 NULL, &data->shallow);
I
Ilari Liusvaara 已提交
546
		data->got_remote_heads = 1;
547
	}
548

549
	memset(&args, 0, sizeof(args));
A
Andy Whitcroft 已提交
550
	args.send_mirror = !!(flags & TRANSPORT_PUSH_MIRROR);
D
Daniel Barkalow 已提交
551
	args.force_update = !!(flags & TRANSPORT_PUSH_FORCE);
552
	args.use_thin_pack = data->options.thin;
553 554
	args.verbose = (transport->verbose > 0);
	args.quiet = (transport->verbose < 0);
555
	args.progress = transport->progress;
D
Daniel Barkalow 已提交
556
	args.dry_run = !!(flags & TRANSPORT_PUSH_DRY_RUN);
557
	args.porcelain = !!(flags & TRANSPORT_PUSH_PORCELAIN);
558
	args.atomic = !!(flags & TRANSPORT_PUSH_ATOMIC);
S
Stefan Beller 已提交
559
	args.push_options = transport->push_options;
560
	args.url = transport->url;
D
Daniel Barkalow 已提交
561

562 563 564 565 566 567 568
	if (flags & TRANSPORT_PUSH_CERT_ALWAYS)
		args.push_cert = SEND_PACK_PUSH_CERT_ALWAYS;
	else if (flags & TRANSPORT_PUSH_CERT_IF_ASKED)
		args.push_cert = SEND_PACK_PUSH_CERT_IF_ASKED;
	else
		args.push_cert = SEND_PACK_PUSH_CERT_NEVER;

569 570 571 572 573 574 575
	ret = send_pack(&args, data->fd, data->conn, remote_refs,
			&data->extra_have);

	close(data->fd[1]);
	close(data->fd[0]);
	ret |= finish_connect(data->conn);
	data->conn = NULL;
I
Ilari Liusvaara 已提交
576
	data->got_remote_heads = 0;
577 578

	return ret;
579 580
}

581 582 583 584 585 586 587 588 589 590 591
static int connect_git(struct transport *transport, const char *name,
		       const char *executable, int fd[2])
{
	struct git_transport_data *data = transport->data;
	data->conn = git_connect(data->fd, transport->url,
				 executable, 0);
	fd[0] = data->fd[0];
	fd[1] = data->fd[1];
	return 0;
}

592 593
static int disconnect_git(struct transport *transport)
{
594 595
	struct git_transport_data *data = transport->data;
	if (data->conn) {
I
Ilari Liusvaara 已提交
596 597
		if (data->got_remote_heads)
			packet_flush(data->fd[1]);
598 599 600 601 602 603
		close(data->fd[0]);
		close(data->fd[1]);
		finish_connect(data->conn);
	}

	free(data);
604 605 606
	return 0;
}

I
Ilari Liusvaara 已提交
607 608 609 610 611 612
void transport_take_over(struct transport *transport,
			 struct child_process *child)
{
	struct git_transport_data *data;

	if (!transport->smart_options)
613
		die("BUG: taking over transport requires non-NULL "
I
Ilari Liusvaara 已提交
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
		    "smart_options field.");

	data = xcalloc(1, sizeof(*data));
	data->options = *transport->smart_options;
	data->conn = child;
	data->fd[0] = data->conn->out;
	data->fd[1] = data->conn->in;
	data->got_remote_heads = 0;
	transport->data = data;

	transport->set_option = NULL;
	transport->get_refs_list = get_refs_via_connect;
	transport->fetch = fetch_refs_via_pack;
	transport->push = NULL;
	transport->push_refs = git_transport_push;
	transport->disconnect = disconnect_git;
	transport->smart_options = &(data->options);
631 632

	transport->cannot_reuse = 1;
I
Ilari Liusvaara 已提交
633 634
}

635 636 637 638 639 640 641 642
static int is_file(const char *url)
{
	struct stat buf;
	if (stat(url, &buf))
		return 0;
	return S_ISREG(buf.st_mode);
}

643 644 645 646 647
static int external_specification_len(const char *url)
{
	return strchr(url, ':') - url;
}

648
static const struct string_list *protocol_whitelist(void)
649
{
650 651
	static int enabled = -1;
	static struct string_list allowed = STRING_LIST_INIT_DUP;
652

653 654 655 656 657 658 659 660 661 662 663 664 665
	if (enabled < 0) {
		const char *v = getenv("GIT_ALLOW_PROTOCOL");
		if (v) {
			string_list_split(&allowed, v, ':', -1);
			string_list_sort(&allowed);
			enabled = 1;
		} else {
			enabled = 0;
		}
	}

	return enabled ? &allowed : NULL;
}
666

667 668 669 670 671 672 673 674
enum protocol_allow_config {
	PROTOCOL_ALLOW_NEVER = 0,
	PROTOCOL_ALLOW_USER_ONLY,
	PROTOCOL_ALLOW_ALWAYS
};

static enum protocol_allow_config parse_protocol_config(const char *key,
							const char *value)
675
{
676 677 678 679 680 681 682 683
	if (!strcasecmp(value, "always"))
		return PROTOCOL_ALLOW_ALWAYS;
	else if (!strcasecmp(value, "never"))
		return PROTOCOL_ALLOW_NEVER;
	else if (!strcasecmp(value, "user"))
		return PROTOCOL_ALLOW_USER_ONLY;

	die("unknown value for config '%s': %s", key, value);
684 685
}

686
static enum protocol_allow_config get_protocol_config(const char *type)
687
{
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
	char *key = xstrfmt("protocol.%s.allow", type);
	char *value;

	/* first check the per-protocol config */
	if (!git_config_get_string(key, &value)) {
		enum protocol_allow_config ret =
			parse_protocol_config(key, value);
		free(key);
		free(value);
		return ret;
	}
	free(key);

	/* if defined, fallback to user-defined default for unknown protocols */
	if (!git_config_get_string("protocol.allow", &value)) {
		enum protocol_allow_config ret =
			parse_protocol_config("protocol.allow", value);
		free(value);
		return ret;
	}

	/* fallback to built-in defaults */
	/* known safe */
	if (!strcmp(type, "http") ||
	    !strcmp(type, "https") ||
	    !strcmp(type, "git") ||
	    !strcmp(type, "ssh") ||
	    !strcmp(type, "file"))
		return PROTOCOL_ALLOW_ALWAYS;

	/* known scary; err on the side of caution */
	if (!strcmp(type, "ext"))
		return PROTOCOL_ALLOW_NEVER;

	/* unknown; by default let them be used only directly by the user */
	return PROTOCOL_ALLOW_USER_ONLY;
724 725
}

726
int is_transport_allowed(const char *type, int from_user)
727
{
728 729 730 731 732 733 734 735 736 737
	const struct string_list *whitelist = protocol_whitelist();
	if (whitelist)
		return string_list_has_string(whitelist, type);

	switch (get_protocol_config(type)) {
	case PROTOCOL_ALLOW_ALWAYS:
		return 1;
	case PROTOCOL_ALLOW_NEVER:
		return 0;
	case PROTOCOL_ALLOW_USER_ONLY:
738 739 740
		if (from_user < 0)
			from_user = git_env_bool("GIT_PROTOCOL_FROM_USER", 1);
		return from_user;
741 742 743
	}

	die("BUG: invalid protocol_allow_config type");
744 745 746 747
}

void transport_check_allowed(const char *type)
{
748
	if (!is_transport_allowed(type, -1))
749 750 751
		die("transport '%s' not allowed", type);
}

752
struct transport *transport_get(struct remote *remote, const char *url)
753
{
I
Ilari Liusvaara 已提交
754
	const char *helper;
755 756
	struct transport *ret = xcalloc(1, sizeof(*ret));

757 758
	ret->progress = isatty(2);

759 760 761
	if (!remote)
		die("No remote provided to transport_get()");

762
	ret->got_remote_refs = 0;
763
	ret->remote = remote;
I
Ilari Liusvaara 已提交
764
	helper = remote->foreign_vcs;
765

766
	if (!url && remote->url)
767
		url = remote->url[0];
768 769
	ret->url = url;

770 771 772 773
	/* maybe it is a foreign URL? */
	if (url) {
		const char *p = url;

J
Jeff King 已提交
774
		while (is_urlschemechar(p == url, *p))
775
			p++;
776
		if (starts_with(p, "::"))
I
Ilari Liusvaara 已提交
777
			helper = xstrndup(url, p - url);
778 779
	}

I
Ilari Liusvaara 已提交
780 781
	if (helper) {
		transport_helper_init(ret, helper);
782
	} else if (starts_with(url, "rsync:")) {
783
		die("git-over-rsync is no longer supported");
784
	} else if (url_is_local_not_ssh(url) && is_file(url) && is_bundle(url, 1)) {
J
Johannes Schindelin 已提交
785
		struct bundle_transport_data *data = xcalloc(1, sizeof(*data));
786
		transport_check_allowed("file");
J
Johannes Schindelin 已提交
787
		ret->data = data;
788 789 790
		ret->get_refs_list = get_refs_from_bundle;
		ret->fetch = fetch_refs_from_bundle;
		ret->disconnect = close_bundle;
791
		ret->smart_options = NULL;
792
	} else if (!is_url(url)
793 794 795
		|| starts_with(url, "file://")
		|| starts_with(url, "git://")
		|| starts_with(url, "ssh://")
796 797 798
		|| starts_with(url, "git+ssh://") /* deprecated - do not use */
		|| starts_with(url, "ssh+git://") /* deprecated - do not use */
		) {
799 800 801 802
		/*
		 * These are builtin smart transports; "allowed" transports
		 * will be checked individually in git_connect.
		 */
803 804
		struct git_transport_data *data = xcalloc(1, sizeof(*data));
		ret->data = data;
805
		ret->set_option = NULL;
806 807
		ret->get_refs_list = get_refs_via_connect;
		ret->fetch = fetch_refs_via_pack;
808
		ret->push_refs = git_transport_push;
809
		ret->connect = connect_git;
810
		ret->disconnect = disconnect_git;
811
		ret->smart_options = &(data->options);
812

813
		data->conn = NULL;
I
Ilari Liusvaara 已提交
814
		data->got_remote_heads = 0;
815 816 817
	} else {
		/* Unknown protocol in URL. Pass to external handler. */
		int len = external_specification_len(url);
818
		char *handler = xmemdupz(url, len);
819
		transport_helper_init(ret, handler);
820
	}
821

822 823 824 825 826 827 828 829 830 831
	if (ret->smart_options) {
		ret->smart_options->thin = 1;
		ret->smart_options->uploadpack = "git-upload-pack";
		if (remote->uploadpack)
			ret->smart_options->uploadpack = remote->uploadpack;
		ret->smart_options->receivepack = "git-receive-pack";
		if (remote->receivepack)
			ret->smart_options->receivepack = remote->receivepack;
	}

832 833 834 835 836 837
	return ret;
}

int transport_set_option(struct transport *transport,
			 const char *name, const char *value)
{
838 839 840 841 842 843
	int git_reports = 1, protocol_reports = 1;

	if (transport->smart_options)
		git_reports = set_git_option(transport->smart_options,
					     name, value);

844
	if (transport->set_option)
845 846 847 848 849 850 851 852 853 854
		protocol_reports = transport->set_option(transport, name,
							value);

	/* If either report is 0, report 0 (success). */
	if (!git_reports || !protocol_reports)
		return 0;
	/* If either reports -1 (invalid value), report -1. */
	if ((git_reports == -1) || (protocol_reports == -1))
		return -1;
	/* Otherwise if both report unknown, report unknown. */
855
	return 1;
856 857
}

858 859
void transport_set_verbosity(struct transport *transport, int verbosity,
	int force_progress)
860
{
J
Jeff King 已提交
861
	if (verbosity >= 1)
862 863 864
		transport->verbose = verbosity <= 3 ? verbosity : 3;
	if (verbosity < 0)
		transport->verbose = -1;
865 866 867 868 869

	/**
	 * Rules used to determine whether to report progress (processing aborts
	 * when a rule is satisfied):
	 *
870 871 872 873
	 *   . Report progress, if force_progress is 1 (ie. --progress).
	 *   . Don't report progress, if force_progress is 0 (ie. --no-progress).
	 *   . Don't report progress, if verbosity < 0 (ie. -q/--quiet ).
	 *   . Report progress if isatty(2) is 1.
874
	 **/
875 876 877 878
	if (force_progress >= 0)
		transport->progress = !!force_progress;
	else
		transport->progress = verbosity >= 0 && isatty(2);
879 880
}

881 882 883 884
static void die_with_unpushed_submodules(struct string_list *needs_pushing)
{
	int i;

885 886
	fprintf(stderr, _("The following submodule paths contain changes that can\n"
			"not be found on any remote:\n"));
887
	for (i = 0; i < needs_pushing->nr; i++)
888
		fprintf(stderr, "  %s\n", needs_pushing->items[i].string);
889 890 891 892 893
	fprintf(stderr, _("\nPlease try\n\n"
			  "	git push --recurse-submodules=on-demand\n\n"
			  "or cd to the path and use\n\n"
			  "	git push\n\n"
			  "to push them to a remote.\n\n"));
894 895 896

	string_list_clear(needs_pushing, 0);

897
	die(_("Aborting."));
898 899
}

900 901 902 903 904
static int run_pre_push_hook(struct transport *transport,
			     struct ref *remote_refs)
{
	int ret = 0, x;
	struct ref *r;
905
	struct child_process proc = CHILD_PROCESS_INIT;
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
	struct strbuf buf;
	const char *argv[4];

	if (!(argv[0] = find_hook("pre-push")))
		return 0;

	argv[1] = transport->remote->name;
	argv[2] = transport->url;
	argv[3] = NULL;

	proc.argv = argv;
	proc.in = -1;

	if (start_command(&proc)) {
		finish_command(&proc);
		return -1;
	}

924 925
	sigchain_push(SIGPIPE, SIG_IGN);

926 927 928 929 930
	strbuf_init(&buf, 256);

	for (r = remote_refs; r; r = r->next) {
		if (!r->peer_ref) continue;
		if (r->status == REF_STATUS_REJECT_NONFASTFORWARD) continue;
931
		if (r->status == REF_STATUS_REJECT_STALE) continue;
932 933 934 935
		if (r->status == REF_STATUS_UPTODATE) continue;

		strbuf_reset(&buf);
		strbuf_addf( &buf, "%s %s %s %s\n",
936 937
			 r->peer_ref->name, oid_to_hex(&r->new_oid),
			 r->name, oid_to_hex(&r->old_oid));
938

939 940 941 942
		if (write_in_full(proc.in, buf.buf, buf.len) < 0) {
			/* We do not mind if a hook does not read all refs. */
			if (errno != EPIPE)
				ret = -1;
943 944 945 946 947 948 949 950 951 952
			break;
		}
	}

	strbuf_release(&buf);

	x = close(proc.in);
	if (!ret)
		ret = x;

953 954
	sigchain_pop(SIGPIPE);

955 956 957 958 959 960 961
	x = finish_command(&proc);
	if (!ret)
		ret = x;

	return ret;
}

962
int transport_push(struct transport *transport,
963
		   int refspec_nr, const char **refspec, int flags,
964
		   unsigned int *reject_reasons)
965
{
966
	*reject_reasons = 0;
967
	transport_verify_remote_names(refspec_nr, refspec);
968

I
Ilari Liusvaara 已提交
969
	if (transport->push) {
I
Ilari Liusvaara 已提交
970 971 972 973
		/* Maybe FIXME. But no important transport uses this case. */
		if (flags & TRANSPORT_PUSH_SET_UPSTREAM)
			die("This transport does not support using --set-upstream");

974
		return transport->push(transport, refspec_nr, refspec, flags);
I
Ilari Liusvaara 已提交
975
	} else if (transport->push_refs) {
976
		struct ref *remote_refs;
977 978
		struct ref *local_refs = get_local_heads();
		int match_flags = MATCH_REFS_NONE;
979 980
		int verbose = (transport->verbose > 0);
		int quiet = (transport->verbose < 0);
981
		int porcelain = flags & TRANSPORT_PUSH_PORCELAIN;
I
Ilari Liusvaara 已提交
982
		int pretend = flags & TRANSPORT_PUSH_DRY_RUN;
983
		int push_ret, ret, err;
984

985 986 987 988 989
		if (check_push_refs(local_refs, refspec_nr, refspec) < 0)
			return -1;

		remote_refs = transport->get_refs_list(transport, 1);

990 991 992 993
		if (flags & TRANSPORT_PUSH_ALL)
			match_flags |= MATCH_REFS_ALL;
		if (flags & TRANSPORT_PUSH_MIRROR)
			match_flags |= MATCH_REFS_MIRROR;
F
Felipe Contreras 已提交
994 995
		if (flags & TRANSPORT_PUSH_PRUNE)
			match_flags |= MATCH_REFS_PRUNE;
J
Junio C Hamano 已提交
996 997
		if (flags & TRANSPORT_PUSH_FOLLOW_TAGS)
			match_flags |= MATCH_REFS_FOLLOW_TAGS;
998

999 1000
		if (match_push_refs(local_refs, &remote_refs,
				    refspec_nr, refspec, match_flags)) {
1001 1002 1003
			return -1;
		}

1004 1005 1006 1007 1008 1009
		if (transport->smart_options &&
		    transport->smart_options->cas &&
		    !is_empty_cas(transport->smart_options->cas))
			apply_push_cas(transport->smart_options->cas,
				       transport->remote, remote_refs);

1010 1011 1012 1013
		set_ref_status_for_push(remote_refs,
			flags & TRANSPORT_PUSH_MIRROR,
			flags & TRANSPORT_PUSH_FORCE);

1014 1015 1016 1017
		if (!(flags & TRANSPORT_PUSH_NO_HOOK))
			if (run_pre_push_hook(transport, remote_refs))
				return -1;

1018 1019 1020
		if ((flags & (TRANSPORT_RECURSE_SUBMODULES_ON_DEMAND |
			      TRANSPORT_RECURSE_SUBMODULES_ONLY)) &&
		    !is_bare_repository()) {
1021
			struct ref *ref = remote_refs;
1022 1023
			struct sha1_array commits = SHA1_ARRAY_INIT;

1024
			for (; ref; ref = ref->next)
1025 1026 1027
				if (!is_null_oid(&ref->new_oid))
					sha1_array_append(&commits, ref->new_oid.hash);

1028 1029 1030
			if (!push_unpushed_submodules(&commits,
						      transport->remote->name,
						      pretend)) {
1031 1032 1033 1034
				sha1_array_clear(&commits);
				die("Failed to push all needed submodules!");
			}
			sha1_array_clear(&commits);
1035 1036
		}

1037
		if (((flags & TRANSPORT_RECURSE_SUBMODULES_CHECK) ||
1038 1039
		     ((flags & (TRANSPORT_RECURSE_SUBMODULES_ON_DEMAND |
				TRANSPORT_RECURSE_SUBMODULES_ONLY)) &&
1040
		      !pretend)) && !is_bare_repository()) {
1041
			struct ref *ref = remote_refs;
1042
			struct string_list needs_pushing = STRING_LIST_INIT_DUP;
1043
			struct sha1_array commits = SHA1_ARRAY_INIT;
1044

1045
			for (; ref; ref = ref->next)
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
				if (!is_null_oid(&ref->new_oid))
					sha1_array_append(&commits, ref->new_oid.hash);

			if (find_unpushed_submodules(&commits, transport->remote->name,
						&needs_pushing)) {
				sha1_array_clear(&commits);
				die_with_unpushed_submodules(&needs_pushing);
			}
			string_list_clear(&needs_pushing, 0);
			sha1_array_clear(&commits);
1056 1057
		}

1058 1059 1060 1061
		if (!(flags & TRANSPORT_RECURSE_SUBMODULES_ONLY))
			push_ret = transport->push_refs(transport, remote_refs, flags);
		else
			push_ret = 0;
1062
		err = push_had_errors(remote_refs);
1063
		ret = push_ret | err;
1064

1065
		if (!quiet || err)
1066
			transport_print_push_status(transport->url, remote_refs,
J
Junio C Hamano 已提交
1067
					verbose | porcelain, porcelain,
1068
					reject_reasons);
1069

I
Ilari Liusvaara 已提交
1070 1071 1072
		if (flags & TRANSPORT_PUSH_SET_UPSTREAM)
			set_upstreams(transport, remote_refs, pretend);

1073 1074
		if (!(flags & (TRANSPORT_PUSH_DRY_RUN |
			       TRANSPORT_RECURSE_SUBMODULES_ONLY))) {
1075 1076
			struct ref *ref;
			for (ref = remote_refs; ref; ref = ref->next)
1077
				transport_update_tracking_ref(transport->remote, ref, verbose);
1078 1079
		}

1080 1081
		if (porcelain && !push_ret)
			puts("Done");
1082
		else if (!quiet && !ret && !transport_refs_pushed(remote_refs))
1083
			fprintf(stderr, "Everything up-to-date\n");
1084

1085 1086 1087
		return ret;
	}
	return 1;
1088 1089
}

1090
const struct ref *transport_get_remote_refs(struct transport *transport)
1091
{
1092
	if (!transport->got_remote_refs) {
1093
		transport->remote_refs = transport->get_refs_list(transport, 0);
1094 1095
		transport->got_remote_refs = 1;
	}
I
Ilari Liusvaara 已提交
1096

1097 1098 1099
	return transport->remote_refs;
}

D
Daniel Barkalow 已提交
1100
int transport_fetch_refs(struct transport *transport, struct ref *refs)
1101
{
1102
	int rc;
N
Nicolas Pitre 已提交
1103
	int nr_heads = 0, nr_alloc = 0, nr_refs = 0;
D
Daniel Barkalow 已提交
1104 1105
	struct ref **heads = NULL;
	struct ref *rm;
1106 1107

	for (rm = refs; rm; rm = rm->next) {
N
Nicolas Pitre 已提交
1108
		nr_refs++;
1109
		if (rm->peer_ref &&
1110 1111
		    !is_null_oid(&rm->old_oid) &&
		    !oidcmp(&rm->peer_ref->old_oid, &rm->old_oid))
1112
			continue;
1113
		ALLOC_GROW(heads, nr_heads + 1, nr_alloc);
1114
		heads[nr_heads++] = rm;
1115 1116
	}

N
Nicolas Pitre 已提交
1117 1118 1119 1120 1121 1122
	if (!nr_heads) {
		/*
		 * When deepening of a shallow repository is requested,
		 * then local and remote refs are likely to still be equal.
		 * Just feed them all to the fetch method in that case.
		 * This condition shouldn't be met in a non-deepening fetch
1123
		 * (see builtin/fetch.c:quickfetch()).
N
Nicolas Pitre 已提交
1124
		 */
J
Jeff King 已提交
1125
		ALLOC_ARRAY(heads, nr_refs);
N
Nicolas Pitre 已提交
1126 1127 1128 1129
		for (rm = refs; rm; rm = rm->next)
			heads[nr_heads++] = rm;
	}

1130
	rc = transport->fetch(transport, nr_heads, heads);
I
Ilari Liusvaara 已提交
1131

1132
	free(heads);
1133
	return rc;
1134 1135
}

1136 1137 1138
void transport_unlock_pack(struct transport *transport)
{
	if (transport->pack_lockfile) {
1139
		unlink_or_warn(transport->pack_lockfile);
1140 1141 1142 1143 1144
		free(transport->pack_lockfile);
		transport->pack_lockfile = NULL;
	}
}

1145 1146 1147 1148 1149 1150 1151 1152 1153
int transport_connect(struct transport *transport, const char *name,
		      const char *exec, int fd[2])
{
	if (transport->connect)
		return transport->connect(transport, name, exec, fd);
	else
		die("Operation not supported by protocol");
}

1154 1155 1156
int transport_disconnect(struct transport *transport)
{
	int ret = 0;
1157 1158
	if (transport->disconnect)
		ret = transport->disconnect(transport);
1159 1160 1161
	free(transport);
	return ret;
}
1162 1163

/*
J
Jim Meyering 已提交
1164
 * Strip username (and password) from a URL and return
1165 1166 1167 1168
 * it in a newly allocated string.
 */
char *transport_anonymize_url(const char *url)
{
J
Jeff King 已提交
1169
	char *scheme_prefix, *anon_part;
1170 1171 1172
	size_t anon_len, prefix_len = 0;

	anon_part = strchr(url, '@');
1173
	if (url_is_local_not_ssh(url) || !anon_part)
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
		goto literal_copy;

	anon_len = strlen(++anon_part);
	scheme_prefix = strstr(url, "://");
	if (!scheme_prefix) {
		if (!strchr(anon_part, ':'))
			/* cannot be "me@there:/path/name" */
			goto literal_copy;
	} else {
		const char *cp;
		/* make sure scheme is reasonable */
		for (cp = url; cp < scheme_prefix; cp++) {
			switch (*cp) {
				/* RFC 1738 2.1 */
			case '+': case '.': case '-':
				break; /* ok */
			default:
				if (isalnum(*cp))
					break;
				/* it isn't */
				goto literal_copy;
			}
		}
		/* @ past the first slash does not count */
		cp = strchr(scheme_prefix + 3, '/');
		if (cp && cp < anon_part)
			goto literal_copy;
		prefix_len = scheme_prefix - url + 3;
	}
J
Jeff King 已提交
1203 1204
	return xstrfmt("%.*s%.*s", (int)prefix_len, url,
		       (int)anon_len, anon_part);
1205 1206 1207
literal_copy:
	return xstrdup(url);
}
1208

1209 1210 1211 1212 1213 1214 1215
struct alternate_refs_data {
	alternate_ref_fn *fn;
	void *data;
};

static int refs_from_alternate_cb(struct alternate_object_database *e,
				  void *data)
1216 1217 1218 1219 1220 1221
{
	char *other;
	size_t len;
	struct remote *remote;
	struct transport *transport;
	const struct ref *extra;
1222
	struct alternate_refs_data *cb = data;
1223

1224
	other = real_pathdup(e->path);
1225 1226 1227 1228 1229
	len = strlen(other);

	while (other[len-1] == '/')
		other[--len] = '\0';
	if (len < 8 || memcmp(other + len - 8, "/objects", 8))
1230
		goto out;
1231 1232 1233
	/* Is this a git repository with refs? */
	memcpy(other + len - 8, "/refs", 6);
	if (!is_directory(other))
1234
		goto out;
1235 1236 1237 1238 1239 1240
	other[len - 8] = '\0';
	remote = remote_get(other);
	transport = transport_get(remote, other);
	for (extra = transport_get_remote_refs(transport);
	     extra;
	     extra = extra->next)
1241
		cb->fn(extra, cb->data);
1242
	transport_disconnect(transport);
1243
out:
1244 1245 1246
	free(other);
	return 0;
}
1247 1248 1249 1250 1251 1252 1253 1254

void for_each_alternate_ref(alternate_ref_fn fn, void *data)
{
	struct alternate_refs_data cb;
	cb.fn = fn;
	cb.data = data;
	foreach_alt_odb(refs_from_alternate_cb, &cb);
}