remote-curl.c 36.3 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"
J
Junio C Hamano 已提交
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

20
static struct remote *remote;
J
Jeff King 已提交
21 22
/* always ends with a trailing slash */
static struct strbuf url = STRBUF_INIT;
23

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

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

#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 */
174 175 176 177 178 179
	} else if (!strcmp(name, "from-promisor")) {
		options.from_promisor = 1;
		return 0;
	} else if (!strcmp(name, "no-dependents")) {
		options.no_dependents = 1;
		return 0;
J
Jeff Hostetler 已提交
180
	} else if (!strcmp(name, "filter")) {
181
		options.filter = xstrdup(value);
J
Jeff Hostetler 已提交
182
		return 0;
183
	} else {
184 185 186 187
		return 1 /* unsupported */;
	}
}

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

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

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

210 211
	heads->version = discover_version(&reader);
	switch (heads->version) {
212
	case protocol_v2:
213 214 215 216 217 218
		/*
		 * 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.
		 */
219
		break;
220 221 222 223 224 225 226 227 228
	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");
	}

229 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') {
			if (mid - start != 40)
J
Jeff King 已提交
253 254
				die("%sinfo/refs not valid: is this a git repository?",
				    url.buf);
255 256
			data[i] = 0;
			ref_name = mid + 1;
257
			ref = alloc_ref(ref_name);
258
			get_oid_hex(start, &ref->old_oid);
259 260 261 262 263 264 265 266 267 268 269
			if (!refs)
				refs = ref;
			if (last_ref)
				last_ref->next = ref;
			last_ref = ref;
			start = NULL;
		}
		i++;
	}

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

	return refs;
}

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

294 295
static int show_http_message(struct strbuf *type, struct strbuf *charset,
			     struct strbuf *msg)
296 297 298 299 300 301 302
{
	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.
	 */
303
	if (strcmp(type->buf, "text/plain"))
304
		return -1;
305 306
	if (charset->len)
		strbuf_reencode(msg, charset->buf, get_log_output_encoding());
307 308 309 310 311 312 313 314 315 316 317 318 319 320

	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;
}

321 322 323 324 325 326 327 328 329 330 331 332 333
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;
}

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
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)
		die("invalid server response; expected service, got flush packet");

	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;

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

	} else {
		die("invalid server response; got '%s'", reader.line);
	}
}

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

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

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

418 419 420 421 422 423 424 425
	/*
	 * 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;

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

430 431 432 433 434
	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;
435
	http_options.extra_headers = &extra_headers;
J
Jeff King 已提交
436
	http_options.initial_request = 1;
437
	http_options.no_cache = 1;
J
Jeff King 已提交
438

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

J
Jeff King 已提交
454 455 456
	if (options.verbosity && !starts_with(refs_url.buf, url.buf))
		warning(_("redirecting to %s"), url.buf);

457
	last= xcalloc(1, sizeof(*last_discovery));
458
	last->service = xstrdup(service);
459 460 461
	last->buf_alloc = strbuf_detach(&buffer, &last->len);
	last->buf = last->buf_alloc;

462 463
	if (maybe_smart)
		check_smart_http(last, service, &type);
464

465 466 467 468 469
	if (last->proto_git)
		last->refs = parse_git_refs(last, for_push);
	else
		last->refs = parse_info_refs(last);

J
Jeff King 已提交
470
	strbuf_release(&refs_url);
471
	strbuf_release(&type);
472
	strbuf_release(&charset);
473
	strbuf_release(&effective_url);
474
	strbuf_release(&buffer);
475 476
	strbuf_release(&protocol_header);
	string_list_clear(&extra_headers, 0);
477 478 479 480 481 482 483 484 485
	last_discovery = last;
	return last;
}

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

	if (for_push)
486
		heads = discover_refs("git-receive-pack", for_push);
487
	else
488
		heads = discover_refs("git-upload-pack", for_push);
489

490
	return heads->refs;
491 492
}

493 494 495 496 497 498 499
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
500
			printf("%s %s\n", oid_to_hex(&posn->old_oid), posn->name);
501 502 503 504 505
	}
	printf("\n");
	fflush(stdout);
}

506 507 508
struct rpc_state {
	const char *service_name;
	const char **argv;
509
	struct strbuf *stdin_preamble;
510 511 512
	char *service_url;
	char *hdr_content_type;
	char *hdr_accept;
513
	char *protocol_header;
514 515 516 517 518 519
	char *buf;
	size_t alloc;
	size_t len;
	size_t pos;
	int in;
	int out;
520
	int any_written;
521
	struct strbuf result;
S
Shawn O. Pearce 已提交
522
	unsigned gzip_request : 1;
523
	unsigned initial_buffer : 1;
524 525 526 527 528 529 530 531 532 533
};

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;

	if (!avail) {
534
		rpc->initial_buffer = 0;
535
		avail = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
536 537 538 539 540 541
		if (!avail)
			return 0;
		rpc->pos = 0;
		rpc->len = avail;
	}

T
Tay Ray Chuan 已提交
542
	if (max < avail)
543 544 545 546 547 548
		avail = max;
	memcpy(ptr, rpc->buf + rpc->pos, avail);
	rpc->pos += avail;
	return avail;
}

549
#ifndef NO_CURL_IOCTL
550
static curlioerr rpc_ioctl(CURL *handle, int cmd, void *clientp)
551 552 553 554 555 556 557 558 559 560 561 562
{
	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;
		}
563
		error("unable to rewind rpc post data - try increasing http.postBuffer");
564 565 566 567 568 569 570 571
		return CURLIOE_FAILRESTART;

	default:
		return CURLIOE_UNKNOWNCMD;
	}
}
#endif

572 573
struct rpc_in_data {
	struct rpc_state *rpc;
574
	struct active_request_slot *slot;
575 576 577 578 579 580
};

/*
 * A callback for CURLOPT_WRITEFUNCTION. The return value is the bytes consumed
 * from ptr.
 */
