remote-curl.c 36.7 KB
Newer Older
1
#include "cache.h"
2
#include "config.h"
3
#include "remote.h"
4
#include "connect.h"
5 6 7
#include "strbuf.h"
#include "walker.h"
#include "http.h"
8
#include "exec-cmd.h"
9
#include "run-command.h"
10
#include "pkt-line.h"
11
#include "string-list.h"
12
#include "sideband.h"
13
#include "argv-array.h"
14
#include "credential.h"
15
#include "sha1-array.h"
16
#include "send-pack.h"
17
#include "protocol.h"
18
#include "quote.h"
19
#include "transport.h"
20

21
static struct remote *remote;
22 23
/* always ends with a trailing slash */
static struct strbuf url = STRBUF_INIT;
24

25 26 27
struct options {
	int verbosity;
	unsigned long depth;
28
	char *deepen_since;
29
	struct string_list deepen_not;
30
	struct string_list push_options;
Jeff Hostetler's avatar
Jeff Hostetler committed
31
	char *filter;
32
	unsigned progress : 1,
33
		check_self_contained_and_connected : 1,
34 35
		cloning : 1,
		update_shallow : 1,
36
		followtags : 1,
37
		dry_run : 1,
38
		thin : 1,
39
		/* One of the SEND_PACK_PUSH_CERT_* constants. */
40
		push_cert : 2,
41 42 43
		deepen_relative : 1,
		from_promisor : 1,
		no_dependents : 1;
44 45
};
static struct options options;
46
static struct string_list cas_options = STRING_LIST_INIT_DUP;
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

static int set_option(const char *name, const char *value)
{
	if (!strcmp(name, "verbosity")) {
		char *end;
		int v = strtol(value, &end, 10);
		if (value == end || *end)
			return -1;
		options.verbosity = v;
		return 0;
	}
	else if (!strcmp(name, "progress")) {
		if (!strcmp(value, "true"))
			options.progress = 1;
		else if (!strcmp(value, "false"))
			options.progress = 0;
		else
			return -1;
65
		return 0;
66 67 68 69 70 71 72
	}
	else if (!strcmp(name, "depth")) {
		char *end;
		unsigned long v = strtoul(value, &end, 10);
		if (value == end || *end)
			return -1;
		options.depth = v;
73
		return 0;
74
	}
75 76 77 78
	else if (!strcmp(name, "deepen-since")) {
		options.deepen_since = xstrdup(value);
		return 0;
	}
79 80 81 82
	else if (!strcmp(name, "deepen-not")) {
		string_list_append(&options.deepen_not, value);
		return 0;
	}
83 84 85 86 87 88 89 90 91
	else if (!strcmp(name, "deepen-relative")) {
		if (!strcmp(value, "true"))
			options.deepen_relative = 1;
		else if (!strcmp(value, "false"))
			options.deepen_relative = 0;
		else
			return -1;
		return 0;
	}
92 93 94 95 96 97 98
	else if (!strcmp(name, "followtags")) {
		if (!strcmp(value, "true"))
			options.followtags = 1;
		else if (!strcmp(value, "false"))
			options.followtags = 0;
		else
			return -1;
99
		return 0;
100
	}
101 102 103 104 105 106 107 108 109
	else if (!strcmp(name, "dry-run")) {
		if (!strcmp(value, "true"))
			options.dry_run = 1;
		else if (!strcmp(value, "false"))
			options.dry_run = 0;
		else
			return -1;
		return 0;
	}
110 111 112 113 114 115 116 117 118
	else if (!strcmp(name, "check-connectivity")) {
		if (!strcmp(value, "true"))
			options.check_self_contained_and_connected = 1;
		else if (!strcmp(value, "false"))
			options.check_self_contained_and_connected = 0;
		else
			return -1;
		return 0;
	}
119 120 121 122 123 124
	else if (!strcmp(name, "cas")) {
		struct strbuf val = STRBUF_INIT;
		strbuf_addf(&val, "--" CAS_OPT_NAME "=%s", value);
		string_list_append(&cas_options, val.buf);
		strbuf_release(&val);
		return 0;
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
	} else if (!strcmp(name, "cloning")) {
		if (!strcmp(value, "true"))
			options.cloning = 1;
		else if (!strcmp(value, "false"))
			options.cloning = 0;
		else
			return -1;
		return 0;
	} else if (!strcmp(name, "update-shallow")) {
		if (!strcmp(value, "true"))
			options.update_shallow = 1;
		else if (!strcmp(value, "false"))
			options.update_shallow = 0;
		else
			return -1;
		return 0;
141 142
	} else if (!strcmp(name, "pushcert")) {
		if (!strcmp(value, "true"))
143
			options.push_cert = SEND_PACK_PUSH_CERT_ALWAYS;
144
		else if (!strcmp(value, "false"))
145 146 147
			options.push_cert = SEND_PACK_PUSH_CERT_NEVER;
		else if (!strcmp(value, "if-asked"))
			options.push_cert = SEND_PACK_PUSH_CERT_IF_ASKED;
148 149 150
		else
			return -1;
		return 0;
151
	} else if (!strcmp(name, "push-option")) {
152 153 154 155 156
		if (*value != '"')
			string_list_append(&options.push_options, value);
		else {
			struct strbuf unquoted = STRBUF_INIT;
			if (unquote_c_style(&unquoted, value, NULL) < 0)
157
				die(_("invalid quoting in push-option value: '%s'"), value);
158 159 160
			string_list_append_nodup(&options.push_options,
						 strbuf_detach(&unquoted, NULL));
		}
161
		return 0;
162 163 164 165 166 167 168 169 170 171 172 173 174

#if LIBCURL_VERSION_NUM >= 0x070a08
	} else if (!strcmp(name, "family")) {
		if (!strcmp(value, "ipv4"))
			git_curl_ipresolve = CURL_IPRESOLVE_V4;
		else if (!strcmp(value, "ipv6"))
			git_curl_ipresolve = CURL_IPRESOLVE_V6;
		else if (!strcmp(value, "all"))
			git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
		else
			return -1;
		return 0;
#endif /* LIBCURL_VERSION_NUM >= 0x070a08 */
175 176 177 178 179 180
	} else if (!strcmp(name, "from-promisor")) {
		options.from_promisor = 1;
		return 0;
	} else if (!strcmp(name, "no-dependents")) {
		options.no_dependents = 1;
		return 0;
Jeff Hostetler's avatar
Jeff Hostetler committed
181
	} else if (!strcmp(name, "filter")) {
182
		options.filter = xstrdup(value);
Jeff Hostetler's avatar
Jeff Hostetler committed
183
		return 0;
184
	} else {
185 186 187 188
		return 1 /* unsupported */;
	}
}

