daemon.c 30.8 KB
Newer Older
1
#include "cache.h"
2
#include "pkt-line.h"
3
#include "exec_cmd.h"
4 5
#include "run-command.h"
#include "strbuf.h"
6
#include "string-list.h"
P
Petr Baudis 已提交
7

8 9 10 11
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 256
#endif

12 13 14 15
#ifdef NO_INITGROUPS
#define initgroups(x, y) (0) /* nothing */
#endif

16
static int log_syslog;
P
Petr Baudis 已提交
17
static int verbose;
18
static int reuseaddr;
19
static int informative_errors;
P
Petr Baudis 已提交
20

21
static const char daemon_usage[] =
S
Stephan Beyer 已提交
22
"git daemon [--verbose] [--syslog] [--export-all]\n"
23 24 25 26
"           [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
"           [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
"           [--user-path | --user-path=<path>]\n"
"           [--interpolated-path=<path>]\n"
27
"           [--reuseaddr] [--pid-file=<file>]\n"
28
"           [--(enable|disable|allow-override|forbid-override)=<service>]\n"
J
Junio C Hamano 已提交
29
"           [--access-hook=<path>]\n"
30
"           [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
31
"                      [--detach] [--user=<user> [--group=<group>]]\n"
32
"           [<directory>...]";
33 34

/* List of acceptable pathname prefixes */
35 36
static char **ok_paths;
static int strict_paths;
37 38

/* If this is set, git-daemon-export-ok is not required */
39
static int export_all_trees;
P
Petr Baudis 已提交
40

P
Petr Baudis 已提交
41
/* Take all paths relative to this one if non-NULL */
42
static char *base_path;
43
static char *interpolated_path;
J
Jens Axboe 已提交
44
static int base_path_relaxed;
45 46 47

/* Flag indicating client sent extra args. */
static int saw_extended_args;
P
Petr Baudis 已提交
48

49 50 51 52
/* If defined, ~user notation is allowed and the string is inserted
 * after ~user/.  E.g. a request to git://host/~alice/frotz would
 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
 */
53
static const char *user_path;
54

55
/* Timeout, and initial timeout */
56 57
static unsigned int timeout;
static unsigned int init_timeout;
P
Petr Baudis 已提交
58

59 60 61 62
static char *hostname;
static char *canon_hostname;
static char *ip_address;
static char *tcp_port;
63

64
static void logreport(int priority, const char *err, va_list params)
P
Petr Baudis 已提交
65
{
66
	if (log_syslog) {
67 68
		char buf[1024];
		vsnprintf(buf, sizeof(buf), err, params);
69
		syslog(priority, "%s", buf);
J
Junio C Hamano 已提交
70 71
	} else {
		/*
72
		 * Since stderr is set to buffered mode, the
73
		 * logging of different processes will not overlap
74
		 * unless they overflow the (rather big) buffers.
75
		 */
76
		fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
77 78
		vfprintf(stderr, err, params);
		fputc('\n', stderr);
79
		fflush(stderr);
80
	}
P
Petr Baudis 已提交
81 82
}

83
__attribute__((format (printf, 1, 2)))
84
static void logerror(const char *err, ...)
P
Petr Baudis 已提交
85 86 87
{
	va_list params;
	va_start(params, err);
88
	logreport(LOG_ERR, err, params);
P
Petr Baudis 已提交
89 90 91
	va_end(params);
}

92
__attribute__((format (printf, 1, 2)))
93
static void loginfo(const char *err, ...)
P
Petr Baudis 已提交
94 95 96 97 98
{
	va_list params;
	if (!verbose)
		return;
	va_start(params, err);
99
	logreport(LOG_INFO, err, params);
P
Petr Baudis 已提交
100 101
	va_end(params);
}
102

103 104 105 106 107 108
static void NORETURN daemon_die(const char *err, va_list params)
{
	logreport(LOG_ERR, err, params);
	exit(1);
}

E
Erik Faye-Lund 已提交
109
static const char *path_ok(char *directory)
110
{
111
	static char rpath[PATH_MAX];
112
	static char interp_path[PATH_MAX];
E
Erik Faye-Lund 已提交
113
	const char *path;
114 115
	char *dir;

116
	dir = directory;
117

118
	if (daemon_avoid_alias(dir)) {
119 120 121 122
		logerror("'%s': aliased", dir);
		return NULL;
	}

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
	if (*dir == '~') {
		if (!user_path) {
			logerror("'%s': User-path not allowed", dir);
			return NULL;
		}
		if (*user_path) {
			/* Got either "~alice" or "~alice/foo";
			 * rewrite them to "~alice/%s" or
			 * "~alice/%s/foo".
			 */
			int namlen, restlen = strlen(dir);
			char *slash = strchr(dir, '/');
			if (!slash)
				slash = dir + restlen;
			namlen = slash - dir;
			restlen -= namlen;
			loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
			snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
				 namlen, dir, user_path, restlen, slash);
			dir = rpath;
		}
	}