581
static size_t rpc_in(char *ptr, size_t eltsize,
582 583 584
		size_t nmemb, void *buffer_)
{
	size_t size = eltsize * nmemb;
585
	struct rpc_in_data *data = buffer_;
586 587 588 589 590 591 592
	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;
593
	if (size)
594 595
		data->rpc->any_written = 1;
	write_or_die(data->rpc->in, ptr, size);
596 597 598
	return size;
}

599 600
static int run_slot(struct active_request_slot *slot,
		    struct slot_results *results)
601
{
602
	int err;
603
	struct slot_results results_buf;
604

605 606 607
	if (!results)
		results = &results_buf;

J
Jeff King 已提交
608
	err = run_one_slot(slot, results);
609

610
	if (err != HTTP_OK && err != HTTP_REAUTH) {
611 612 613 614 615 616 617 618 619 620 621 622 623 624
		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);
			}
		}
		error("RPC failed; %s", msg.buf);
		strbuf_release(&msg);
625 626 627 628 629
	}

	return err;
}

630
static int probe_rpc(struct rpc_state *rpc, struct slot_results *results)
631 632
{
	struct active_request_slot *slot;
633
	struct curl_slist *headers = http_copy_default_headers();
634 635 636 637 638 639 640 641 642 643 644
	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);
645
	curl_easy_setopt(slot->curl, CURLOPT_ENCODING, NULL);
646 647 648 649 650 651
	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);

652
	err = run_slot(slot, results);
653 654 655 656 657 658

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

659 660
static curl_off_t xcurl_off_t(size_t len)
{
661 662
	uintmax_t size = len;
	if (size > maximum_signed_value_of_type(curl_off_t))
663
		die("cannot handle pushes this big");
664
	return (curl_off_t)size;
665 666
}