189
struct discovery {
190
	char *service;
191 192 193
	char *buf_alloc;
	char *buf;
	size_t len;
194
	struct ref *refs;
195
	struct oid_array shallow;
196
	enum protocol_version version;
197 198 199 200
	unsigned proto_git : 1;
};
static struct discovery *last_discovery;

201 202 203
static struct ref *parse_git_refs(struct discovery *heads, int for_push)
{
	struct ref *list = NULL;
204 205 206 207
	struct packet_reader reader;

	packet_reader_init(&reader, -1, heads->buf, heads->len,
			   PACKET_READ_CHOMP_NEWLINE |
208 209
			   PACKET_READ_GENTLE_ON_EOF |
			   PACKET_READ_DIE_ON_ERR_PACKET);
210

211 212
	heads->version = discover_version(&reader);
	switch (heads->version) {
213
	case protocol_v2:
214 215 216 217 218 219
		/*
		 * Do nothing.  This isn't a list of refs but rather a
		 * capability advertisement.  Client would have run
		 * 'stateless-connect' so we'll dump this capability listing
		 * and let them request the refs themselves.
		 */
220
		break;
221 222 223 224 225 226 227 228 229
	case protocol_v1:
	case protocol_v0:
		get_remote_heads(&reader, &list, for_push ? REF_NORMAL : 0,
				 NULL, &heads->shallow);
		break;
	case protocol_unknown_version:
		BUG("unknown protocol version");
	}

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
	return list;
}

static struct ref *parse_info_refs(struct discovery *heads)
{
	char *data, *start, *mid;
	char *ref_name;
	int i = 0;

	struct ref *refs = NULL;
	struct ref *ref = NULL;
	struct ref *last_ref = NULL;

	data = heads->buf;
	start = NULL;
	mid = data;
	while (i < heads->len) {
		if (!start) {
			start = &data[i];
		}
		if (data[i] == '\t')
			mid = &data[i];
		if (data[i] == '\n') {
253
			if (mid - start != the_hash_algo->hexsz)
254
				die(_("%sinfo/refs not valid: is this a git repository?"),
255
				    transport_anonymize_url(url.buf));
256 257
			data[i] = 0;
			ref_name = mid + 1;
258
			ref = alloc_ref(ref_name);
259
			get_oid_hex(start, &ref->old_oid);
260 261 262 263 264 265 266 267 268 269 270
			if (!refs)
				refs = ref;
			if (last_ref)
				last_ref->next = ref;
			last_ref = ref;
			start = NULL;
		}
		i++;
	}

	ref = alloc_ref("HEAD");
271
	if (!http_fetch_ref(url.buf, ref) &&
272 273 274 275 276 277 278 279 280 281
	    !resolve_remote_symref(ref, refs)) {
		ref->next = refs;
		refs = ref;
	} else {
		free(ref);
	}

	return refs;
}

282 283 284 285 286
static void free_discovery(struct discovery *d)
{
	if (d) {
		if (d == last_discovery)
			last_discovery = NULL;
287
		free(d->shallow.oid);
288
		free(d->buf_alloc);
289
		free_refs(d->refs);
290
		free(d->service);
291 292 293 294
		free(d);
	}
}

295 296
static int show_http_message(struct strbuf *type, struct strbuf *charset,
			     struct strbuf *msg)
297 298 299 300 301 302 303
{
	const char *p, *eol;

	/*
	 * We only show text/plain parts, as other types are likely
	 * to be ugly to look at on the user's terminal.
	 */
304
	if (strcmp(type->buf, "text/plain"))
305
		return -1;
306 307
	if (charset->len)
		strbuf_reencode(msg, charset->buf, get_log_output_encoding());
308 309 310 311 312 313 314 315 316 317 318 319 320 321

	strbuf_trim(msg);
	if (!msg->len)
		return -1;

	p = msg->buf;
	do {
		eol = strchrnul(p, '\n');
		fprintf(stderr, "remote: %.*s\n", (int)(eol - p), p);
		p = eol + 1;
	} while(*eol);
	return 0;
}

322 323 324 325 326 327 328 329 330 331 332 333 334
static int get_protocol_http_header(enum protocol_version version,
				    struct strbuf *header)
{
	if (version > 0) {
		strbuf_addf(header, GIT_PROTOCOL_HEADER ": version=%d",
			    version);

		return 1;
	}

	return 0;
}

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
static void check_smart_http(struct discovery *d, const char *service,
			     struct strbuf *type)
{
	const char *p;
	struct packet_reader reader;

	/*
	 * If we don't see x-$service-advertisement, then it's not smart-http.
	 * But once we do, we commit to it and assume any other protocol
	 * violations are hard errors.
	 */
	if (!skip_prefix(type->buf, "application/x-", &p) ||
	    !skip_prefix(p, service, &p) ||
	    strcmp(p, "-advertisement"))
		return;

	packet_reader_init(&reader, -1, d->buf, d->len,
			   PACKET_READ_CHOMP_NEWLINE |
			   PACKET_READ_DIE_ON_ERR_PACKET);
	if (packet_reader_read(&reader) != PACKET_READ_NORMAL)
355
		die(_("invalid server response; expected service, got flush packet"));
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377