145
	else if (interpolated_path && saw_extended_args) {
146
		struct strbuf expanded_path = STRBUF_INIT;
147 148 149 150 151 152 153 154
		struct strbuf_expand_dict_entry dict[6];

		dict[0].placeholder = "H"; dict[0].value = hostname;
		dict[1].placeholder = "CH"; dict[1].value = canon_hostname;
		dict[2].placeholder = "IP"; dict[2].value = ip_address;
		dict[3].placeholder = "P"; dict[3].value = tcp_port;
		dict[4].placeholder = "D"; dict[4].value = directory;
		dict[5].placeholder = NULL; dict[5].value = NULL;
155 156 157 158 159 160
		if (*dir != '/') {
			/* Allow only absolute */
			logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
			return NULL;
		}

161 162 163 164
		strbuf_expand(&expanded_path, interpolated_path,
				strbuf_expand_dict_cb, &dict);
		strlcpy(interp_path, expanded_path.buf, PATH_MAX);
		strbuf_release(&expanded_path);
165 166 167 168
		loginfo("Interpolated dir '%s'", interp_path);

		dir = interp_path;
	}
169 170 171
	else if (base_path) {
		if (*dir != '/') {
			/* Allow only absolute */
172
			logerror("'%s': Non-absolute path denied (base-path active)", dir);
P
Petr Baudis 已提交
173 174
			return NULL;
		}
175 176
		snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
		dir = rpath;
P
Petr Baudis 已提交
177 178
	}

179 180
	path = enter_repo(dir, strict_paths);
	if (!path && base_path && base_path_relaxed) {
J
Jens Axboe 已提交
181 182 183 184
		/*
		 * if we fail and base_path_relaxed is enabled, try without
		 * prefixing the base path
		 */
185 186 187
		dir = directory;
		path = enter_repo(dir, strict_paths);
	}
188

189
	if (!path) {
190
		logerror("'%s' does not appear to be a git repository", dir);
191
		return NULL;
192 193 194
	}

	if ( ok_paths && *ok_paths ) {
J
Junio C Hamano 已提交
195
		char **pp;
196
		int pathlen = strlen(path);
197

J
Junio C Hamano 已提交
198
		/* The validation is done on the paths after enter_repo
J
Junio C Hamano 已提交
199
		 * appends optional {.git,.git/.git} and friends, but
200 201 202 203
		 * it does not use getcwd().  So if your /pub is
		 * a symlink to /mnt/pub, you can whitelist /pub and
		 * do not have to say /mnt/pub.
		 * Do not say /pub/.
J
Junio C Hamano 已提交
204
		 */
205 206
		for ( pp = ok_paths ; *pp ; pp++ ) {
			int len = strlen(*pp);
J
Junio C Hamano 已提交
207 208 209 210 211
			if (len <= pathlen &&
			    !memcmp(*pp, path, len) &&
			    (path[len] == '\0' ||
			     (!strict_paths && path[len] == '/')))
				return path;
212
		}
213 214 215 216 217
	}
	else {
		/* be backwards compatible */
		if (!strict_paths)
			return path;
218 219
	}

220 221
	logerror("'%s': not in whitelist", path);
	return NULL;		/* Fallthrough. Deny by default */
222
}
223

224 225 226 227 228 229 230 231 232 233 234 235
typedef int (*daemon_service_fn)(void);
struct daemon_service {
	const char *name;
	const char *config_name;
	daemon_service_fn fn;
	int enabled;
	int overridable;
};

static struct daemon_service *service_looking_at;
static int service_enabled;

236
static int git_daemon_config(const char *var, const char *value, void *cb)
237
{
238
	if (!prefixcmp(var, "daemon.") &&
239 240 241 242 243 244 245 246 247
	    !strcmp(var + 7, service_looking_at->config_name)) {
		service_enabled = git_config_bool(var, value);
		return 0;
	}

	/* we are not interested in parsing any other configuration here */
	return 0;
}

248 249 250 251 252 253 254 255
static int daemon_error(const char *dir, const char *msg)
{
	if (!informative_errors)
		msg = "access denied or repository not exported";
	packet_write(1, "ERR %s: %s", msg, dir);
	return -1;
}

J
Junio C Hamano 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 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 316 317 318 319 320
static char *access_hook;

static int run_access_hook(struct daemon_service *service, const char *dir, const char *path)
{
	struct child_process child;
	struct strbuf buf = STRBUF_INIT;
	const char *argv[8];
	const char **arg = argv;
	char *eol;
	int seen_errors = 0;

#define STRARG(x) ((x) ? (x) : "")
	*arg++ = access_hook;
	*arg++ = service->name;
	*arg++ = path;
	*arg++ = STRARG(hostname);
	*arg++ = STRARG(canon_hostname);
	*arg++ = STRARG(ip_address);
	*arg++ = STRARG(tcp_port);
	*arg = NULL;
#undef STRARG

	memset(&child, 0, sizeof(child));
	child.use_shell = 1;
	child.argv = argv;
	child.no_stdin = 1;
	child.no_stderr = 1;
	child.out = -1;
	if (start_command(&child)) {
		logerror("daemon access hook '%s' failed to start",
			 access_hook);
		goto error_return;
	}
	if (strbuf_read(&buf, child.out, 0) < 0) {
		logerror("failed to read from pipe to daemon access hook '%s'",
			 access_hook);
		strbuf_reset(&buf);
		seen_errors = 1;
	}
	if (close(child.out) < 0) {
		logerror("failed to close pipe to daemon access hook '%s'",
			 access_hook);
		seen_errors = 1;
	}
	if (finish_command(&child))
		seen_errors = 1;

	if (!seen_errors) {
		strbuf_release(&buf);
		return 0;
	}

error_return:
	strbuf_ltrim(&buf);
	if (!buf.len)
		strbuf_addstr(&buf, "service rejected");
	eol = strchr(buf.buf, '\n');
	if (eol)
		*eol = '\0';
	errno = EACCES;
	daemon_error(dir, buf.buf);
	strbuf_release(&buf);
	return -1;
}