667 668 669
static int post_rpc(struct rpc_state *rpc)
{
	struct active_request_slot *slot;
670
	struct curl_slist *headers = http_copy_default_headers();
S
Shawn O. Pearce 已提交
671 672
	int use_gzip = rpc->gzip_request;
	char *gzip_body = NULL;
673
	size_t gzip_size = 0;
674
	int err, large_request = 0;
675
	int needs_100_continue = 0;
676
	struct rpc_in_data rpc_in_data;
677 678 679 680 681 682 683 684 685 686 687 688

	/* 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.
	 */
	while (1) {
		size_t left = rpc->alloc - rpc->len;
		char *buf = rpc->buf + rpc->len;
		int n;

		if (left < LARGE_PACKET_MAX) {
			large_request = 1;
S
Shawn O. Pearce 已提交
689
			use_gzip = 0;
690 691 692
			break;
		}

693
		n = packet_read(rpc->out, NULL, NULL, buf, left, 0);
694 695 696 697 698
		if (!n)
			break;
		rpc->len += n;
	}

699
	if (large_request) {
700 701
		struct slot_results results;

702
		do {
703
			err = probe_rpc(rpc, &results);
704 705
			if (err == HTTP_REAUTH)
				credential_fill(&http_auth);
706 707 708
		} while (err == HTTP_REAUTH);
		if (err != HTTP_OK)
			return -1;
709 710 711

		if (results.auth_avail & CURLAUTH_GSSNEGOTIATE)
			needs_100_continue = 1;
712 713
	}

714 715
	headers = curl_slist_append(headers, rpc->hdr_content_type);
	headers = curl_slist_append(headers, rpc->hdr_accept);
716 717
	headers = curl_slist_append(headers, needs_100_continue ?
		"Expect: 100-continue" : "Expect:");
718

719 720 721 722
	/* Add the extra Git-Protocol header */
	if (rpc->protocol_header)
		headers = curl_slist_append(headers, rpc->protocol_header);

723
retry:
724 725 726
	slot = get_active_slot();

	curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
727
	curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
728
	curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
729
	curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
730 731 732 733 734 735

	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");
736
		rpc->initial_buffer = 1;
737 738
		curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, rpc_out);
		curl_easy_setopt(slot->curl, CURLOPT_INFILE, rpc);
739 740 741 742
#ifndef NO_CURL_IOCTL
		curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, rpc_ioctl);
		curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, rpc);
#endif
743 744 745 746 747
		if (options.verbosity > 1) {
			fprintf(stderr, "POST %s (chunked)\n", rpc->service_name);
			fflush(stderr);
		}

748 749 750 751 752 753 754
	} 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);
755
		curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(gzip_size));
756

S
Shawn O. Pearce 已提交
757 758
	} else if (use_gzip && 1024 < rpc->len) {
		/* The client backend isn't giving us compressed data so
759
		 * we can try to deflate it ourselves, this may save on
S
Shawn O. Pearce 已提交
760 761
		 * the transfer time.
		 */
762
		git_zstream stream;
S
Shawn O. Pearce 已提交
763 764
		int ret;

765
		git_deflate_init_gzip(&stream, Z_BEST_COMPRESSION);
766 767
		gzip_size = git_deflate_bound(&stream, rpc->len);
		gzip_body = xmalloc(gzip_size);
S
Shawn O. Pearce 已提交
768 769 770 771

		stream.next_in = (unsigned char *)rpc->buf;
		stream.avail_in = rpc->len;
		stream.next_out = (unsigned char *)gzip_body;
772
		stream.avail_out = gzip_size;
S
Shawn O. Pearce 已提交
773

774
		ret = git_deflate(&stream, Z_FINISH);
S
Shawn O. Pearce 已提交
775 776 777
		if (ret != Z_STREAM_END)
			die("cannot deflate request; zlib deflate error %d", ret);

778
		ret = git_deflate_end_gently(&stream);
S
Shawn O. Pearce 已提交
779 780 781
		if (ret != Z_OK)
			die("cannot deflate request; zlib end error %d", ret);

782
		gzip_size = stream.total_out;
S
Shawn O. Pearce 已提交
783 784 785

		headers = curl_slist_append(headers, "Content-Encoding: gzip");
		curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
786
		curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(gzip_size));
S
Shawn O. Pearce 已提交
787 788 789 790

		if (options.verbosity > 1) {
			fprintf(stderr, "POST %s (gzip %lu to %lu bytes)\n",
				rpc->service_name,
791
				(unsigned long)rpc->len, (unsigned long)gzip_size);
S
Shawn O. Pearce 已提交
792 793
			fflush(stderr);
		}
794 795 796 797 798
	} 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);
799
		curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(rpc->len));
800 801 802 803 804 805 806 807 808
		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);
809
	rpc_in_data.rpc = rpc;
810
	rpc_in_data.slot = slot;
811
	curl_easy_setopt(slot->curl, CURLOPT_FILE, &rpc_in_data);