	if (skip_prefix(reader.line, "# service=", &p) && !strcmp(p, service)) {
		/*
		 * The header can include additional metadata lines, up
		 * until a packet flush marker.  Ignore these now, but
		 * in the future we might start to scan them.
		 */
		for (;;) {
			packet_reader_read(&reader);
			if (reader.pktlen <= 0) {
				break;
			}
		}

		/*
		 * v0 smart http; callers expect us to soak up the
		 * service and header packets
		 */
		d->buf = reader.src_buffer;
		d->len = reader.src_len;
		d->proto_git = 1;

378
	} else if (!strcmp(reader.line, "version 2")) {
379 380 381 382 383 384 385
		/*
		 * v2 smart http; do not consume version packet, which will
		 * be handled elsewhere.
		 */
		d->proto_git = 1;

	} else {
386
		die(_("invalid server response; got '%s'"), reader.line);
387 388 389
	}
}

390
static struct discovery *discover_refs(const char *service, int for_push)
391
{
392
	struct strbuf type = STRBUF_INIT;
393
	struct strbuf charset = STRBUF_INIT;
394
	struct strbuf buffer = STRBUF_INIT;
395
	struct strbuf refs_url = STRBUF_INIT;
396
	struct strbuf effective_url = STRBUF_INIT;
397 398
	struct strbuf protocol_header = STRBUF_INIT;
	struct string_list extra_headers = STRING_LIST_INIT_DUP;
399
	struct discovery *last = last_discovery;
400
	int http_ret, maybe_smart = 0;
401
	struct http_get_options http_options;
402
	enum protocol_version version = get_protocol_version_config();
403

404 405 406
	if (last && !strcmp(service, last->service))
		return last;
	free_discovery(last);
407

408
	strbuf_addf(&refs_url, "%sinfo/refs", url.buf);
409
	if ((starts_with(url.buf, "http://") || starts_with(url.buf, "https://")) &&
410
	     git_env_bool("GIT_SMART_HTTP", 1)) {
411
		maybe_smart = 1;
412
		if (!strchr(url.buf, '?'))
413
			strbuf_addch(&refs_url, '?');
414
		else
415 416
			strbuf_addch(&refs_url, '&');
		strbuf_addf(&refs_url, "service=%s", service);
417
	}
418

419 420 421 422 423 424 425 426
	/*
	 * NEEDSWORK: If we are trying to use protocol v2 and we are planning
	 * to perform a push, then fallback to v0 since the client doesn't know
	 * how to push yet using v2.
	 */
	if (version == protocol_v2 && !strcmp("git-receive-pack", service))
		version = protocol_v0;

427
	/* Add the extra Git-Protocol header */
428
	if (get_protocol_http_header(version, &protocol_header))
429 430
		string_list_append(&extra_headers, protocol_header.buf);

431 432 433 434 435
	memset(&http_options, 0, sizeof(http_options));
	http_options.content_type = &type;
	http_options.charset = &charset;
	http_options.effective_url = &effective_url;
	http_options.base_url = &url;
436
	http_options.extra_headers = &extra_headers;
437
	http_options.initial_request = 1;
438
	http_options.no_cache = 1;
439

440
	http_ret = http_get_strbuf(refs_url.buf, &buffer, &http_options);
441 442 443 444
	switch (http_ret) {
	case HTTP_OK:
		break;
	case HTTP_MISSING_TARGET:
445
		show_http_message(&type, &charset, &buffer);
446
		die(_("repository '%s' not found"),
447
		    transport_anonymize_url(url.buf));
448
	case HTTP_NOAUTH:
449
		show_http_message(&type, &charset, &buffer);
450
		die(_("Authentication failed for '%s'"),
451
		    transport_anonymize_url(url.buf));
452
	default:
453
		show_http_message(&type, &charset, &buffer);
454
		die(_("unable to access '%s': %s"),
455
		    transport_anonymize_url(url.buf), curl_errorstr);
456 457
	}

458 459 460 461 462
	if (options.verbosity && !starts_with(refs_url.buf, url.buf)) {
		char *u = transport_anonymize_url(url.buf);
		warning(_("redirecting to %s"), u);
		free(u);
	}
463

464
	last= xcalloc(1, sizeof(*last_discovery));
465
	last->service = xstrdup(service);
466 467 468
	last->buf_alloc = strbuf_detach(&buffer, &last->len);
	last->buf = last->buf_alloc;

469 470
	if (maybe_smart)
		check_smart_http(last, service, &type);
471

472 473 474 475 476
	if (last->proto_git)
		last->refs = parse_git_refs(last, for_push);
	else
		last->refs = parse_info_refs(last);

477
	strbuf_release(&refs_url);
478
	strbuf_release(&type);
479
	strbuf_release(&charset);
480
	strbuf_release(&effective_url);
481
	strbuf_release(&buffer);
482 483
	strbuf_release(&protocol_header);
	string_list_clear(&extra_headers, 0);
484 485 486 487 488 489 490 491 492
	last_discovery = last;
	return last;
}

static struct ref *get_refs(int for_push)
{
	struct discovery *heads;

	if (for_push)
493
		heads = discover_refs("git-receive-pack", for_push);
494
	else
495
		heads = discover_refs("git-upload-pack", for_push);
496

497
	return heads->refs;
498 499
}

500 501 502 503 504 505 506
static void output_refs(struct ref *refs)
{
	struct ref *posn;
	for (posn = refs; posn; posn = posn->next) {
		if (posn->symref)
			printf("@%s %s\n", posn->symref, posn->name);
		else
507
			printf("%s %s\n", oid_to_hex(&posn->old_oid), posn->name);
508 509 510 511 512
	}
	printf("\n");
	fflush(stdout);
}