321
static int run_service(char *dir, struct daemon_service *service)
322
{
323
	const char *path;
324 325
	int enabled = service->enabled;

326
	loginfo("Request %s for '%s'", service->name, dir);
327

328 329 330
	if (!enabled && !service->overridable) {
		logerror("'%s': service not enabled.", service->name);
		errno = EACCES;
331
		return daemon_error(dir, "service not enabled");
332
	}
333

334
	if (!(path = path_ok(dir)))
335
		return daemon_error(dir, "no such repository");
H
H. Peter Anvin 已提交
336

337 338 339
	/*
	 * Security on the cheap.
	 *
340
	 * We want a readable HEAD, usable "objects" directory, and
341 342
	 * a "git-daemon-export-ok" flag that says that the other side
	 * is ok with us doing this.
343 344 345
	 *
	 * path_ok() uses enter_repo() and does whitelist checking.
	 * We only need to make sure the repository is exported.
346
	 */
347

348
	if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
349
		logerror("'%s': repository not exported.", path);
350
		errno = EACCES;
351
		return daemon_error(dir, "repository not exported");
352 353
	}

354 355 356
	if (service->overridable) {
		service_looking_at = service;
		service_enabled = -1;
357
		git_config(git_daemon_config, NULL);
358 359 360 361 362 363 364
		if (0 <= service_enabled)
			enabled = service_enabled;
	}
	if (!enabled) {
		logerror("'%s': service not enabled for '%s'",
			 service->name, path);
		errno = EACCES;
365
		return daemon_error(dir, "service not enabled");
366 367
	}

J
Junio C Hamano 已提交
368 369 370 371 372 373 374
	/*
	 * Optionally, a hook can choose to deny access to the
	 * repository depending on the phase of the moon.
	 */
	if (access_hook && run_access_hook(service, dir, path))
		return -1;

375 376 377 378 379 380
	/*
	 * We'll ignore SIGTERM from now on, we have a
	 * good client.
	 */
	signal(SIGTERM, SIG_IGN);

381 382 383
	return service->fn();
}

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
static void copy_to_log(int fd)
{
	struct strbuf line = STRBUF_INIT;
	FILE *fp;

	fp = fdopen(fd, "r");
	if (fp == NULL) {
		logerror("fdopen of error channel failed");
		close(fd);
		return;
	}

	while (strbuf_getline(&line, fp, '\n') != EOF) {
		logerror("%s", line.buf);
		strbuf_setlen(&line, 0);
	}

	strbuf_release(&line);
	fclose(fp);
}

static int run_service_command(const char **argv)
{
	struct child_process cld;

	memset(&cld, 0, sizeof(cld));
	cld.argv = argv;
	cld.git_cmd = 1;
	cld.err = -1;
	if (start_command(&cld))
		return -1;

	close(0);
	close(1);

	copy_to_log(cld.err);

	return finish_command(&cld);
}

424 425 426 427
static int upload_pack(void)
{
	/* Timeout as string */
	char timeout_buf[64];
428 429 430
	const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };

	argv[2] = timeout_buf;
431

432
	snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
433
	return run_service_command(argv);
434 435
}

F
Franck Bui-Huu 已提交
436 437
static int upload_archive(void)
{
438 439
	static const char *argv[] = { "upload-archive", ".", NULL };
	return run_service_command(argv);
F
Franck Bui-Huu 已提交
440 441
}

L
Linus Torvalds 已提交
442 443
static int receive_pack(void)
{
444 445
	static const char *argv[] = { "receive-pack", ".", NULL };
	return run_service_command(argv);
L
Linus Torvalds 已提交
446 447
}

448
static struct daemon_service daemon_service[] = {
F
Franck Bui-Huu 已提交
449
	{ "upload-archive", "uploadarch", upload_archive, 0, 1 },
450
	{ "upload-pack", "uploadpack", upload_pack, 1, 1 },
L
Linus Torvalds 已提交
451
	{ "receive-pack", "receivepack", receive_pack, 0, 1 },
452 453
};

454 455
static void enable_service(const char *name, int ena)
{
456 457 458 459 460 461 462 463 464 465
	int i;
	for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
		if (!strcmp(daemon_service[i].name, name)) {
			daemon_service[i].enabled = ena;
			return;
		}
	}
	die("No such service %s", name);
}

466 467
static void make_service_overridable(const char *name, int ena)
{
468 469 470 471 472 473 474 475 476 477
	int i;
	for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
		if (!strcmp(daemon_service[i].name, name)) {
			daemon_service[i].overridable = ena;
			return;
		}
	}
	die("No such service %s", name);
}

478 479 480 481 482 483 484 485
static char *xstrdup_tolower(const char *str)
{
	char *p, *dup = xstrdup(str);
	for (p = dup; *p; p++)
		*p = tolower(*p);
	return dup;
}

486 487 488 489 490 491 492 493
static void parse_host_and_port(char *hostport, char **host,
	char **port)
{
	if (*hostport == '[') {
		char *end;

		end = strchr(hostport, ']');
		if (!end)
494
			die("Invalid request ('[' without ']')");
495 496 497 498 499 500 501 502 503 504 505 506
		*end = '\0';
		*host = hostport + 1;
		if (!end[1])
			*port = NULL;
		else if (end[1] == ':')
			*port = end + 2;
		else
			die("Garbage after end of host part");
	} else {
		*host = hostport;
		*port = strrchr(hostport, ':');
		if (*port) {
507
			**port = '\0';
508 509 510 511 512
			++*port;
		}
	}
}

