http-backend.c 15.7 KB
Newer Older
1 2 3 4 5 6
#include "cache.h"
#include "refs.h"
#include "pkt-line.h"
#include "object.h"
#include "tag.h"
#include "exec_cmd.h"
7 8
#include "run-command.h"
#include "string-list.h"
J
Jeff King 已提交
9
#include "url.h"
10
#include "argv-array.h"
11 12 13 14

static const char content_type[] = "Content-Type";
static const char content_length[] = "Content-Length";
static const char last_modified[] = "Last-Modified";
15
static int getanyfile = 1;
16
static unsigned long max_request_buffer = 10 * 1024 * 1024;
17

18 19 20 21 22
static struct string_list *query_params;

struct rpc_service {
	const char *name;
	const char *config_name;
23
	unsigned buffer_input : 1;
24 25 26 27
	signed enabled : 2;
};

static struct rpc_service rpc_service[] = {
28 29
	{ "upload-pack", "uploadpack", 1, 1 },
	{ "receive-pack", "receivepack", 0, -1 },
30 31 32 33 34 35 36 37 38
};

static struct string_list *get_parameters(void)
{
	if (!query_params) {
		const char *query = getenv("QUERY_STRING");

		query_params = xcalloc(1, sizeof(*query_params));
		while (query && *query) {
J
Jeff King 已提交
39 40
			char *name = url_decode_parameter_name(&query);
			char *value = url_decode_parameter_value(&query);
41 42
			struct string_list_item *i;

43
			i = string_list_lookup(query_params, name);
44
			if (!i)
45
				i = string_list_insert(query_params, name);
46 47 48 49 50 51 52 53 54 55 56
			else
				free(i->util);
			i->util = value;
		}
	}
	return query_params;
}

static const char *get_parameter(const char *name)
{
	struct string_list_item *i;
57
	i = string_list_lookup(get_parameters(), name);
58 59 60
	return i ? i->util : NULL;
}

61
__attribute__((format (printf, 2, 3)))
62 63 64 65 66 67 68 69 70 71 72 73 74
static void format_write(int fd, const char *fmt, ...)
{
	static char buffer[1024];

	va_list args;
	unsigned n;

	va_start(args, fmt);
	n = vsnprintf(buffer, sizeof(buffer), fmt, args);
	va_end(args);
	if (n >= sizeof(buffer))
		die("protocol error: impossibly long line");

J
Jeff King 已提交
75
	write_or_die(fd, buffer, n);
76 77 78 79 80 81 82 83 84 85 86 87
}

static void http_status(unsigned code, const char *msg)
{
	format_write(1, "Status: %u %s\r\n", code, msg);
}

static void hdr_str(const char *name, const char *value)
{
	format_write(1, "%s: %s\r\n", name, value);
}

88
static void hdr_int(const char *name, uintmax_t value)
89 90 91 92 93 94
{
	format_write(1, "%s: %" PRIuMAX "\r\n", name, value);
}

static void hdr_date(const char *name, unsigned long when)
{
95
	const char *value = show_date(when, 0, DATE_MODE(RFC2822));
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
	hdr_str(name, value);
}

static void hdr_nocache(void)
{
	hdr_str("Expires", "Fri, 01 Jan 1980 00:00:00 GMT");
	hdr_str("Pragma", "no-cache");
	hdr_str("Cache-Control", "no-cache, max-age=0, must-revalidate");
}

static void hdr_cache_forever(void)
{
	unsigned long now = time(NULL);
	hdr_date("Date", now);
	hdr_date("Expires", now + 31536000);
	hdr_str("Cache-Control", "public, max-age=31536000");
}

static void end_headers(void)
{
J
Jeff King 已提交
116
	write_or_die(1, "\r\n", 2);
117 118
}

119
__attribute__((format (printf, 1, 2)))
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
static NORETURN void not_found(const char *err, ...)
{
	va_list params;

	http_status(404, "Not Found");
	hdr_nocache();
	end_headers();

	va_start(params, err);
	if (err && *err)
		vfprintf(stderr, err, params);
	va_end(params);
	exit(0);
}

135
__attribute__((format (printf, 1, 2)))
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
static NORETURN void forbidden(const char *err, ...)
{
	va_list params;

	http_status(403, "Forbidden");
	hdr_nocache();
	end_headers();

	va_start(params, err);
	if (err && *err)
		vfprintf(stderr, err, params);
	va_end(params);
	exit(0);
}

151 152 153 154 155 156
static void select_getanyfile(void)
{
	if (!getanyfile)
		forbidden("Unsupported service: getanyfile");
}