513 514 515 516 517
struct rpc_state {
	const char *service_name;
	char *service_url;
	char *hdr_content_type;
	char *hdr_accept;
518
	char *protocol_header;
519 520 521 522 523 524
	char *buf;
	size_t alloc;
	size_t len;
	size_t pos;
	int in;
	int out;
525
	int any_written;
526
	unsigned gzip_request : 1;
527
	unsigned initial_buffer : 1;
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542

	/*
	 * Whenever a pkt-line is read into buf, append the 4 characters
	 * denoting its length before appending the payload.
	 */
	unsigned write_line_lengths : 1;

	/*
	 * Used by rpc_out; initialize to 0. This is true if a flush has been
	 * read, but the corresponding line length (if write_line_lengths is
	 * true) and EOF have not been sent to libcurl. Since each flush marks
	 * the end of a request, each flush must be completely sent before any
	 * further reading occurs.
	 */
	unsigned flush_read_but_not_sent : 1;
543 544
};

545 546 547 548 549
/*
 * Appends the result of reading from rpc->out to the string represented by
 * rpc->buf and rpc->len if there is enough space. Returns 1 if there was
 * enough space, 0 otherwise.
 *
550 551 552 553
 * If rpc->write_line_lengths is true, appends the line length as a 4-byte
 * hexadecimal string before appending the result described above.
 *
 * Writes the total number of bytes appended into appended.
554
 */
555 556 557 558 559 560 561 562 563 564 565 566 567 568
static int rpc_read_from_out(struct rpc_state *rpc, int options,
			     size_t *appended,
			     enum packet_read_status *status) {
	size_t left;
	char *buf;
	int pktlen_raw;

	if (rpc->write_line_lengths) {
		left = rpc->alloc - rpc->len - 4;
		buf = rpc->buf + rpc->len + 4;
	} else {
		left = rpc->alloc - rpc->len;
		buf = rpc->buf + rpc->len;
	}
569 570 571 572

	if (left < LARGE_PACKET_MAX)
		return 0;

573 574 575 576 577 578 579 580 581 582 583
	*status = packet_read_with_status(rpc->out, NULL, NULL, buf,
			left, &pktlen_raw, options);
	if (*status != PACKET_READ_EOF) {
		*appended = pktlen_raw + (rpc->write_line_lengths ? 4 : 0);
		rpc->len += *appended;
	}

	if (rpc->write_line_lengths) {
		switch (*status) {
		case PACKET_READ_EOF:
			if (!(options & PACKET_READ_GENTLE_ON_EOF))
584
				die(_("shouldn't have EOF when not gentle on EOF"));
585 586 587 588 589 590 591 592 593 594 595 596 597
			break;
		case PACKET_READ_NORMAL:
			set_packet_header(buf - 4, *appended);
			break;
		case PACKET_READ_DELIM:
			memcpy(buf - 4, "0001", 4);
			break;
		case PACKET_READ_FLUSH:
			memcpy(buf - 4, "0000", 4);
			break;
		}
	}

598 599 600
	return 1;
}

601 602 603 604 605 606
static size_t rpc_out(void *ptr, size_t eltsize,
		size_t nmemb, void *buffer_)
{
	size_t max = eltsize * nmemb;
	struct rpc_state *rpc = buffer_;
	size_t avail = rpc->len - rpc->pos;
607
	enum packet_read_status status;
608 609

	if (!avail) {
610
		rpc->initial_buffer = 0;
611
		rpc->len = 0;
612
		rpc->pos = 0;
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
		if (!rpc->flush_read_but_not_sent) {
			if (!rpc_read_from_out(rpc, 0, &avail, &status))
				BUG("The entire rpc->buf should be larger than LARGE_PACKET_MAX");
			if (status == PACKET_READ_FLUSH)
				rpc->flush_read_but_not_sent = 1;
		}
		/*
		 * If flush_read_but_not_sent is true, we have already read one
		 * full request but have not fully sent it + EOF, which is why
		 * we need to refrain from reading.
		 */
	}
	if (rpc->flush_read_but_not_sent) {
		if (!avail) {
			/*
			 * The line length either does not need to be sent at
			 * all or has already been completely sent. Now we can
			 * return 0, indicating EOF, meaning that the flush has
			 * been fully sent.
			 */
			rpc->flush_read_but_not_sent = 0;
			return 0;
		}
		/*
		 * If avail is non-zerp, the line length for the flush still
		 * hasn't been fully sent. Proceed with sending the line
		 * length.
		 */
641 642
	}

Ray's avatar
Ray committed
643
	if (max < avail)
644 645 646 647 648 649
		avail = max;
	memcpy(ptr, rpc->buf + rpc->pos, avail);
	rpc->pos += avail;
	return avail;
}

650
#ifndef NO_CURL_IOCTL
651
static curlioerr rpc_ioctl(CURL *handle, int cmd, void *clientp)
652 653 654 655 656 657 658 659 660 661 662 663
{
	struct rpc_state *rpc = clientp;

	switch (cmd) {
	case CURLIOCMD_NOP:
		return CURLIOE_OK;

	case CURLIOCMD_RESTARTREAD:
		if (rpc->initial_buffer) {
			rpc->pos = 0;
			return CURLIOE_OK;
		}
664
		error(_("unable to rewind rpc post data - try increasing http.postBuffer"));
665 666 667 668 669 670 671 672
		return CURLIOE_FAILRESTART;

	default:
		return CURLIOE_UNKNOWNCMD;
	}
}
#endif

673 674
struct rpc_in_data {
	struct rpc_state *rpc;
675
	struct active_request_slot *slot;
676 677 678 679 680 681
};

/*
 * A callback for CURLOPT_WRITEFUNCTION. The return value is the bytes consumed
 * from ptr.
 */