812
	curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
813

814 815

	rpc->any_written = 0;
816
	err = run_slot(slot, NULL);
817 818
	if (err == HTTP_REAUTH && !large_request) {
		credential_fill(&http_auth);
819
		goto retry;
820
	}
821 822
	if (err != HTTP_OK)
		err = -1;
823

824 825 826
	if (!rpc->any_written)
		err = -1;

827
	curl_slist_free_all(headers);
S
Shawn O. Pearce 已提交
828
	free(gzip_body);
829 830 831 832 833 834 835
	return err;
}

static int rpc_service(struct rpc_state *rpc, struct discovery *heads)
{
	const char *svc = rpc->service_name;
	struct strbuf buf = STRBUF_INIT;
836
	struct strbuf *preamble = rpc->stdin_preamble;
837
	struct child_process client = CHILD_PROCESS_INIT;
838 839 840 841 842 843 844 845
	int err = 0;

	client.in = -1;
	client.out = -1;
	client.git_cmd = 1;
	client.argv = rpc->argv;
	if (start_command(&client))
		exit(1);
846 847
	if (preamble)
		write_or_die(client.in, preamble->buf, preamble->len);
848 849 850 851 852 853 854 855 856
	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;
	strbuf_init(&rpc->result, 0);

J
Jeff King 已提交
857
	strbuf_addf(&buf, "%s%s", url.buf, svc);
858 859 860 861 862
	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);

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

866 867 868 869 870
	if (get_protocol_http_header(heads->version, &buf))
		rpc->protocol_header = strbuf_detach(&buf, NULL);
	else
		rpc->protocol_header = NULL;

871
	while (!err) {
872
		int n = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
873 874 875 876 877 878 879 880 881
		if (!n)
			break;
		rpc->pos = 0;
		rpc->len = n;
		err |= post_rpc(rpc);
	}

	close(client.in);
	client.in = -1;
882 883 884 885 886 887 888 889
	if (!err) {
		strbuf_read(&rpc->result, client.out, 0);
	} else {
		char buf[4096];
		for (;;)
			if (xread(client.out, buf, sizeof(buf)) <= 0)
				break;
	}
890 891

	close(client.out);
892 893 894 895 896 897
	client.out = -1;

	err |= finish_command(&client);
	free(rpc->service_url);
	free(rpc->hdr_content_type);
	free(rpc->hdr_accept);
898
	free(rpc->protocol_header);
899 900 901 902 903
	free(rpc->buf);
	strbuf_release(&buf);
	return err;
}

904 905
static int fetch_dumb(int nr_heads, struct ref **to_fetch)
{
906
	struct walker *walker;
J
Jeff King 已提交
907
	char **targets;
908 909
	int ret, i;

J
Jeff King 已提交
910
	ALLOC_ARRAY(targets, nr_heads);
911 912
	if (options.depth || options.deepen_since)
		die("dumb http transport does not support shallow capabilities");
913
	for (i = 0; i < nr_heads; i++)
914
		targets[i] = xstrdup(oid_to_hex(&to_fetch[i]->old_oid));
915

J
Jeff King 已提交
916
	walker = get_http_walker(url.buf);
917
	walker->get_verbosely = options.verbosity >= 3;
918 919
	walker->get_recover = 0;
	ret = walker_fetch(walker, nr_heads, targets, NULL, NULL);
920
	walker_free(walker);
921 922 923 924 925

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

926
	return ret ? error("fetch failed.") : 0;
927 928
}