157 158 159 160 161
static void send_strbuf(const char *type, struct strbuf *buf)
{
	hdr_int(content_length, buf->len);
	hdr_str(content_type, type);
	end_headers();
J
Jeff King 已提交
162
	write_or_die(1, buf->buf, buf->len);
163 164
}

165
static void send_local_file(const char *the_type, const char *name)
166
{
167
	char *p = git_pathdup("%s", name);
168 169 170 171 172 173 174 175 176 177 178
	size_t buf_alloc = 8192;
	char *buf = xmalloc(buf_alloc);
	int fd;
	struct stat sb;

	fd = open(p, O_RDONLY);
	if (fd < 0)
		not_found("Cannot open '%s': %s", p, strerror(errno));
	if (fstat(fd, &sb) < 0)
		die_errno("Cannot stat '%s'", p);

179
	hdr_int(content_length, sb.st_size);
180 181 182 183
	hdr_str(content_type, the_type);
	hdr_date(last_modified, sb.st_mtime);
	end_headers();

184
	for (;;) {
185 186 187 188 189
		ssize_t n = xread(fd, buf, buf_alloc);
		if (n < 0)
			die_errno("Cannot read '%s'", p);
		if (!n)
			break;
J
Jeff King 已提交
190
		write_or_die(1, buf, n);
191 192 193
	}
	close(fd);
	free(buf);
194
	free(p);
195 196 197 198
}

static void get_text_file(char *name)
{
199
	select_getanyfile();
200
	hdr_nocache();
201
	send_local_file("text/plain", name);
202 203 204 205
}

static void get_loose_object(char *name)
{
206
	select_getanyfile();
207
	hdr_cache_forever();
208
	send_local_file("application/x-git-loose-object", name);
209 210 211 212
}

static void get_pack_file(char *name)
{
213
	select_getanyfile();
214
	hdr_cache_forever();
215
	send_local_file("application/x-git-packed-objects", name);
216 217 218 219
}

static void get_idx_file(char *name)
{
220
	select_getanyfile();
221
	hdr_cache_forever();
222
	send_local_file("application/x-git-packed-objects-toc", name);
223 224
}

225
static void http_config(void)
226
{
227 228
	int i, value = 0;
	struct strbuf var = STRBUF_INIT;
229

230
	git_config_get_bool("http.getanyfile", &getanyfile);
231
	git_config_get_ulong("http.maxrequestbuffer", &max_request_buffer);
232

233 234 235 236 237 238
	for (i = 0; i < ARRAY_SIZE(rpc_service); i++) {
		struct rpc_service *svc = &rpc_service[i];
		strbuf_addf(&var, "http.%s", svc->config_name);
		if (!git_config_get_bool(var.buf, &value))
			svc->enabled = value;
		strbuf_reset(&var);
239 240
	}

241
	strbuf_release(&var);
242 243 244 245
}

static struct rpc_service *select_service(const char *name)
{
246
	const char *svc_name;
247 248 249
	struct rpc_service *svc = NULL;
	int i;

250
	if (!skip_prefix(name, "git-", &svc_name))
251 252 253 254
		forbidden("Unsupported service: '%s'", name);

	for (i = 0; i < ARRAY_SIZE(rpc_service); i++) {
		struct rpc_service *s = &rpc_service[i];
255
		if (!strcmp(s->name, svc_name)) {
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
			svc = s;
			break;
		}
	}

	if (!svc)
		forbidden("Unsupported service: '%s'", name);

	if (svc->enabled < 0) {
		const char *user = getenv("REMOTE_USER");
		svc->enabled = (user && *user) ? 1 : 0;
	}
	if (!svc->enabled)
		forbidden("Service not enabled: '%s'", svc->name);
	return svc;
}

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
/*
 * This is basically strbuf_read(), except that if we
 * hit max_request_buffer we die (we'd rather reject a
 * maliciously large request than chew up infinite memory).
 */
static ssize_t read_request(int fd, unsigned char **out)
{
	size_t len = 0, alloc = 8192;
	unsigned char *buf = xmalloc(alloc);

	if (max_request_buffer < alloc)
		max_request_buffer = alloc;

	while (1) {
		ssize_t cnt;

		cnt = read_in_full(fd, buf + len, alloc - len);
		if (cnt < 0) {
			free(buf);
			return -1;
		}

		/* partial read from read_in_full means we hit EOF */
		len += cnt;
		if (len < alloc) {
			*out = buf;
			return len;
		}

		/* otherwise, grow and try again (if we can) */
		if (alloc == max_request_buffer)
			die("request was larger than our maximum size (%lu);"
			    " try setting GIT_HTTP_MAX_REQUEST_BUFFER",
			    max_request_buffer);

		alloc = alloc_nr(alloc);
		if (alloc > max_request_buffer)
			alloc = max_request_buffer;
		REALLOC_ARRAY(buf, alloc);
	}
}