682
static size_t rpc_in(char *ptr, size_t eltsize,
683 684 685
		size_t nmemb, void *buffer_)
{
	size_t size = eltsize * nmemb;
686
	struct rpc_in_data *data = buffer_;
687 688 689 690 691 692 693
	long response_code;

	if (curl_easy_getinfo(data->slot->curl, CURLINFO_RESPONSE_CODE,
			      &response_code) != CURLE_OK)
		return size;
	if (response_code >= 300)
		return size;
694
	if (size)
695 696
		data->rpc->any_written = 1;
	write_or_die(data->rpc->in, ptr, size);
697 698 699
	return size;
}

700 701
static int run_slot(struct active_request_slot *slot,
		    struct slot_results *results)
702
{
703
	int err;
704
	struct slot_results results_buf;
705

706 707 708
	if (!results)
		results = &results_buf;

709
	err = run_one_slot(slot, results);
710

711
	if (err != HTTP_OK && err != HTTP_REAUTH) {
712 713 714 715 716 717 718 719 720 721 722 723
		struct strbuf msg = STRBUF_INIT;
		if (results->http_code && results->http_code != 200)
			strbuf_addf(&msg, "HTTP %ld", results->http_code);
		if (results->curl_result != CURLE_OK) {
			if (msg.len)
				strbuf_addch(&msg, ' ');
			strbuf_addf(&msg, "curl %d", results->curl_result);
			if (curl_errorstr[0]) {
				strbuf_addch(&msg, ' ');
				strbuf_addstr(&msg, curl_errorstr);
			}
		}
724
		error(_("RPC failed; %s"), msg.buf);
725
		strbuf_release(&msg);
726 727 728 729 730
	}

	return err;
}

731
static int probe_rpc(struct rpc_state *rpc, struct slot_results *results)
732 733
{
	struct active_request_slot *slot;
734
	struct curl_slist *headers = http_copy_default_headers();
735 736 737 738 739 740 741 742 743 744 745
	struct strbuf buf = STRBUF_INIT;
	int err;

	slot = get_active_slot();

	headers = curl_slist_append(headers, rpc->hdr_content_type);
	headers = curl_slist_append(headers, rpc->hdr_accept);

	curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
	curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
	curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
746
	curl_easy_setopt(slot->curl, CURLOPT_ENCODING, NULL);
747 748 749 750 751 752
	curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, "0000");
	curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, 4);
	curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
	curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
	curl_easy_setopt(slot->curl, CURLOPT_FILE, &buf);

753
	err = run_slot(slot, results);
754 755 756 757 758 759

	curl_slist_free_all(headers);
	strbuf_release(&buf);
	return err;
}

760 761
static curl_off_t xcurl_off_t(size_t len)
{
762 763
	uintmax_t size = len;
	if (size > maximum_signed_value_of_type(curl_off_t))
764
		die(_("cannot handle pushes this big"));
765
	return (curl_off_t)size;
766 767
}

768 769 770 771 772
/*
 * If flush_received is true, do not attempt to read any more; just use what's
 * in rpc->buf.
 */
static int post_rpc(struct rpc_state *rpc, int flush_received)
773 774
{
	struct active_request_slot *slot;
775
	struct curl_slist *headers = http_copy_default_headers();
776 777
	int use_gzip = rpc->gzip_request;
	char *gzip_body = NULL;
778
	size_t gzip_size = 0;
779
	int err, large_request = 0;
780
	int needs_100_continue = 0;
781
	struct rpc_in_data rpc_in_data;
782 783 784 785 786

	/* Try to load the entire request, if we can fit it into the
	 * allocated buffer space we can use HTTP/1.0 and avoid the
	 * chunked encoding mess.
	 */
787 788 789 790 791 792 793 794 795 796 797 798
	if (!flush_received) {
		while (1) {
			size_t n;
			enum packet_read_status status;

			if (!rpc_read_from_out(rpc, 0, &n, &status)) {
				large_request = 1;
				use_gzip = 0;
				break;
			}
			if (status == PACKET_READ_FLUSH)
				break;
799 800 801
		}
	}

802
	if (large_request) {
803 804
		struct slot_results results;

805
		do {
806
			err = probe_rpc(rpc, &results);
807 808
			if (err == HTTP_REAUTH)
				credential_fill(&http_auth);
809 810 811
		} while (err == HTTP_REAUTH);
		if (err != HTTP_OK)
			return -1;
812 813 814

		if (results.auth_avail & CURLAUTH_GSSNEGOTIATE)
			needs_100_continue = 1;
815 816
	}

817 818
	headers = curl_slist_append(headers, rpc->hdr_content_type);
	headers = curl_slist_append(headers, rpc->hdr_accept);
819 820
	headers = curl_slist_append(headers, needs_100_continue ?
		"Expect: 100-continue" : "Expect:");
821

822 823 824 825
	/* Add the extra Git-Protocol header */
	if (rpc->protocol_header)
		headers = curl_slist_append(headers, rpc->protocol_header);

826
retry:
827 828 829
	slot = get_active_slot();

	curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
830
	curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
831
	curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
832
	curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
833 834 835 836 837 838

	if (large_request) {
		/* The request body is large and the size cannot be predicted.
		 * We must use chunked encoding to send it.
		 */
		headers = curl_slist_append(headers, "Transfer-Encoding: chunked");
839
		rpc->initial_buffer = 1;
840 841
		curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, rpc_out);
		curl_easy_setopt(slot->curl, CURLOPT_INFILE, rpc);
842 843 844 845
#ifndef NO_CURL_IOCTL
		curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, rpc_ioctl);
		curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, rpc);
#endif
846 847 848 849 850
		if (options.verbosity > 1) {
			fprintf(stderr, "POST %s (chunked)\n", rpc->service_name);
			fflush(stderr);
		}

851 852 853 854 855 856 857
	} else if (gzip_body) {
		/*
		 * If we are looping to retry authentication, then the previous
		 * run will have set up the headers and gzip buffer already,
		 * and we just need to send it.
		 */
		curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
858
		curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(gzip_size));
859