929 930 931 932
static int fetch_git(struct discovery *heads,
	int nr_heads, struct ref **to_fetch)
{
	struct rpc_state rpc;
933
	struct strbuf preamble = STRBUF_INIT;
934 935 936 937 938
	int i, err;
	struct argv_array args = ARGV_ARRAY_INIT;

	argv_array_pushl(&args, "fetch-pack", "--stateless-rpc",
			 "--stdin", "--lock-pack", NULL);
939
	if (options.followtags)
940
		argv_array_push(&args, "--include-tag");
941
	if (options.thin)
942 943 944
		argv_array_push(&args, "--thin");
	if (options.verbosity >= 3)
		argv_array_pushl(&args, "-v", "-v", NULL);
945
	if (options.check_self_contained_and_connected)
946
		argv_array_push(&args, "--check-self-contained-and-connected");
947
	if (options.cloning)
948
		argv_array_push(&args, "--cloning");
949
	if (options.update_shallow)
950
		argv_array_push(&args, "--update-shallow");
951
	if (!options.progress)
952 953 954
		argv_array_push(&args, "--no-progress");
	if (options.depth)
		argv_array_pushf(&args, "--depth=%lu", options.depth);
955 956
	if (options.deepen_since)
		argv_array_pushf(&args, "--shallow-since=%s", options.deepen_since);
957 958 959
	for (i = 0; i < options.deepen_not.nr; i++)
		argv_array_pushf(&args, "--shallow-exclude=%s",
				 options.deepen_not.items[i].string);
960 961
	if (options.deepen_relative && options.depth)
		argv_array_push(&args, "--deepen-relative");
962 963 964 965
	if (options.from_promisor)
		argv_array_push(&args, "--from-promisor");
	if (options.no_dependents)
		argv_array_push(&args, "--no-dependents");
J
Jeff Hostetler 已提交
966 967
	if (options.filter)
		argv_array_pushf(&args, "--filter=%s", options.filter);
968
	argv_array_push(&args, url.buf);
969

970 971
	for (i = 0; i < nr_heads; i++) {
		struct ref *ref = to_fetch[i];
972
		if (!*ref->name)
973
			die("cannot fetch by sha1 over smart http");
974
		packet_buf_write(&preamble, "%s %s\n",
975
				 oid_to_hex(&ref->old_oid), ref->name);
976
	}
977
	packet_buf_flush(&preamble);
978 979 980

	memset(&rpc, 0, sizeof(rpc));
	rpc.service_name = "git-upload-pack",
981
	rpc.argv = args.argv;
982
	rpc.stdin_preamble = &preamble;
S
Shawn O. Pearce 已提交
983
	rpc.gzip_request = 1;
984 985 986

	err = rpc_service(&rpc, heads);
	if (rpc.result.len)
J
Jeff King 已提交
987
		write_or_die(1, rpc.result.buf, rpc.result.len);
988
	strbuf_release(&rpc.result);
989
	strbuf_release(&preamble);
990
	argv_array_clear(&args);
991 992 993 994 995
	return err;
}

static int fetch(int nr_heads, struct ref **to_fetch)
{
996
	struct discovery *d = discover_refs("git-upload-pack", 0);
997 998 999 1000 1001 1002
	if (d->proto_git)
		return fetch_git(d, nr_heads, to_fetch);
	else
		return fetch_dumb(nr_heads, to_fetch);
}