513
/*
514
 * Read the host as supplied by the client connection.
515
 */
516
static void parse_host_arg(char *extra_args, int buflen)
517 518 519 520 521
{
	char *val;
	int vallen;
	char *end = extra_args + buflen;

522
	if (extra_args < end && *extra_args) {
523 524 525 526 527
		saw_extended_args = 1;
		if (strncasecmp("host=", extra_args, 5) == 0) {
			val = extra_args + 5;
			vallen = strlen(val) + 1;
			if (*val) {
528
				/* Split <host>:<port> at colon. */
529 530 531
				char *host;
				char *port;
				parse_host_and_port(val, &host, &port);
532
				if (port) {
533 534
					free(tcp_port);
					tcp_port = xstrdup(port);
535
				}
536
				free(hostname);
537
				hostname = xstrdup_tolower(host);
538
			}
539

540 541 542
			/* On to the next one */
			extra_args = val + vallen;
		}
543 544
		if (extra_args < end && *extra_args)
			die("Invalid request");
545
	}
546 547 548 549

	/*
	 * Locate canonical hostname and its IP address.
	 */
550
	if (hostname) {
551 552
#ifndef NO_IPV6
		struct addrinfo hints;
B
Benjamin Kramer 已提交
553
		struct addrinfo *ai;
554 555 556 557 558 559
		int gai;
		static char addrbuf[HOST_NAME_MAX + 1];

		memset(&hints, 0, sizeof(hints));
		hints.ai_flags = AI_CANONNAME;

560
		gai = getaddrinfo(hostname, NULL, &hints, &ai);
561
		if (!gai) {
B
Benjamin Kramer 已提交
562 563 564 565 566 567 568 569 570 571 572 573
			struct sockaddr_in *sin_addr = (void *)ai->ai_addr;

			inet_ntop(AF_INET, &sin_addr->sin_addr,
				  addrbuf, sizeof(addrbuf));
			free(ip_address);
			ip_address = xstrdup(addrbuf);

			free(canon_hostname);
			canon_hostname = xstrdup(ai->ai_canonname ?
						 ai->ai_canonname : ip_address);

			freeaddrinfo(ai);
574 575 576 577 578 579 580
		}
#else
		struct hostent *hent;
		struct sockaddr_in sa;
		char **ap;
		static char addrbuf[HOST_NAME_MAX + 1];

581
		hent = gethostbyname(hostname);
582 583 584 585 586 587 588 589 590

		ap = hent->h_addr_list;
		memset(&sa, 0, sizeof sa);
		sa.sin_family = hent->h_addrtype;
		sa.sin_port = htons(0);
		memcpy(&sa.sin_addr, *ap, hent->h_length);

		inet_ntop(hent->h_addrtype, &sa.sin_addr,
			  addrbuf, sizeof(addrbuf));
591

592 593 594 595
		free(canon_hostname);
		canon_hostname = xstrdup(hent->h_name);
		free(ip_address);
		ip_address = xstrdup(addrbuf);
596
#endif
597
	}
598 599 600
}


601
static int execute(void)
602
{
603
	char *line = packet_buffer;
604
	int pktlen, len, i;
605
	char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
606

607 608
	if (addr)
		loginfo("Connection from %s:%s", addr, port);
609

610
	alarm(init_timeout ? init_timeout : timeout);
611
	pktlen = packet_read(0, NULL, NULL, packet_buffer, sizeof(packet_buffer), 0);
612
	alarm(0);
613

614 615 616 617 618
	len = strlen(line);
	if (pktlen != len)
		loginfo("Extended attributes (%d bytes) exist <%.*s>",
			(int) pktlen - len,
			(int) pktlen - len, line + len + 1);
619
	if (len && line[len-1] == '\n') {
620
		line[--len] = 0;
621 622
		pktlen--;
	}
623

624 625 626 627
	free(hostname);
	free(canon_hostname);
	free(ip_address);
	free(tcp_port);
628
	hostname = canon_hostname = ip_address = tcp_port = NULL;
629

630
	if (len != pktlen)
631
		parse_host_arg(line + len + 1, pktlen - len - 1);
632

633 634 635
	for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
		struct daemon_service *s = &(daemon_service[i]);
		int namelen = strlen(s->name);
636
		if (!prefixcmp(line, "git-") &&
637
		    !strncmp(s->name, line + 4, namelen) &&
638
		    line[namelen + 4] == ' ') {
639 640 641 642
			/*
			 * Note: The directory here is probably context sensitive,
			 * and might depend on the actual service being performed.
			 */
643
			return run_service(line + namelen + 5, s);
644
		}
645
	}
646

P
Petr Baudis 已提交
647
	logerror("Protocol error: '%s'", line);
648 649 650
	return -1;
}

651 652 653
static int addrcmp(const struct sockaddr_storage *s1,
    const struct sockaddr_storage *s2)
{
654 655 656 657 658 659
	const struct sockaddr *sa1 = (const struct sockaddr*) s1;
	const struct sockaddr *sa2 = (const struct sockaddr*) s2;

	if (sa1->sa_family != sa2->sa_family)
		return sa1->sa_family - sa2->sa_family;
	if (sa1->sa_family == AF_INET)
660 661 662 663
		return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
		    &((struct sockaddr_in *)s2)->sin_addr,
		    sizeof(struct in_addr));