860 861
	} else if (use_gzip && 1024 < rpc->len) {
		/* The client backend isn't giving us compressed data so
862
		 * we can try to deflate it ourselves, this may save on
863 864
		 * the transfer time.
		 */
865
		git_zstream stream;
866 867
		int ret;

868
		git_deflate_init_gzip(&stream, Z_BEST_COMPRESSION);
869 870
		gzip_size = git_deflate_bound(&stream, rpc->len);
		gzip_body = xmalloc(gzip_size);
871 872 873 874

		stream.next_in = (unsigned char *)rpc->buf;
		stream.avail_in = rpc->len;
		stream.next_out = (unsigned char *)gzip_body;
875
		stream.avail_out = gzip_size;
876

877
		ret = git_deflate(&stream, Z_FINISH);
878
		if (ret != Z_STREAM_END)
879
			die(_("cannot deflate request; zlib deflate error %d"), ret);
880

881
		ret = git_deflate_end_gently(&stream);
882
		if (ret != Z_OK)
883
			die(_("cannot deflate request; zlib end error %d"), ret);
884

885
		gzip_size = stream.total_out;
886 887 888

		headers = curl_slist_append(headers, "Content-Encoding: gzip");
		curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
889
		curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(gzip_size));
890 891 892 893

		if (options.verbosity > 1) {
			fprintf(stderr, "POST %s (gzip %lu to %lu bytes)\n",
				rpc->service_name,
894
				(unsigned long)rpc->len, (unsigned long)gzip_size);
895 896
			fflush(stderr);
		}
897 898 899 900 901
	} else {
		/* We know the complete request size in advance, use the
		 * more normal Content-Length approach.
		 */
		curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, rpc->buf);
902
		curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(rpc->len));
903 904 905 906 907 908 909 910 911
		if (options.verbosity > 1) {
			fprintf(stderr, "POST %s (%lu bytes)\n",
				rpc->service_name, (unsigned long)rpc->len);
			fflush(stderr);
		}
	}

	curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
	curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, rpc_in);
912
	rpc_in_data.rpc = rpc;
913
	rpc_in_data.slot = slot;
914
	curl_easy_setopt(slot->curl, CURLOPT_FILE, &rpc_in_data);
915
	curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
916

917 918

	rpc->any_written = 0;
919
	err = run_slot(slot, NULL);
920 921
	if (err == HTTP_REAUTH && !large_request) {
		credential_fill(&http_auth);
922
		goto retry;
923
	}
924 925
	if (err != HTTP_OK)
		err = -1;
926

927 928 929
	if (!rpc->any_written)
		err = -1;

930
	curl_slist_free_all(headers);
931
	free(gzip_body);
932 933 934
	return err;
}

935
static int rpc_service(struct rpc_state *rpc, struct discovery *heads,
936 937
		       const char **client_argv, const struct strbuf *preamble,
		       struct strbuf *rpc_result)
938 939 940
{
	const char *svc = rpc->service_name;
	struct strbuf buf = STRBUF_INIT;
941
	struct child_process client = CHILD_PROCESS_INIT;
942 943 944 945 946
	int err = 0;

	client.in = -1;
	client.out = -1;
	client.git_cmd = 1;
947
	client.argv = client_argv;
948 949
	if (start_command(&client))
		exit(1);
950
	write_or_die(client.in, preamble->buf, preamble->len);
951 952 953 954 955 956 957 958
	if (heads)
		write_or_die(client.in, heads->buf, heads->len);

	rpc->alloc = http_post_buffer;
	rpc->buf = xmalloc(rpc->alloc);
	rpc->in = client.in;
	rpc->out = client.out;

959
	strbuf_addf(&buf, "%s%s", url.buf, svc);
960 961 962 963 964
	rpc->service_url = strbuf_detach(&buf, NULL);

	strbuf_addf(&buf, "Content-Type: application/x-%s-request", svc);
	rpc->hdr_content_type = strbuf_detach(&buf, NULL);

965
	strbuf_addf(&buf, "Accept: application/x-%s-result", svc);
966 967
	rpc->hdr_accept = strbuf_detach(&buf, NULL);

968 969 970 971 972
	if (get_protocol_http_header(heads->version, &buf))
		rpc->protocol_header = strbuf_detach(&buf, NULL);
	else
		rpc->protocol_header = NULL;

973
	while (!err) {
974
		int n = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
975 976 977 978
		if (!n)
			break;
		rpc->pos = 0;
		rpc->len = n;
979
		err |= post_rpc(rpc, 0);
980 981 982 983
	}

	close(client.in);
	client.in = -1;
984
	if (!err) {
985
		strbuf_read(rpc_result, client.out, 0);
986 987 988 989 990 991
	} else {
		char buf[4096];
		for (;;)
			if (xread(client.out, buf, sizeof(buf)) <= 0)
				break;
	}
992 993

	close(client.out);
994 995 996 997 998 999
	client.out = -1;

	err |= finish_command(&client);
	free(rpc->service_url);
	free(rpc->hdr_content_type);
	free(rpc->hdr_accept);
1000
	free(rpc->protocol_header);
1001 1002 1003 1004 1005
	free(rpc->buf);
	strbuf_release(&buf);
	return err;
}

1006 1007
static int fetch_dumb(int nr_heads, struct ref **to_fetch)
{
1008
	struct walker *walker;
1009
	char **targets;
1010 1011
	int ret, i;

1012
	ALLOC_ARRAY(targets, nr_heads);
1013
	if (options.depth || options.deepen_since)
1014
		die(_("dumb http transport does not support shallow capabilities"));
1015
	for (i = 0; i < nr_heads; i++)
1016
		targets[i] = xstrdup(oid_to_hex(&to_fetch[i]->old_oid));
1017

1018
	walker = get_http_walker(url.buf);
1019
	walker->get_verbosely = options.verbosity >= 3;
1020 1021
	walker->get_recover = 0;
	ret = walker_fetch(walker, nr_heads, targets, NULL, NULL);
1022
	walker_free(walker);
1023 1024 1025 1026 1027

	for (i = 0; i < nr_heads; i++)
		free(targets[i]);
	free(targets);

1028
	return ret ? error(_("fetch failed.")) : 0;
1029 1030
}