1003 1004 1005 1006 1007 1008 1009 1010
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 {
1011 1012 1013
		const char *p;
		if (skip_prefix(buf->buf, "fetch ", &p)) {
			const char *name;
1014
			struct ref *ref;
1015
			struct object_id old_oid;
1016

1017
			if (get_oid_hex(p, &old_oid))
1018
				die("protocol error: expected sha/ref, got %s'", p);
1019 1020 1021
			if (p[GIT_SHA1_HEXSZ] == ' ')
				name = p + GIT_SHA1_HEXSZ + 1;
			else if (!p[GIT_SHA1_HEXSZ])
1022 1023 1024 1025 1026
				name = "";
			else
				die("protocol error: expected sha/ref, got %s'", p);

			ref = alloc_ref(name);
1027
			oidcpy(&ref->old_oid, &old_oid);
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038

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

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

		strbuf_reset(buf);
1039
		if (strbuf_getline_lf(buf, stdin) == EOF)
1040 1041 1042 1043 1044
			return;
		if (!*buf->buf)
			break;
	} while (1);

1045
	if (fetch(nr_heads, to_fetch))
1046 1047 1048 1049 1050 1051 1052 1053 1054
		exit(128); /* error already reported */
	free_refs(list_head);
	free(to_fetch);

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

1055 1056
static int push_dav(int nr_spec, char **specs)
{
1057 1058
	struct child_process child = CHILD_PROCESS_INIT;
	size_t i;
1059

1060 1061 1062
	child.git_cmd = 1;
	argv_array_push(&child.args, "http-push");
	argv_array_push(&child.args, "--helper-status");
1063
	if (options.dry_run)
1064
		argv_array_push(&child.args, "--dry-run");
1065
	if (options.verbosity > 1)
1066 1067
		argv_array_push(&child.args, "--verbose");
	argv_array_push(&child.args, url.buf);
1068
	for (i = 0; i < nr_spec; i++)
1069
		argv_array_push(&child.args, specs[i]);
1070

1071 1072
	if (run_command(&child))
		die("git-http-push failed");
1073 1074 1075
	return 0;
}

1076 1077 1078
static int push_git(struct discovery *heads, int nr_spec, char **specs)
{
	struct rpc_state rpc;
J
Junio C Hamano 已提交
1079 1080
	int i, err;
	struct argv_array args;
1081
	struct string_list_item *cas_option;
J
Jeff King 已提交
1082
	struct strbuf preamble = STRBUF_INIT;
J
Junio C Hamano 已提交
1083 1084 1085 1086

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

	if (options.thin)
J
Junio C Hamano 已提交
1089
		argv_array_push(&args, "--thin");
1090
	if (options.dry_run)
J
Junio C Hamano 已提交
1091
		argv_array_push(&args, "--dry-run");
1092 1093 1094 1095
	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");
1096
	if (options.verbosity == 0)
J
Junio C Hamano 已提交
1097
		argv_array_push(&args, "--quiet");
1098
	else if (options.verbosity > 1)
J
Junio C Hamano 已提交
1099
		argv_array_push(&args, "--verbose");
1100 1101 1102
	for (i = 0; i < options.push_options.nr; i++)
		argv_array_pushf(&args, "--push-option=%s",
				 options.push_options.items[i].string);
J
Junio C Hamano 已提交
1103
	argv_array_push(&args, options.progress ? "--progress" : "--no-progress");
1104
	for_each_string_list_item(cas_option, &cas_options)
J
Junio C Hamano 已提交
1105
		argv_array_push(&args, cas_option->string);
J
Jeff King 已提交
1106
	argv_array_push(&args, url.buf);
J
Jeff King 已提交
1107 1108

	argv_array_push(&args, "--stdin");
1109
	for (i = 0; i < nr_spec; i++)
J
Jeff King 已提交
1110 1111
		packet_buf_write(&preamble, "%s\n", specs[i]);
	packet_buf_flush(&preamble);
1112 1113 1114

	memset(&rpc, 0, sizeof(rpc));
	rpc.service_name = "git-receive-pack",
J
Junio C Hamano 已提交
1115
	rpc.argv = args.argv;
J
Jeff King 已提交
1116
	rpc.stdin_preamble = &preamble;
1117 1118 1119

	err = rpc_service(&rpc, heads);
	if (rpc.result.len)
J
Jeff King 已提交
1120
		write_or_die(1, rpc.result.buf, rpc.result.len);
1121
	strbuf_release(&rpc.result);
J
Jeff King 已提交
1122
	strbuf_release(&preamble);
J
Junio C Hamano 已提交
1123
	argv_array_clear(&args);
1124 1125 1126 1127 1128
	return err;
}

static int push(int nr_spec, char **specs)
{
1129
	struct discovery *heads = discover_refs("git-receive-pack", 1);
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
	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;
}

1140 1141 1142
static void parse_push(struct strbuf *buf)
{
	char **specs = NULL;
1143
	int alloc_spec = 0, nr_spec = 0, i, ret;
1144 1145

	do {
1146
		if (starts_with(buf->buf, "push ")) {
1147 1148 1149 1150 1151 1152 1153
			ALLOC_GROW(specs, nr_spec + 1, alloc_spec);
			specs[nr_spec++] = xstrdup(buf->buf + 5);
		}
		else
			die("http transport does not support %s", buf->buf);

		strbuf_reset(buf);
1154
		if (strbuf_getline_lf(buf, stdin) == EOF)
J
Jim Meyering 已提交
1155
			goto free_specs;
1156 1157 1158 1159
		if (!*buf->buf)
			break;
	} while (1);

1160
	ret = push(nr_spec, specs);
1161 1162
	printf("\n");
	fflush(stdout);
J
Jim Meyering 已提交
1163

1164 1165 1166
	if (ret)
		exit(128); /* error already reported */

J
Jim Meyering 已提交
1167 1168 1169 1170
 free_specs:
	for (i = 0; i < nr_spec; i++)
		free(specs[i]);
	free(specs);
1171 1172
}

1173 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 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
/*
 * Used to represent the state of a connection to an HTTP server when
 * communicating using git's wire-protocol version 2.
 */
struct proxy_state {
	char *service_name;
	char *service_url;
	struct curl_slist *headers;
	struct strbuf request_buffer;
	int in;
	int out;
	struct packet_reader reader;
	size_t pos;
	int seen_flush;
};

static void proxy_state_init(struct proxy_state *p, const char *service_name,
			     enum protocol_version version)
{
	struct strbuf buf = STRBUF_INIT;

	memset(p, 0, sizeof(*p));
	p->service_name = xstrdup(service_name);

	p->in = 0;
	p->out = 1;
	strbuf_init(&p->request_buffer, 0);

	strbuf_addf(&buf, "%s%s", url.buf, p->service_name);
	p->service_url = strbuf_detach(&buf, NULL);

	p->headers = http_copy_default_headers();

	strbuf_addf(&buf, "Content-Type: application/x-%s-request", p->service_name);
	p->headers = curl_slist_append(p->headers, buf.buf);
	strbuf_reset(&buf);

	strbuf_addf(&buf, "Accept: application/x-%s-result", p->service_name);
	p->headers = curl_slist_append(p->headers, buf.buf);
	strbuf_reset(&buf);

	p->headers = curl_slist_append(p->headers, "Transfer-Encoding: chunked");

	/* Add the Git-Protocol header */
	if (get_protocol_http_header(version, &buf))
		p->headers = curl_slist_append(p->headers, buf.buf);

	packet_reader_init(&p->reader, p->in, NULL, 0,
1221 1222
			   PACKET_READ_GENTLE_ON_EOF |
			   PACKET_READ_DIE_ON_ERR_PACKET);
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307

	strbuf_release(&buf);
}

static void proxy_state_clear(struct proxy_state *p)
{
	free(p->service_name);
	free(p->service_url);
	curl_slist_free_all(p->headers);
	strbuf_release(&p->request_buffer);
}

/*
 * CURLOPT_READFUNCTION callback function.
 * Attempts to copy over a single packet-line at a time into the
 * curl provided buffer.
 */
static size_t proxy_in(char *buffer, size_t eltsize,
		       size_t nmemb, void *userdata)
{
	size_t max;
	struct proxy_state *p = userdata;
	size_t avail = p->request_buffer.len - p->pos;


	if (eltsize != 1)
		BUG("curl read callback called with size = %"PRIuMAX" != 1",
		    (uintmax_t)eltsize);
	max = nmemb;

	if (!avail) {
		if (p->seen_flush) {
			p->seen_flush = 0;
			return 0;
		}

		strbuf_reset(&p->request_buffer);
		switch (packet_reader_read(&p->reader)) {
		case PACKET_READ_EOF:
			die("unexpected EOF when reading from parent process");
		case PACKET_READ_NORMAL:
			packet_buf_write_len(&p->request_buffer, p->reader.line,
					     p->reader.pktlen);
			break;
		case PACKET_READ_DELIM:
			packet_buf_delim(&p->request_buffer);
			break;
		case PACKET_READ_FLUSH:
			packet_buf_flush(&p->request_buffer);
			p->seen_flush = 1;
			break;
		}
		p->pos = 0;
		avail = p->request_buffer.len;
	}

	if (max < avail)
		avail = max;
	memcpy(buffer, p->request_buffer.buf + p->pos, avail);
	p->pos += avail;
	return avail;
}

static size_t proxy_out(char *buffer, size_t eltsize,
			size_t nmemb, void *userdata)
{
	size_t size;
	struct proxy_state *p = userdata;

	if (eltsize != 1)
		BUG("curl read callback called with size = %"PRIuMAX" != 1",
		    (uintmax_t)eltsize);
	size = nmemb;

	write_or_die(p->out, buffer, size);
	return size;
}

/* Issues a request to the HTTP server configured in `p` */
static int proxy_request(struct proxy_state *p)
{
	struct active_request_slot *slot;

	slot = get_active_slot();

1308
	curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
	curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
	curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
	curl_easy_setopt(slot->curl, CURLOPT_URL, p->service_url);
	curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, p->headers);

	/* Setup function to read request from client */
	curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, proxy_in);
	curl_easy_setopt(slot->curl, CURLOPT_READDATA, p);

	/* Setup function to write server response to client */
	curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, proxy_out);
	curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, p);

	if (run_slot(slot, NULL) != HTTP_OK)
		return -1;

	return 0;
}