#ifndef NO_IPV6
664
	if (sa1->sa_family == AF_INET6)
665 666 667 668 669 670 671
		return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
		    &((struct sockaddr_in6 *)s2)->sin6_addr,
		    sizeof(struct in6_addr));
#endif
	return 0;
}

672
static int max_connections = 32;
673

674
static unsigned int live_children;
675

L
Linus Torvalds 已提交
676
static struct child {
677
	struct child *next;
678
	struct child_process cld;
679
	struct sockaddr_storage address;
680
} *firstborn;
681

E
Erik Faye-Lund 已提交
682
static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
683
{
J
Junio C Hamano 已提交
684 685 686 687
	struct child *newborn, **cradle;

	newborn = xcalloc(1, sizeof(*newborn));
	live_children++;
688
	memcpy(&newborn->cld, cld, sizeof(*cld));
J
Junio C Hamano 已提交
689 690
	memcpy(&newborn->address, addr, addrlen);
	for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
691
		if (!addrcmp(&(*cradle)->address, &newborn->address))
J
Junio C Hamano 已提交
692 693 694
			break;
	newborn->next = *cradle;
	*cradle = newborn;
695 696 697 698 699 700
}

/*
 * This gets called if the number of connections grows
 * past "max_connections".
 *
701
 * We kill the newest connection from a duplicate IP.
702
 */
703
static void kill_some_child(void)
704
{
J
Junio C Hamano 已提交
705
	const struct child *blanket, *next;
706

J
Junio C Hamano 已提交
707 708
	if (!(blanket = firstborn))
		return;
709

J
Junio C Hamano 已提交
710
	for (; (next = blanket->next); blanket = next)
711
		if (!addrcmp(&blanket->address, &next->address)) {
712
			kill(blanket->cld.pid, SIGTERM);
J
Junio C Hamano 已提交
713 714
			break;
		}
715 716
}

717
static void check_dead_children(void)
718
{
719 720
	int status;
	pid_t pid;
721

722 723 724 725 726 727 728 729 730 731 732 733 734 735
	struct child **cradle, *blanket;
	for (cradle = &firstborn; (blanket = *cradle);)
		if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
			const char *dead = "";
			if (status)
				dead = " (with error)";
			loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);

			/* remove the child */
			*cradle = blanket->next;
			live_children--;
			free(blanket);
		} else
			cradle = &blanket->next;
736 737
}

738
static char **cld_argv;
E
Erik Faye-Lund 已提交
739
static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
740
{
S
Stephen Boyd 已提交
741
	struct child_process cld = { NULL };
742 743
	char addrbuf[300] = "REMOTE_ADDR=", portbuf[300];
	char *env[] = { addrbuf, portbuf, NULL };
744

745 746
	if (max_connections && live_children >= max_connections) {
		kill_some_child();
J
Junio C Hamano 已提交
747
		sleep(1);  /* give it some time to die */
748 749 750 751 752 753 754
		check_dead_children();
		if (live_children >= max_connections) {
			close(incoming);
			logerror("Too many children, dropping connection");
			return;
		}
	}
755

756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
	if (addr->sa_family == AF_INET) {
		struct sockaddr_in *sin_addr = (void *) addr;
		inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf + 12,
		    sizeof(addrbuf) - 12);
		snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
		    ntohs(sin_addr->sin_port));
#ifndef NO_IPV6
	} else if (addr && addr->sa_family == AF_INET6) {
		struct sockaddr_in6 *sin6_addr = (void *) addr;

		char *buf = addrbuf + 12;
		*buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
		inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf,
		    sizeof(addrbuf) - 13);
		strcat(buf, "]");

		snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
		    ntohs(sin6_addr->sin6_port));
#endif
	}

	cld.env = (const char **)env;
778 779 780
	cld.argv = (const char **)cld_argv;
	cld.in = incoming;
	cld.out = dup(incoming);
781

782 783 784 785
	if (start_command(&cld))
		logerror("unable to fork");
	else
		add_child(&cld, addr, addrlen);
786 787 788
	close(incoming);
}

789 790
static void child_handler(int signo)
{
J
Junio C Hamano 已提交
791 792
	/*
	 * Otherwise empty handler because systemcalls will get interrupted
793 794 795
	 * upon signal receipt
	 * SysV needs the handler to be rearmed
	 */
796
	signal(SIGCHLD, child_handler);
797 798
}

799 800 801 802 803 804 805 806 807 808
static int set_reuse_addr(int sockfd)
{
	int on = 1;

	if (!reuseaddr)
		return 0;
	return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
			  &on, sizeof(on));
}

809 810 811 812 813 814
struct socketlist {
	int *list;
	size_t nr;
	size_t alloc;
};

815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
{
#ifdef NO_IPV6
	static char ip[INET_ADDRSTRLEN];
#else
	static char ip[INET6_ADDRSTRLEN];
#endif

	switch (family) {
#ifndef NO_IPV6
	case AF_INET6:
		inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
		break;
#endif
	case AF_INET:
		inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
		break;
	default:
		strcpy(ip, "<unknown>");
	}
	return ip;
}

P
Peter Anvin 已提交
838 839
#ifndef NO_IPV6