1031 1032 1033 1034
static int fetch_git(struct discovery *heads,
	int nr_heads, struct ref **to_fetch)
{
	struct rpc_state rpc;
1035
	struct strbuf preamble = STRBUF_INIT;
1036 1037
	int i, err;
	struct argv_array args = ARGV_ARRAY_INIT;
1038
	struct strbuf rpc_result = STRBUF_INIT;
1039 1040 1041

	argv_array_pushl(&args, "fetch-pack", "--stateless-rpc",
			 "--stdin", "--lock-pack", NULL);
1042
	if (options.followtags)
1043
		argv_array_push(&args, "--include-tag");
1044
	if (options.thin)
1045 1046 1047
		argv_array_push(&args, "--thin");
	if (options.verbosity >= 3)
		argv_array_pushl(&args, "-v", "-v", NULL);
1048
	if (options.check_self_contained_and_connected)
1049
		argv_array_push(&args, "--check-self-contained-and-connected");
1050
	if (options.cloning)
1051
		argv_array_push(&args, "--cloning");
1052
	if (options.update_shallow)
1053
		argv_array_push(&args, "--update-shallow");
1054
	if (!options.progress)
1055 1056 1057
		argv_array_push(&args, "--no-progress");
	if (options.depth)
		argv_array_pushf(&args, "--depth=%lu", options.depth);
1058 1059
	if (options.deepen_since)
		argv_array_pushf(&args, "--shallow-since=%s", options.deepen_since);
1060 1061 1062
	for (i = 0; i < options.deepen_not.nr; i++)
		argv_array_pushf(&args, "--shallow-exclude=%s",
				 options.deepen_not.items[i].string);
1063 1064
	if (options.deepen_relative && options.depth)
		argv_array_push(&args, "--deepen-relative");
1065 1066 1067 1068
	if (options.from_promisor)
		argv_array_push(&args, "--from-promisor");
	if (options.no_dependents)
		argv_array_push(&args, "--no-dependents");
Jeff Hostetler's avatar
Jeff Hostetler committed
1069 1070
	if (options.filter)
		argv_array_pushf(&args, "--filter=%s", options.filter);
1071
	argv_array_push(&args, url.buf);
1072

1073 1074
	for (i = 0; i < nr_heads; i++) {
		struct ref *ref = to_fetch[i];
1075
		if (!*ref->name)
1076
			die(_("cannot fetch by sha1 over smart http"));
1077
		packet_buf_write(&preamble, "%s %s\n",
1078
				 oid_to_hex(&ref->old_oid), ref->name);
1079
	}
1080
	packet_buf_flush(&preamble);
1081 1082 1083

	memset(&rpc, 0, sizeof(rpc));
	rpc.service_name = "git-upload-pack",
1084
	rpc.gzip_request = 1;
1085

1086 1087 1088 1089
	err = rpc_service(&rpc, heads, args.argv, &preamble, &rpc_result);
	if (rpc_result.len)
		write_or_die(1, rpc_result.buf, rpc_result.len);
	strbuf_release(&rpc_result);
1090
	strbuf_release(&preamble);
1091
	argv_array_clear(&args);
1092 1093 1094 1095 1096
	return err;
}

static int fetch(int nr_heads, struct ref **to_fetch)
{
1097
	struct discovery *d = discover_refs("git-upload-pack", 0);
1098 1099 1100 1101 1102 1103
	if (d->proto_git)
		return fetch_git(d, nr_heads, to_fetch);
	else
		return fetch_dumb(nr_heads, to_fetch);
}

1104 1105 1106 1107 1108 1109 1110 1111
static void parse_fetch(struct strbuf *buf)
{
	struct ref **to_fetch = NULL;
	struct ref *list_head = NULL;
	struct ref **list = &list_head;
	int alloc_heads = 0, nr_heads = 0;

	do {
1112 1113 1114
		const char *p;
		if (skip_prefix(buf->buf, "fetch ", &p)) {
			const char *name;
1115
			struct ref *ref;
1116
			struct object_id old_oid;
1117
			const char *q;
1118

1119
			if (parse_oid_hex(p, &old_oid, &q))
1120
				die(_("protocol error: expected sha/ref, got %s'"), p);
1121 1122 1123
			if (*q == ' ')
				name = q + 1;
			else if (!*q)
1124 1125
				name = "";
			else
1126
				die(_("protocol error: expected sha/ref, got %s'"), p);
1127 1128

			ref = alloc_ref(name);
1129
			oidcpy(&ref->old_oid, &old_oid);
1130 1131 1132 1133 1134 1135 1136 1137

			*list = ref;
			list = &ref->next;

			ALLOC_GROW(to_fetch, nr_heads + 1, alloc_heads);
			to_fetch[nr_heads++] = ref;
		}
		else
1138
			die(_("http transport does not support %s"), buf->buf);
1139 1140

		strbuf_reset(buf);
1141
		if (strbuf_getline_lf(buf, stdin) == EOF)
1142 1143 1144 1145 1146
			return;
		if (!*buf->buf)
			break;
	} while (1);

1147
	if (fetch(nr_heads, to_fetch))
1148 1149 1150 1151 1152 1153 1154 1155 1156
		exit(128); /* error already reported */
	free_refs(list_head);
	free(to_fetch);

	printf("\n");
	fflush(stdout);
	strbuf_reset(buf);
}