static void inflate_request(const char *prog_name, int out, int buffer_input)
316
{
317
	git_zstream stream;
318
	unsigned char *full_request = NULL;
319 320 321 322 323
	unsigned char in_buf[8192];
	unsigned char out_buf[8192];
	unsigned long cnt = 0;

	memset(&stream, 0, sizeof(stream));
324
	git_inflate_init_gzip_only(&stream);
325 326

	while (1) {
327 328 329 330 331 332 333 334 335 336 337 338 339
		ssize_t n;

		if (buffer_input) {
			if (full_request)
				n = 0; /* nothing left to read */
			else
				n = read_request(0, &full_request);
			stream.next_in = full_request;
		} else {
			n = xread(0, in_buf, sizeof(in_buf));
			stream.next_in = in_buf;
		}

340 341 342 343 344 345 346 347 348 349
		if (n <= 0)
			die("request ended in the middle of the gzip stream");
		stream.avail_in = n;

		while (0 < stream.avail_in) {
			int ret;

			stream.next_out = out_buf;
			stream.avail_out = sizeof(out_buf);

350
			ret = git_inflate(&stream, Z_NO_FLUSH);
351 352 353 354 355 356 357 358 359 360 361 362 363 364
			if (ret != Z_OK && ret != Z_STREAM_END)
				die("zlib error inflating request, result %d", ret);

			n = stream.total_out - cnt;
			if (write_in_full(out, out_buf, n) != n)
				die("%s aborted reading request", prog_name);
			cnt += n;

			if (ret == Z_STREAM_END)
				goto done;
		}
	}

done:
365
	git_inflate_end(&stream);
366
	close(out);
367 368 369 370 371 372 373 374 375 376 377 378 379
	free(full_request);
}

static void copy_request(const char *prog_name, int out)
{
	unsigned char *buf;
	ssize_t n = read_request(0, &buf);
	if (n < 0)
		die_errno("error reading request body");
	if (write_in_full(out, buf, n) != n)
		die("%s aborted reading request", prog_name);
	close(out);
	free(buf);
380 381
}

382
static void run_service(const char **argv, int buffer_input)
383 384 385 386 387
{
	const char *encoding = getenv("HTTP_CONTENT_ENCODING");
	const char *user = getenv("REMOTE_USER");
	const char *host = getenv("REMOTE_ADDR");
	int gzipped_request = 0;
388
	struct child_process cld = CHILD_PROCESS_INIT;
389 390 391 392 393 394 395 396 397 398 399

	if (encoding && !strcmp(encoding, "gzip"))
		gzipped_request = 1;
	else if (encoding && !strcmp(encoding, "x-gzip"))
		gzipped_request = 1;

	if (!user || !*user)
		user = "anonymous";
	if (!host || !*host)
		host = "(none)";

400
	if (!getenv("GIT_COMMITTER_NAME"))
401
		argv_array_pushf(&cld.env_array, "GIT_COMMITTER_NAME=%s", user);
402
	if (!getenv("GIT_COMMITTER_EMAIL"))
403 404
		argv_array_pushf(&cld.env_array,
				 "GIT_COMMITTER_EMAIL=%s@http.%s", user, host);
405 406

	cld.argv = argv;
407
	if (buffer_input || gzipped_request)
408 409 410 411 412 413 414
		cld.in = -1;
	cld.git_cmd = 1;
	if (start_command(&cld))
		exit(1);

	close(1);
	if (gzipped_request)
415 416 417
		inflate_request(argv[0], cld.in, buffer_input);
	else if (buffer_input)
		copy_request(argv[0], cld.in);
418 419 420 421 422 423 424
	else
		close(0);

	if (finish_command(&cld))
		exit(1);
}

425 426
static int show_text_ref(const char *name, const struct object_id *oid,
			 int flag, void *cb_data)
427
{
428
	const char *name_nons = strip_namespace(name);
429
	struct strbuf *buf = cb_data;
430
	struct object *o = parse_object(oid->hash);
431 432 433
	if (!o)
		return 0;

434
	strbuf_addf(buf, "%s\t%s\n", oid_to_hex(oid), name_nons);
435 436 437 438
	if (o->type == OBJ_TAG) {
		o = deref_tag(o, name, 0);
		if (!o)
			return 0;
439
		strbuf_addf(buf, "%s\t%s^{}\n", oid_to_hex(&o->oid),
440
			    name_nons);
441 442 443 444 445 446
	}
	return 0;
}