840
static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
841
{
842
	int socknum = 0;
843 844
	int maxfd = -1;
	char pbuf[NI_MAXSERV];
P
Peter Anvin 已提交
845 846
	struct addrinfo hints, *ai0, *ai;
	int gai;
847
	long flags;
848

849
	sprintf(pbuf, "%d", listen_port);
850 851 852 853 854 855
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	hints.ai_flags = AI_PASSIVE;

856
	gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
857 858 859 860
	if (gai) {
		logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
		return 0;
	}
861 862 863 864 865 866 867 868

	for (ai = ai0; ai; ai = ai->ai_next) {
		int sockfd;

		sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
		if (sockfd < 0)
			continue;
		if (sockfd >= FD_SETSIZE) {
869
			logerror("Socket descriptor too large");
870 871 872 873 874 875 876 877 878 879 880 881 882
			close(sockfd);
			continue;
		}

#ifdef IPV6_V6ONLY
		if (ai->ai_family == AF_INET6) {
			int on = 1;
			setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
				   &on, sizeof(on));
			/* Note: error is not fatal */
		}
#endif

883
		if (set_reuse_addr(sockfd)) {
884
			logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
885
			close(sockfd);
886
			continue;
887 888
		}

889
		if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
890 891 892
			logerror("Could not bind to %s: %s",
				 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
				 strerror(errno));
893 894 895 896
			close(sockfd);
			continue;	/* not fatal */
		}
		if (listen(sockfd, 5) < 0) {
897 898 899
			logerror("Could not listen to %s: %s",
				 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
				 strerror(errno));
900 901 902 903
			close(sockfd);
			continue;	/* not fatal */
		}

904 905 906 907
		flags = fcntl(sockfd, F_GETFD, 0);
		if (flags >= 0)
			fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);

908 909 910
		ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
		socklist->list[socklist->nr++] = sockfd;
		socknum++;
911 912 913 914 915 916 917

		if (maxfd < sockfd)
			maxfd = sockfd;
	}

	freeaddrinfo(ai0);

P
Peter Anvin 已提交
918 919 920 921 922
	return socknum;
}

#else /* NO_IPV6 */

923
static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
P
Peter Anvin 已提交
924 925 926
{
	struct sockaddr_in sin;
	int sockfd;
927
	long flags;
P
Peter Anvin 已提交
928

929 930 931 932 933 934 935 936 937 938 939 940
	memset(&sin, 0, sizeof sin);
	sin.sin_family = AF_INET;
	sin.sin_port = htons(listen_port);

	if (listen_addr) {
		/* Well, host better be an IP address here. */
		if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
			return 0;
	} else {
		sin.sin_addr.s_addr = htonl(INADDR_ANY);
	}

P
Peter Anvin 已提交
941 942 943 944
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0)
		return 0;

945
	if (set_reuse_addr(sockfd)) {
946
		logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
947 948 949 950
		close(sockfd);
		return 0;
	}

P
Peter Anvin 已提交
951
	if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
952 953 954
		logerror("Could not listen to %s: %s",
			 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
			 strerror(errno));
P
Peter Anvin 已提交
955 956 957
		close(sockfd);
		return 0;
	}
958

959
	if (listen(sockfd, 5) < 0) {
960 961 962
		logerror("Could not listen to %s: %s",
			 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
			 strerror(errno));
963 964 965 966
		close(sockfd);
		return 0;
	}

967 968 969 970
	flags = fcntl(sockfd, F_GETFD, 0);
	if (flags >= 0)
		fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);

971 972
	ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
	socklist->list[socklist->nr++] = sockfd;
973
	return 1;
P
Peter Anvin 已提交
974 975 976 977
}

#endif

978
static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
979
{
980 981 982 983 984 985 986 987 988 989 990 991 992
	if (!listen_addr->nr)
		setup_named_sock(NULL, listen_port, socklist);
	else {
		int i, socknum;
		for (i = 0; i < listen_addr->nr; i++) {
			socknum = setup_named_sock(listen_addr->items[i].string,
						   listen_port, socklist);

			if (socknum == 0)
				logerror("unable to allocate any listen sockets for host %s on port %u",
					 listen_addr->items[i].string, listen_port);
		}
	}
993 994 995
}

static int service_loop(struct socketlist *socklist)
P
Peter Anvin 已提交
996 997 998 999
{
	struct pollfd *pfd;
	int i;

1000
	pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
P
Peter Anvin 已提交
1001

1002 1003
	for (i = 0; i < socklist->nr; i++) {
		pfd[i].fd = socklist->list[i];
P
Peter Anvin 已提交
1004 1005
		pfd[i].events = POLLIN;
	}
1006 1007

	signal(SIGCHLD, child_handler);
1008 1009

	for (;;) {
1010
		int i;
P
Peter Anvin 已提交
1011

1012 1013
		check_dead_children();

1014
		if (poll(pfd, socklist->nr, -1) < 0) {
1015
			if (errno != EINTR) {
1016
				logerror("Poll failed, resuming: %s",
1017 1018 1019
				      strerror(errno));
				sleep(1);
			}
1020 1021 1022
			continue;
		}

1023
		for (i = 0; i < socklist->nr; i++) {
P
Peter Anvin 已提交
1024
			if (pfd[i].revents & POLLIN) {
1025 1026 1027 1028 1029 1030 1031
				union {
					struct sockaddr sa;
					struct sockaddr_in sai;
#ifndef NO_IPV6
					struct sockaddr_in6 sai6;
#endif
				} ss;
E
Erik Faye-Lund 已提交
1032
				socklen_t sslen = sizeof(ss);
1033
				int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1034 1035 1036 1037 1038 1039 1040
				if (incoming < 0) {
					switch (errno) {
					case EAGAIN:
					case EINTR:
					case ECONNABORTED:
						continue;
					default:
1041
						die_errno("accept returned");
1042 1043
					}
				}
1044
				handle(incoming, &ss.sa, sslen);
1045 1046 1047 1048 1049
			}
		}
	}
}