1157 1158
static int push_dav(int nr_spec, char **specs)
{
1159 1160
	struct child_process child = CHILD_PROCESS_INIT;
	size_t i;
1161

1162 1163 1164
	child.git_cmd = 1;
	argv_array_push(&child.args, "http-push");
	argv_array_push(&child.args, "--helper-status");
1165
	if (options.dry_run)
1166
		argv_array_push(&child.args, "--dry-run");
1167
	if (options.verbosity > 1)
1168 1169
		argv_array_push(&child.args, "--verbose");
	argv_array_push(&child.args, url.buf);
1170
	for (i = 0; i < nr_spec; i++)
1171
		argv_array_push(&child.args, specs[i]);
1172

1173
	if (run_command(&child))
1174
		die(_("git-http-push failed"));
1175 1176 1177
	return 0;
}

1178 1179 1180
static int push_git(struct discovery *heads, int nr_spec, char **specs)
{
	struct rpc_state rpc;
1181 1182
	int i, err;
	struct argv_array args;
1183
	struct string_list_item *cas_option;
1184
	struct strbuf preamble = STRBUF_INIT;
1185
	struct strbuf rpc_result = STRBUF_INIT;
1186 1187 1188 1189

	argv_array_init(&args);
	argv_array_pushl(&args, "send-pack", "--stateless-rpc", "--helper-status",
			 NULL);
1190 1191

	if (options.thin)
1192
		argv_array_push(&args, "--thin");
1193
	if (options.dry_run)
1194
		argv_array_push(&args, "--dry-run");
1195 1196 1197 1198
	if (options.push_cert == SEND_PACK_PUSH_CERT_ALWAYS)
		argv_array_push(&args, "--signed=yes");
	else if (options.push_cert == SEND_PACK_PUSH_CERT_IF_ASKED)
		argv_array_push(&args, "--signed=if-asked");
1199
	if (options.verbosity == 0)
1200
		argv_array_push(&args, "--quiet");
1201
	else if (options.verbosity > 1)
1202
		argv_array_push(&args, "--verbose");
1203 1204 1205
	for (i = 0; i < options.push_options.nr; i++)
		argv_array_pushf(&args, "--push-option=%s",
				 options.push_options.items[i].string);
1206
	argv_array_push(&args, options.progress ? "--progress" : "--no-progress");
1207
	for_each_string_list_item(cas_option, &cas_options)
1208
		argv_array_push(&args, cas_option->string);
1209
	argv_array_push(&args, url.buf);
1210 1211

	argv_array_push(&args, "--stdin");
1212
	for (i = 0; i < nr_spec; i++)
1213 1214
		packet_buf_write(&preamble, "%s\n", specs[i]);
	packet_buf_flush(&preamble);
1215 1216 1217 1218

	memset(&rpc, 0, sizeof(rpc));
	rpc.service_name = "git-receive-pack",

1219 1220 1221 1222
	err = rpc_service(&rpc, heads, args.argv, &preamble, &rpc_result);
	if (rpc_result.len)
		write_or_die(1, rpc_result.buf, rpc_result.len);
	strbuf_release(&rpc_result);
1223
	strbuf_release(&preamble);
1224
	argv_array_clear(&args);
1225 1226 1227 1228 1229
	return err;
}

static int push(int nr_spec, char **specs)
{
1230
	struct discovery *heads = discover_refs("git-receive-pack", 1);
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
	int ret;

	if (heads->proto_git)
		ret = push_git(heads, nr_spec, specs);
	else
		ret = push_dav(nr_spec, specs);
	free_discovery(heads);
	return ret;
}

1241 1242 1243
static void parse_push(struct strbuf *buf)
{
	char **specs = NULL;
1244
	int alloc_spec = 0, nr_spec = 0, i, ret;
1245 1246

	do {
1247
		if (starts_with(buf->buf, "push ")) {
1248 1249 1250 1251
			ALLOC_GROW(specs, nr_spec + 1, alloc_spec);
			specs[nr_spec++] = xstrdup(buf->buf + 5);
		}
		else
1252
			die(_("http transport does not support %s"), buf->buf);
1253 1254

		strbuf_reset(buf);
1255
		if (strbuf_getline_lf(buf, stdin) == EOF)
1256
			goto free_specs;
1257 1258 1259 1260
		if (!*buf->buf)
			break;
	} while (1);

1261
	ret = push(nr_spec, specs);
1262 1263
	printf("\n");
	fflush(stdout);
1264

1265 1266 1267
	if (ret)
		exit(128); /* error already reported */

1268 1269 1270 1271
 free_specs:
	for (i = 0; i < nr_spec; i++)
		free(specs[i]);
	free(specs);
1272 1273
}

1274 1275 1276
static int stateless_connect(const char *service_name)
{
	struct discovery *discover;
1277 1278
	struct rpc_state rpc;
	struct strbuf buf = STRBUF_INIT;
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297

	/*
	 * Run the info/refs request and see if the server supports protocol
	 * v2.  If and only if the server supports v2 can we successfully
	 * establish a stateless connection, otherwise we need to tell the
	 * client to fallback to using other transport helper functions to
	 * complete their request.
	 */
	discover = discover_refs(service_name, 0);
	if (discover->version != protocol_v2) {
		printf("fallback\n");
		fflush(stdout);
		return -1;
	} else {
		/* Stateless Connection established */
		printf("\n");
		fflush(stdout);
	}

1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
	rpc.service_name = service_name;
	rpc.service_url = xstrfmt("%s%s", url.buf, rpc.service_name);
	rpc.hdr_content_type = xstrfmt("Content-Type: application/x-%s-request", rpc.service_name);
	rpc.hdr_accept = xstrfmt("Accept: application/x-%s-result", rpc.service_name);
	if (get_protocol_http_header(discover->version, &buf)) {
		rpc.protocol_header = strbuf_detach(&buf, NULL);
	} else {
		rpc.protocol_header = NULL;
		strbuf_release(&buf);
	}
	rpc.buf = xmalloc(http_post_buffer);
	rpc.alloc = http_post_buffer;
	rpc.len = 0;
	rpc.pos = 0;
	rpc.in = 1;
	rpc.out = 0;
	rpc.any_written = 0;
	rpc.gzip_request = 1;
	rpc.initial_buffer = 0;