static void get_info_refs(char *arg)
{
447
	const char *service_name = get_parameter("service");
448 449 450
	struct strbuf buf = STRBUF_INIT;

	hdr_nocache();
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466

	if (service_name) {
		const char *argv[] = {NULL /* service name */,
			"--stateless-rpc", "--advertise-refs",
			".", NULL};
		struct rpc_service *svc = select_service(service_name);

		strbuf_addf(&buf, "application/x-git-%s-advertisement",
			svc->name);
		hdr_str(content_type, buf.buf);
		end_headers();

		packet_write(1, "# service=git-%s\n", svc->name);
		packet_flush(1);

		argv[0] = svc->name;
467
		run_service(argv, 0);
468 469

	} else {
470
		select_getanyfile();
471
		for_each_namespaced_ref(show_text_ref, &buf);
472 473
		send_strbuf("text/plain", &buf);
	}
474 475 476
	strbuf_release(&buf);
}

477 478
static int show_head_ref(const char *refname, const struct object_id *oid,
			 int flag, void *cb_data)
479 480 481 482
{
	struct strbuf *buf = cb_data;

	if (flag & REF_ISSYMREF) {
483
		struct object_id unused;
484 485
		const char *target = resolve_ref_unsafe(refname,
							RESOLVE_REF_READING,
486
							unused.hash, NULL);
487 488 489 490
		const char *target_nons = strip_namespace(target);

		strbuf_addf(buf, "ref: %s\n", target_nons);
	} else {
491
		strbuf_addf(buf, "%s\n", oid_to_hex(oid));
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
	}

	return 0;
}

static void get_head(char *arg)
{
	struct strbuf buf = STRBUF_INIT;

	select_getanyfile();
	head_ref_namespaced(show_head_ref, &buf);
	send_strbuf("text/plain", &buf);
	strbuf_release(&buf);
}

507 508 509 510 511 512 513
static void get_info_packs(char *arg)
{
	size_t objdirlen = strlen(get_object_directory());
	struct strbuf buf = STRBUF_INIT;
	struct packed_git *p;
	size_t cnt = 0;

514
	select_getanyfile();
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
	prepare_packed_git();
	for (p = packed_git; p; p = p->next) {
		if (p->pack_local)
			cnt++;
	}

	strbuf_grow(&buf, cnt * 53 + 2);
	for (p = packed_git; p; p = p->next) {
		if (p->pack_local)
			strbuf_addf(&buf, "P %s\n", p->pack_name + objdirlen + 6);
	}
	strbuf_addch(&buf, '\n');

	hdr_nocache();
	send_strbuf("text/plain; charset=utf-8", &buf);
	strbuf_release(&buf);
}

533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
static void check_content_type(const char *accepted_type)
{
	const char *actual_type = getenv("CONTENT_TYPE");

	if (!actual_type)
		actual_type = "";

	if (strcmp(actual_type, accepted_type)) {
		http_status(415, "Unsupported Media Type");
		hdr_nocache();
		end_headers();
		format_write(1,
			"Expected POST with Content-Type '%s',"
			" but received '%s' instead.\n",
			accepted_type, actual_type);
		exit(0);
	}
}

static void service_rpc(char *service_name)
{
	const char *argv[] = {NULL, "--stateless-rpc", ".", NULL};
	struct rpc_service *svc = select_service(service_name);
	struct strbuf buf = STRBUF_INIT;

	strbuf_reset(&buf);
	strbuf_addf(&buf, "application/x-git-%s-request", svc->name);
	check_content_type(buf.buf);

	hdr_nocache();

	strbuf_reset(&buf);
	strbuf_addf(&buf, "application/x-git-%s-result", svc->name);
	hdr_str(content_type, buf.buf);

	end_headers();

	argv[0] = svc->name;
571
	run_service(argv, svc->buffer_input);
572 573 574
	strbuf_release(&buf);
}

575
static int dead;
576 577
static NORETURN void die_webcgi(const char *err, va_list params)
{
578 579
	if (dead <= 1) {
		vreportf("fatal: ", err, params);
580

581 582 583 584 585
		http_status(500, "Internal Server Error");
		hdr_nocache();
		end_headers();
	}
	exit(0); /* we successfully reported a failure ;-) */
586 587
}

588 589 590 591 592
static int die_webcgi_recursing(void)
{
	return dead++ > 1;
}