1050 1051 1052 1053 1054 1055 1056
/* if any standard file descriptor is missing open it to /dev/null */
static void sanitize_stdfds(void)
{
	int fd = open("/dev/null", O_RDWR, 0);
	while (fd != -1 && fd < 2)
		fd = dup(fd);
	if (fd == -1)
1057
		die_errno("open /dev/null or dup failed");
1058 1059 1060 1061
	if (fd > 2)
		close(fd);
}

1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
#ifdef NO_POSIX_GOODIES

struct credentials;

static void drop_privileges(struct credentials *cred)
{
	/* nothing */
}

static void daemonize(void)
{
	die("--detach not supported on this platform");
}

static struct credentials *prepare_credentials(const char *user_name,
    const char *group_name)
{
	die("--user not supported on this platform");
}

#else

struct credentials {
	struct passwd *pass;
	gid_t gid;
};

static void drop_privileges(struct credentials *cred)
{
	if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
	    setgid (cred->gid) || setuid(cred->pass->pw_uid)))
		die("cannot drop privileges");
}

static struct credentials *prepare_credentials(const char *user_name,
    const char *group_name)
{
	static struct credentials c;

	c.pass = getpwnam(user_name);
	if (!c.pass)
		die("user not found - %s", user_name);

	if (!group_name)
		c.gid = c.pass->pw_gid;
	else {
		struct group *group = getgrnam(group_name);
		if (!group)
			die("group not found - %s", group_name);

		c.gid = group->gr_gid;
	}

	return &c;
}

1118 1119 1120 1121 1122 1123
static void daemonize(void)
{
	switch (fork()) {
		case 0:
			break;
		case -1:
1124
			die_errno("fork failed");
1125 1126 1127 1128
		default:
			exit(0);
	}
	if (setsid() == -1)
1129
		die_errno("setsid failed");
1130 1131 1132 1133 1134
	close(0);
	close(1);
	close(2);
	sanitize_stdfds();
}
1135
#endif
1136

1137 1138 1139 1140
static void store_pid(const char *path)
{
	FILE *f = fopen(path, "w");
	if (!f)
1141
		die_errno("cannot open pid file '%s'", path);
1142
	if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
1143
		die_errno("failed to write pid file '%s'", path);
1144 1145
}

1146 1147
static int serve(struct string_list *listen_addr, int listen_port,
    struct credentials *cred)
P
Peter Anvin 已提交
1148
{
1149
	struct socketlist socklist = { NULL, 0, 0 };
J
Junio C Hamano 已提交
1150

1151 1152
	socksetup(listen_addr, listen_port, &socklist);
	if (socklist.nr == 0)
1153 1154
		die("unable to allocate any listen sockets on port %u",
		    listen_port);
J
Junio C Hamano 已提交
1155

1156
	drop_privileges(cred);
1157

1158 1159
	loginfo("Ready to rumble");

1160
	return service_loop(&socklist);
J
Junio C Hamano 已提交
1161
}
P
Peter Anvin 已提交
1162