static int stateless_connect(const char *service_name)
{
	struct discovery *discover;
	struct proxy_state p;

	/*
	 * 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);
	}

	proxy_state_init(&p, service_name, discover->version);

	/*
	 * Dump the capability listing that we got from the server earlier
	 * during the info/refs request.
	 */
	write_or_die(p.out, discover->buf, discover->len);

	/* Peek the next packet line.  Until we see EOF keep sending POSTs */
	while (packet_reader_peek(&p.reader) != PACKET_READ_EOF) {
		if (proxy_request(&p)) {
			/* We would have an err here */
			break;
		}
	}

	proxy_state_clear(&p);
	return 0;
}

1371
int cmd_main(int argc, const char **argv)
1372 1373
{
	struct strbuf buf = STRBUF_INIT;
1374
	int nongit;
1375

1376
	setup_git_directory_gently(&nongit);
1377
	if (argc < 2) {
1378
		error("remote-curl: usage: git remote-curl <remote> [<url>]");
1379 1380 1381
		return 1;
	}

1382 1383
	options.verbosity = 1;
	options.progress = !!isatty(2);
1384
	options.thin = 1;
1385
	string_list_init(&options.deepen_not, 1);
1386
	string_list_init(&options.push_options, 1);
1387

1388 1389 1390
	remote = remote_get(argv[1]);

	if (argc > 2) {
J
Jeff King 已提交
1391
		end_url_with_slash(&url, argv[2]);
1392
	} else {
J
Jeff King 已提交
1393
		end_url_with_slash(&url, remote->url[0]);
1394 1395
	}

J
Jeff King 已提交
1396
	http_init(remote, url.buf, 0);
1397

1398
	do {
1399 1400
		const char *arg;

1401
		if (strbuf_getline_lf(&buf, stdin) == EOF) {
1402
			if (ferror(stdin))
1403
				error("remote-curl: error reading command stream from git");
1404 1405 1406
			return 1;
		}
		if (buf.len == 0)
1407
			break;
1408
		if (starts_with(buf.buf, "fetch ")) {
1409
			if (nongit)
1410
				die("remote-curl: fetch attempted without a local repo");
1411 1412
			parse_fetch(&buf);

1413
		} else if (!strcmp(buf.buf, "list") || starts_with(buf.buf, "list ")) {
1414 1415
			int for_push = !!strstr(buf.buf + 4, "for-push");
			output_refs(get_refs(for_push));
1416

1417
		} else if (starts_with(buf.buf, "push ")) {
1418 1419
			parse_push(&buf);

1420 1421
		} else if (skip_prefix(buf.buf, "option ", &arg)) {
			char *value = strchr(arg, ' ');
1422 1423 1424 1425 1426 1427 1428
			int result;

			if (value)
				*value++ = '\0';
			else
				value = "true";

1429
			result = set_option(arg, value);
1430 1431 1432 1433 1434 1435
			if (!result)
				printf("ok\n");
			else if (result < 0)
				printf("error invalid value\n");
			else
				printf("unsupported\n");
1436
			fflush(stdout);
1437

1438
		} else if (!strcmp(buf.buf, "capabilities")) {
1439
			printf("stateless-connect\n");
1440
			printf("fetch\n");
1441
			printf("option\n");
1442
			printf("push\n");
1443
			printf("check-connectivity\n");
1444 1445
			printf("\n");
			fflush(stdout);
1446 1447 1448
		} else if (skip_prefix(buf.buf, "stateless-connect ", &arg)) {
			if (!stateless_connect(arg))
				break;
1449
		} else {
1450
			error("remote-curl: unknown command '%s' from git", buf.buf);
1451 1452 1453 1454
			return 1;
		}
		strbuf_reset(&buf);
	} while (1);
1455 1456 1457

	http_cleanup();

1458 1459
	return 0;
}