593 594 595 596 597 598 599 600 601 602
static char* getdir(void)
{
	struct strbuf buf = STRBUF_INIT;
	char *pathinfo = getenv("PATH_INFO");
	char *root = getenv("GIT_PROJECT_ROOT");
	char *path = getenv("PATH_TRANSLATED");

	if (root && *root) {
		if (!pathinfo || !*pathinfo)
			die("GIT_PROJECT_ROOT is set but PATH_INFO is not");
603 604
		if (daemon_avoid_alias(pathinfo))
			die("'%s': aliased", pathinfo);
605
		end_url_with_slash(&buf, root);
606 607
		if (pathinfo[0] == '/')
			pathinfo++;
608 609 610 611 612 613 614 615 616
		strbuf_addstr(&buf, pathinfo);
		return strbuf_detach(&buf, NULL);
	} else if (path && *path) {
		return xstrdup(path);
	} else
		die("No GIT_PROJECT_ROOT or PATH_TRANSLATED from server");
	return NULL;
}

617 618 619 620 621
static struct service_cmd {
	const char *method;
	const char *pattern;
	void (*imp)(char *);
} services[] = {
622
	{"GET", "/HEAD$", get_head},
623 624 625 626 627 628
	{"GET", "/info/refs$", get_info_refs},
	{"GET", "/objects/info/alternates$", get_text_file},
	{"GET", "/objects/info/http-alternates$", get_text_file},
	{"GET", "/objects/info/packs$", get_info_packs},
	{"GET", "/objects/[0-9a-f]{2}/[0-9a-f]{38}$", get_loose_object},
	{"GET", "/objects/pack/pack-[0-9a-f]{40}\\.pack$", get_pack_file},
629 630 631 632
	{"GET", "/objects/pack/pack-[0-9a-f]{40}\\.idx$", get_idx_file},

	{"POST", "/git-upload-pack$", service_rpc},
	{"POST", "/git-receive-pack$", service_rpc}
633 634
};

635
int cmd_main(int argc, const char **argv)
636 637
{
	char *method = getenv("REQUEST_METHOD");
638
	char *dir;
639 640 641 642
	struct service_cmd *cmd = NULL;
	char *cmd_arg = NULL;
	int i;

643 644
	git_setup_gettext();

645 646
	git_extract_argv0_path(argv[0]);
	set_die_routine(die_webcgi);
647
	set_die_is_recursing_routine(die_webcgi_recursing);
648 649 650 651 652

	if (!method)
		die("No REQUEST_METHOD from server");
	if (!strcmp(method, "HEAD"))
		method = "GET";
653
	dir = getdir();
654 655 656 657 658 659 660 661 662

	for (i = 0; i < ARRAY_SIZE(services); i++) {
		struct service_cmd *c = &services[i];
		regex_t re;
		regmatch_t out[1];

		if (regcomp(&re, c->pattern, REG_EXTENDED))
			die("Bogus regex in service table: %s", c->pattern);
		if (!regexec(&re, dir, 1, out, 0)) {
663
			size_t n;
664 665 666

			if (strcmp(method, c->method)) {
				const char *proto = getenv("SERVER_PROTOCOL");
667
				if (proto && !strcmp(proto, "HTTP/1.1")) {
668
					http_status(405, "Method Not Allowed");
669 670 671
					hdr_str("Allow", !strcmp(c->method, "GET") ?
						"GET, HEAD" : c->method);
				} else
672 673 674 675 676 677 678
					http_status(400, "Bad Request");
				hdr_nocache();
				end_headers();
				return 0;
			}

			cmd = c;
679
			n = out[0].rm_eo - out[0].rm_so;
680
			cmd_arg = xmemdupz(dir + out[0].rm_so + 1, n - 1);
681 682 683 684 685 686 687 688 689 690 691 692
			dir[out[0].rm_so] = 0;
			break;
		}
		regfree(&re);
	}

	if (!cmd)
		not_found("Request not supported: '%s'", dir);

	setup_path();
	if (!enter_repo(dir, 0))
		not_found("Not a git repository: '%s'", dir);
693 694 695
	if (!getenv("GIT_HTTP_EXPORT_ALL") &&
	    access("git-daemon-export-ok", F_OK) )
		not_found("Repository not exported: '%s'", dir);
696

697
	http_config();
698 699 700
	max_request_buffer = git_env_ulong("GIT_HTTP_MAX_REQUEST_BUFFER",
					   max_request_buffer);

701 702 703
	cmd->imp(cmd_arg);
	return 0;
}