1163 1164
int main(int argc, char **argv)
{
1165
	int listen_port = 0;
1166
	struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1167
	int serve_mode = 0, inetd_mode = 0;
1168
	const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1169
	int detach = 0;
1170
	struct credentials *cred = NULL;
1171 1172
	int i;

1173 1174
	git_setup_gettext();

1175 1176
	git_extract_argv0_path(argv[0]);

1177 1178 1179
	for (i = 1; i < argc; i++) {
		char *arg = argv[i];

1180
		if (!prefixcmp(arg, "--listen=")) {
1181
			string_list_append(&listen_addr, xstrdup_tolower(arg + 9));
1182
			continue;
1183
		}
1184
		if (!prefixcmp(arg, "--port=")) {
1185 1186 1187 1188
			char *end;
			unsigned long n;
			n = strtoul(arg+7, &end, 0);
			if (arg[7] && !*end) {
1189
				listen_port = n;
1190 1191 1192
				continue;
			}
		}
1193 1194 1195 1196
		if (!strcmp(arg, "--serve")) {
			serve_mode = 1;
			continue;
		}
1197 1198
		if (!strcmp(arg, "--inetd")) {
			inetd_mode = 1;
A
Andreas Ericsson 已提交
1199
			log_syslog = 1;
1200 1201
			continue;
		}
P
Petr Baudis 已提交
1202 1203 1204 1205
		if (!strcmp(arg, "--verbose")) {
			verbose = 1;
			continue;
		}
1206 1207 1208 1209
		if (!strcmp(arg, "--syslog")) {
			log_syslog = 1;
			continue;
		}
1210 1211 1212 1213
		if (!strcmp(arg, "--export-all")) {
			export_all_trees = 1;
			continue;
		}
J
Junio C Hamano 已提交
1214 1215 1216 1217
		if (!prefixcmp(arg, "--access-hook=")) {
			access_hook = arg + 14;
			continue;
		}
1218
		if (!prefixcmp(arg, "--timeout=")) {
1219
			timeout = atoi(arg+10);
A
Andreas Ericsson 已提交
1220
			continue;
1221
		}
1222
		if (!prefixcmp(arg, "--init-timeout=")) {
1223
			init_timeout = atoi(arg+15);
A
Andreas Ericsson 已提交
1224
			continue;
1225
		}
1226 1227 1228 1229 1230 1231
		if (!prefixcmp(arg, "--max-connections=")) {
			max_connections = atoi(arg+18);
			if (max_connections < 0)
				max_connections = 0;	        /* unlimited */
			continue;
		}
1232 1233 1234 1235
		if (!strcmp(arg, "--strict-paths")) {
			strict_paths = 1;
			continue;
		}
1236
		if (!prefixcmp(arg, "--base-path=")) {
P
Petr Baudis 已提交
1237 1238 1239
			base_path = arg+12;
			continue;
		}
J
Jens Axboe 已提交
1240 1241 1242 1243
		if (!strcmp(arg, "--base-path-relaxed")) {
			base_path_relaxed = 1;
			continue;
		}
1244
		if (!prefixcmp(arg, "--interpolated-path=")) {
1245 1246 1247
			interpolated_path = arg+20;
			continue;
		}
1248 1249 1250 1251
		if (!strcmp(arg, "--reuseaddr")) {
			reuseaddr = 1;
			continue;
		}
1252 1253 1254 1255
		if (!strcmp(arg, "--user-path")) {
			user_path = "";
			continue;
		}
1256
		if (!prefixcmp(arg, "--user-path=")) {
1257 1258 1259
			user_path = arg + 12;
			continue;
		}
1260
		if (!prefixcmp(arg, "--pid-file=")) {
1261 1262 1263
			pid_file = arg + 11;
			continue;
		}
1264 1265 1266 1267 1268
		if (!strcmp(arg, "--detach")) {
			detach = 1;
			log_syslog = 1;
			continue;
		}
1269
		if (!prefixcmp(arg, "--user=")) {
1270 1271 1272
			user_name = arg + 7;
			continue;
		}
1273
		if (!prefixcmp(arg, "--group=")) {
1274 1275 1276
			group_name = arg + 8;
			continue;
		}
1277
		if (!prefixcmp(arg, "--enable=")) {
1278 1279 1280
			enable_service(arg + 9, 1);
			continue;
		}
1281
		if (!prefixcmp(arg, "--disable=")) {
1282 1283 1284
			enable_service(arg + 10, 0);
			continue;
		}
1285
		if (!prefixcmp(arg, "--allow-override=")) {
J
Junio C Hamano 已提交
1286
			make_service_overridable(arg + 17, 1);
1287 1288
			continue;
		}
1289
		if (!prefixcmp(arg, "--forbid-override=")) {
J
Junio C Hamano 已提交
1290
			make_service_overridable(arg + 18, 0);
1291 1292
			continue;
		}
1293 1294 1295 1296 1297 1298 1299 1300
		if (!prefixcmp(arg, "--informative-errors")) {
			informative_errors = 1;
			continue;
		}
		if (!prefixcmp(arg, "--no-informative-errors")) {
			informative_errors = 0;
			continue;
		}
1301 1302 1303 1304 1305 1306 1307
		if (!strcmp(arg, "--")) {
			ok_paths = &argv[i+1];
			break;
		} else if (arg[0] != '-') {
			ok_paths = &argv[i];
			break;
		}
1308

1309 1310 1311
		usage(daemon_usage);
	}

1312
	if (log_syslog) {
1313
		openlog("git-daemon", LOG_PID, LOG_DAEMON);
1314
		set_die_routine(daemon_die);
J
Junio C Hamano 已提交
1315
	} else
J
Junio C Hamano 已提交
1316
		/* avoid splitting a message in the middle */
1317
		setvbuf(stderr, NULL, _IOFBF, 4096);
1318

1319 1320
	if (inetd_mode && (detach || group_name || user_name))
		die("--detach, --user and --group are incompatible with --inetd");
1321

1322
	if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1323 1324 1325 1326
		die("--listen= and --port= are incompatible with --inetd");
	else if (listen_port == 0)
		listen_port = DEFAULT_GIT_PORT;

1327 1328 1329
	if (group_name && !user_name)
		die("--group supplied without --user");

1330 1331
	if (user_name)
		cred = prepare_credentials(user_name, group_name);
1332

1333 1334 1335
	if (strict_paths && (!ok_paths || !*ok_paths))
		die("option --strict-paths requires a whitelist");

1336 1337 1338
	if (base_path && !is_directory(base_path))
		die("base-path '%s' does not exist or is not a directory",
		    base_path);
1339

1340
	if (inetd_mode) {
1341 1342 1343 1344
		if (!freopen("/dev/null", "w", stderr))
			die_errno("failed to redirect stderr to /dev/null");
	}

1345 1346
	if (inetd_mode || serve_mode)
		return execute();
1347

1348
	if (detach)
1349 1350 1351
		daemonize();
	else
		sanitize_stdfds();
1352

1353 1354 1355
	if (pid_file)
		store_pid(pid_file);

1356 1357
	/* prepare argv for serving-processes */
	cld_argv = xmalloc(sizeof (char *) * (argc + 2));
1358 1359 1360 1361
	cld_argv[0] = argv[0];	/* git-daemon */
	cld_argv[1] = "--serve";
	for (i = 1; i < argc; ++i)
		cld_argv[i+1] = argv[i];
1362 1363
	cld_argv[argc+1] = NULL;

1364
	return serve(&listen_addr, listen_port, cred);
1365
}