1 #include "cache.h"
2 #include "config.h"
3 #include "pkt-line.h"
4 #include "run-command.h"
5 #include "strbuf.h"
6 #include "string-list.h"
7 
8 #ifdef NO_INITGROUPS
9 #define initgroups(x, y) (0) /* nothing */
10 #endif
11 
12 static enum log_destination {
13 	LOG_DESTINATION_UNSET = -1,
14 	LOG_DESTINATION_NONE = 0,
15 	LOG_DESTINATION_STDERR = 1,
16 	LOG_DESTINATION_SYSLOG = 2,
17 } log_destination = LOG_DESTINATION_UNSET;
18 static int verbose;
19 static int reuseaddr;
20 static int informative_errors;
21 
22 static const char daemon_usage[] =
23 "git daemon [--verbose] [--syslog] [--export-all]\n"
24 "           [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
25 "           [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
26 "           [--user-path | --user-path=<path>]\n"
27 "           [--interpolated-path=<path>]\n"
28 "           [--reuseaddr] [--pid-file=<file>]\n"
29 "           [--(enable|disable|allow-override|forbid-override)=<service>]\n"
30 "           [--access-hook=<path>]\n"
31 "           [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
32 "                      [--detach] [--user=<user> [--group=<group>]]\n"
33 "           [--log-destination=(stderr|syslog|none)]\n"
34 "           [<directory>...]";
35 
36 /* List of acceptable pathname prefixes */
37 static const char **ok_paths;
38 static int strict_paths;
39 
40 /* If this is set, git-daemon-export-ok is not required */
41 static int export_all_trees;
42 
43 /* Take all paths relative to this one if non-NULL */
44 static const char *base_path;
45 static const char *interpolated_path;
46 static int base_path_relaxed;
47 
48 /* If defined, ~user notation is allowed and the string is inserted
49  * after ~user/.  E.g. a request to git://host/~alice/frotz would
50  * go to /home/alice/pub_git/frotz with --user-path=pub_git.
51  */
52 static const char *user_path;
53 
54 /* Timeout, and initial timeout */
55 static unsigned int timeout;
56 static unsigned int init_timeout;
57 
58 struct hostinfo {
59 	struct strbuf hostname;
60 	struct strbuf canon_hostname;
61 	struct strbuf ip_address;
62 	struct strbuf tcp_port;
63 	unsigned int hostname_lookup_done:1;
64 	unsigned int saw_extended_args:1;
65 };
66 #define HOSTINFO_INIT { \
67 	.hostname = STRBUF_INIT, \
68 	.canon_hostname = STRBUF_INIT, \
69 	.ip_address = STRBUF_INIT, \
70 	.tcp_port = STRBUF_INIT, \
71 }
72 
73 static void lookup_hostname(struct hostinfo *hi);
74 
get_canon_hostname(struct hostinfo * hi)75 static const char *get_canon_hostname(struct hostinfo *hi)
76 {
77 	lookup_hostname(hi);
78 	return hi->canon_hostname.buf;
79 }
80 
get_ip_address(struct hostinfo * hi)81 static const char *get_ip_address(struct hostinfo *hi)
82 {
83 	lookup_hostname(hi);
84 	return hi->ip_address.buf;
85 }
86 
logreport(int priority,const char * err,va_list params)87 static void logreport(int priority, const char *err, va_list params)
88 {
89 	switch (log_destination) {
90 	case LOG_DESTINATION_SYSLOG: {
91 		char buf[1024];
92 		vsnprintf(buf, sizeof(buf), err, params);
93 		syslog(priority, "%s", buf);
94 		break;
95 	}
96 	case LOG_DESTINATION_STDERR:
97 		/*
98 		 * Since stderr is set to buffered mode, the
99 		 * logging of different processes will not overlap
100 		 * unless they overflow the (rather big) buffers.
101 		 */
102 		fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
103 		vfprintf(stderr, err, params);
104 		fputc('\n', stderr);
105 		fflush(stderr);
106 		break;
107 	case LOG_DESTINATION_NONE:
108 		break;
109 	case LOG_DESTINATION_UNSET:
110 		BUG("log destination not initialized correctly");
111 	}
112 }
113 
114 __attribute__((format (printf, 1, 2)))
logerror(const char * err,...)115 static void logerror(const char *err, ...)
116 {
117 	va_list params;
118 	va_start(params, err);
119 	logreport(LOG_ERR, err, params);
120 	va_end(params);
121 }
122 
123 __attribute__((format (printf, 1, 2)))
loginfo(const char * err,...)124 static void loginfo(const char *err, ...)
125 {
126 	va_list params;
127 	if (!verbose)
128 		return;
129 	va_start(params, err);
130 	logreport(LOG_INFO, err, params);
131 	va_end(params);
132 }
133 
daemon_die(const char * err,va_list params)134 static void NORETURN daemon_die(const char *err, va_list params)
135 {
136 	logreport(LOG_ERR, err, params);
137 	exit(1);
138 }
139 
140 struct expand_path_context {
141 	const char *directory;
142 	struct hostinfo *hostinfo;
143 };
144 
expand_path(struct strbuf * sb,const char * placeholder,void * ctx)145 static size_t expand_path(struct strbuf *sb, const char *placeholder, void *ctx)
146 {
147 	struct expand_path_context *context = ctx;
148 	struct hostinfo *hi = context->hostinfo;
149 
150 	switch (placeholder[0]) {
151 	case 'H':
152 		strbuf_addbuf(sb, &hi->hostname);
153 		return 1;
154 	case 'C':
155 		if (placeholder[1] == 'H') {
156 			strbuf_addstr(sb, get_canon_hostname(hi));
157 			return 2;
158 		}
159 		break;
160 	case 'I':
161 		if (placeholder[1] == 'P') {
162 			strbuf_addstr(sb, get_ip_address(hi));
163 			return 2;
164 		}
165 		break;
166 	case 'P':
167 		strbuf_addbuf(sb, &hi->tcp_port);
168 		return 1;
169 	case 'D':
170 		strbuf_addstr(sb, context->directory);
171 		return 1;
172 	}
173 	return 0;
174 }
175 
path_ok(const char * directory,struct hostinfo * hi)176 static const char *path_ok(const char *directory, struct hostinfo *hi)
177 {
178 	static char rpath[PATH_MAX];
179 	static char interp_path[PATH_MAX];
180 	size_t rlen;
181 	const char *path;
182 	const char *dir;
183 
184 	dir = directory;
185 
186 	if (daemon_avoid_alias(dir)) {
187 		logerror("'%s': aliased", dir);
188 		return NULL;
189 	}
190 
191 	if (*dir == '~') {
192 		if (!user_path) {
193 			logerror("'%s': User-path not allowed", dir);
194 			return NULL;
195 		}
196 		if (*user_path) {
197 			/* Got either "~alice" or "~alice/foo";
198 			 * rewrite them to "~alice/%s" or
199 			 * "~alice/%s/foo".
200 			 */
201 			int namlen, restlen = strlen(dir);
202 			const char *slash = strchr(dir, '/');
203 			if (!slash)
204 				slash = dir + restlen;
205 			namlen = slash - dir;
206 			restlen -= namlen;
207 			loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
208 			rlen = snprintf(rpath, sizeof(rpath), "%.*s/%s%.*s",
209 					namlen, dir, user_path, restlen, slash);
210 			if (rlen >= sizeof(rpath)) {
211 				logerror("user-path too large: %s", rpath);
212 				return NULL;
213 			}
214 			dir = rpath;
215 		}
216 	}
217 	else if (interpolated_path && hi->saw_extended_args) {
218 		struct strbuf expanded_path = STRBUF_INIT;
219 		struct expand_path_context context;
220 
221 		context.directory = directory;
222 		context.hostinfo = hi;
223 
224 		if (*dir != '/') {
225 			/* Allow only absolute */
226 			logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
227 			return NULL;
228 		}
229 
230 		strbuf_expand(&expanded_path, interpolated_path,
231 			      expand_path, &context);
232 
233 		rlen = strlcpy(interp_path, expanded_path.buf,
234 			       sizeof(interp_path));
235 		if (rlen >= sizeof(interp_path)) {
236 			logerror("interpolated path too large: %s",
237 				 interp_path);
238 			return NULL;
239 		}
240 
241 		strbuf_release(&expanded_path);
242 		loginfo("Interpolated dir '%s'", interp_path);
243 
244 		dir = interp_path;
245 	}
246 	else if (base_path) {
247 		if (*dir != '/') {
248 			/* Allow only absolute */
249 			logerror("'%s': Non-absolute path denied (base-path active)", dir);
250 			return NULL;
251 		}
252 		rlen = snprintf(rpath, sizeof(rpath), "%s%s", base_path, dir);
253 		if (rlen >= sizeof(rpath)) {
254 			logerror("base-path too large: %s", rpath);
255 			return NULL;
256 		}
257 		dir = rpath;
258 	}
259 
260 	path = enter_repo(dir, strict_paths);
261 	if (!path && base_path && base_path_relaxed) {
262 		/*
263 		 * if we fail and base_path_relaxed is enabled, try without
264 		 * prefixing the base path
265 		 */
266 		dir = directory;
267 		path = enter_repo(dir, strict_paths);
268 	}
269 
270 	if (!path) {
271 		logerror("'%s' does not appear to be a git repository", dir);
272 		return NULL;
273 	}
274 
275 	if ( ok_paths && *ok_paths ) {
276 		const char **pp;
277 		int pathlen = strlen(path);
278 
279 		/* The validation is done on the paths after enter_repo
280 		 * appends optional {.git,.git/.git} and friends, but
281 		 * it does not use getcwd().  So if your /pub is
282 		 * a symlink to /mnt/pub, you can whitelist /pub and
283 		 * do not have to say /mnt/pub.
284 		 * Do not say /pub/.
285 		 */
286 		for ( pp = ok_paths ; *pp ; pp++ ) {
287 			int len = strlen(*pp);
288 			if (len <= pathlen &&
289 			    !memcmp(*pp, path, len) &&
290 			    (path[len] == '\0' ||
291 			     (!strict_paths && path[len] == '/')))
292 				return path;
293 		}
294 	}
295 	else {
296 		/* be backwards compatible */
297 		if (!strict_paths)
298 			return path;
299 	}
300 
301 	logerror("'%s': not in whitelist", path);
302 	return NULL;		/* Fallthrough. Deny by default */
303 }
304 
305 typedef int (*daemon_service_fn)(const struct strvec *env);
306 struct daemon_service {
307 	const char *name;
308 	const char *config_name;
309 	daemon_service_fn fn;
310 	int enabled;
311 	int overridable;
312 };
313 
daemon_error(const char * dir,const char * msg)314 static int daemon_error(const char *dir, const char *msg)
315 {
316 	if (!informative_errors)
317 		msg = "access denied or repository not exported";
318 	packet_write_fmt(1, "ERR %s: %s", msg, dir);
319 	return -1;
320 }
321 
322 static const char *access_hook;
323 
run_access_hook(struct daemon_service * service,const char * dir,const char * path,struct hostinfo * hi)324 static int run_access_hook(struct daemon_service *service, const char *dir,
325 			   const char *path, struct hostinfo *hi)
326 {
327 	struct child_process child = CHILD_PROCESS_INIT;
328 	struct strbuf buf = STRBUF_INIT;
329 	const char *argv[8];
330 	const char **arg = argv;
331 	char *eol;
332 	int seen_errors = 0;
333 
334 	*arg++ = access_hook;
335 	*arg++ = service->name;
336 	*arg++ = path;
337 	*arg++ = hi->hostname.buf;
338 	*arg++ = get_canon_hostname(hi);
339 	*arg++ = get_ip_address(hi);
340 	*arg++ = hi->tcp_port.buf;
341 	*arg = NULL;
342 
343 	child.use_shell = 1;
344 	child.argv = argv;
345 	child.no_stdin = 1;
346 	child.no_stderr = 1;
347 	child.out = -1;
348 	if (start_command(&child)) {
349 		logerror("daemon access hook '%s' failed to start",
350 			 access_hook);
351 		goto error_return;
352 	}
353 	if (strbuf_read(&buf, child.out, 0) < 0) {
354 		logerror("failed to read from pipe to daemon access hook '%s'",
355 			 access_hook);
356 		strbuf_reset(&buf);
357 		seen_errors = 1;
358 	}
359 	if (close(child.out) < 0) {
360 		logerror("failed to close pipe to daemon access hook '%s'",
361 			 access_hook);
362 		seen_errors = 1;
363 	}
364 	if (finish_command(&child))
365 		seen_errors = 1;
366 
367 	if (!seen_errors) {
368 		strbuf_release(&buf);
369 		return 0;
370 	}
371 
372 error_return:
373 	strbuf_ltrim(&buf);
374 	if (!buf.len)
375 		strbuf_addstr(&buf, "service rejected");
376 	eol = strchr(buf.buf, '\n');
377 	if (eol)
378 		*eol = '\0';
379 	errno = EACCES;
380 	daemon_error(dir, buf.buf);
381 	strbuf_release(&buf);
382 	return -1;
383 }
384 
run_service(const char * dir,struct daemon_service * service,struct hostinfo * hi,const struct strvec * env)385 static int run_service(const char *dir, struct daemon_service *service,
386 		       struct hostinfo *hi, const struct strvec *env)
387 {
388 	const char *path;
389 	int enabled = service->enabled;
390 	struct strbuf var = STRBUF_INIT;
391 
392 	loginfo("Request %s for '%s'", service->name, dir);
393 
394 	if (!enabled && !service->overridable) {
395 		logerror("'%s': service not enabled.", service->name);
396 		errno = EACCES;
397 		return daemon_error(dir, "service not enabled");
398 	}
399 
400 	if (!(path = path_ok(dir, hi)))
401 		return daemon_error(dir, "no such repository");
402 
403 	/*
404 	 * Security on the cheap.
405 	 *
406 	 * We want a readable HEAD, usable "objects" directory, and
407 	 * a "git-daemon-export-ok" flag that says that the other side
408 	 * is ok with us doing this.
409 	 *
410 	 * path_ok() uses enter_repo() and does whitelist checking.
411 	 * We only need to make sure the repository is exported.
412 	 */
413 
414 	if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
415 		logerror("'%s': repository not exported.", path);
416 		errno = EACCES;
417 		return daemon_error(dir, "repository not exported");
418 	}
419 
420 	if (service->overridable) {
421 		strbuf_addf(&var, "daemon.%s", service->config_name);
422 		git_config_get_bool(var.buf, &enabled);
423 		strbuf_release(&var);
424 	}
425 	if (!enabled) {
426 		logerror("'%s': service not enabled for '%s'",
427 			 service->name, path);
428 		errno = EACCES;
429 		return daemon_error(dir, "service not enabled");
430 	}
431 
432 	/*
433 	 * Optionally, a hook can choose to deny access to the
434 	 * repository depending on the phase of the moon.
435 	 */
436 	if (access_hook && run_access_hook(service, dir, path, hi))
437 		return -1;
438 
439 	/*
440 	 * We'll ignore SIGTERM from now on, we have a
441 	 * good client.
442 	 */
443 	signal(SIGTERM, SIG_IGN);
444 
445 	return service->fn(env);
446 }
447 
copy_to_log(int fd)448 static void copy_to_log(int fd)
449 {
450 	struct strbuf line = STRBUF_INIT;
451 	FILE *fp;
452 
453 	fp = fdopen(fd, "r");
454 	if (fp == NULL) {
455 		logerror("fdopen of error channel failed");
456 		close(fd);
457 		return;
458 	}
459 
460 	while (strbuf_getline_lf(&line, fp) != EOF) {
461 		logerror("%s", line.buf);
462 		strbuf_setlen(&line, 0);
463 	}
464 
465 	strbuf_release(&line);
466 	fclose(fp);
467 }
468 
run_service_command(struct child_process * cld)469 static int run_service_command(struct child_process *cld)
470 {
471 	strvec_push(&cld->args, ".");
472 	cld->git_cmd = 1;
473 	cld->err = -1;
474 	if (start_command(cld))
475 		return -1;
476 
477 	close(0);
478 	close(1);
479 
480 	copy_to_log(cld->err);
481 
482 	return finish_command(cld);
483 }
484 
upload_pack(const struct strvec * env)485 static int upload_pack(const struct strvec *env)
486 {
487 	struct child_process cld = CHILD_PROCESS_INIT;
488 	strvec_pushl(&cld.args, "upload-pack", "--strict", NULL);
489 	strvec_pushf(&cld.args, "--timeout=%u", timeout);
490 
491 	strvec_pushv(&cld.env_array, env->v);
492 
493 	return run_service_command(&cld);
494 }
495 
upload_archive(const struct strvec * env)496 static int upload_archive(const struct strvec *env)
497 {
498 	struct child_process cld = CHILD_PROCESS_INIT;
499 	strvec_push(&cld.args, "upload-archive");
500 
501 	strvec_pushv(&cld.env_array, env->v);
502 
503 	return run_service_command(&cld);
504 }
505 
receive_pack(const struct strvec * env)506 static int receive_pack(const struct strvec *env)
507 {
508 	struct child_process cld = CHILD_PROCESS_INIT;
509 	strvec_push(&cld.args, "receive-pack");
510 
511 	strvec_pushv(&cld.env_array, env->v);
512 
513 	return run_service_command(&cld);
514 }
515 
516 static struct daemon_service daemon_service[] = {
517 	{ "upload-archive", "uploadarch", upload_archive, 0, 1 },
518 	{ "upload-pack", "uploadpack", upload_pack, 1, 1 },
519 	{ "receive-pack", "receivepack", receive_pack, 0, 1 },
520 };
521 
enable_service(const char * name,int ena)522 static void enable_service(const char *name, int ena)
523 {
524 	int i;
525 	for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
526 		if (!strcmp(daemon_service[i].name, name)) {
527 			daemon_service[i].enabled = ena;
528 			return;
529 		}
530 	}
531 	die("No such service %s", name);
532 }
533 
make_service_overridable(const char * name,int ena)534 static void make_service_overridable(const char *name, int ena)
535 {
536 	int i;
537 	for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
538 		if (!strcmp(daemon_service[i].name, name)) {
539 			daemon_service[i].overridable = ena;
540 			return;
541 		}
542 	}
543 	die("No such service %s", name);
544 }
545 
parse_host_and_port(char * hostport,char ** host,char ** port)546 static void parse_host_and_port(char *hostport, char **host,
547 	char **port)
548 {
549 	if (*hostport == '[') {
550 		char *end;
551 
552 		end = strchr(hostport, ']');
553 		if (!end)
554 			die("Invalid request ('[' without ']')");
555 		*end = '\0';
556 		*host = hostport + 1;
557 		if (!end[1])
558 			*port = NULL;
559 		else if (end[1] == ':')
560 			*port = end + 2;
561 		else
562 			die("Garbage after end of host part");
563 	} else {
564 		*host = hostport;
565 		*port = strrchr(hostport, ':');
566 		if (*port) {
567 			**port = '\0';
568 			++*port;
569 		}
570 	}
571 }
572 
573 /*
574  * Sanitize a string from the client so that it's OK to be inserted into a
575  * filesystem path. Specifically, we disallow directory separators, runs
576  * of "..", and trailing and leading dots, which means that the client
577  * cannot escape our base path via ".." traversal.
578  */
sanitize_client(struct strbuf * out,const char * in)579 static void sanitize_client(struct strbuf *out, const char *in)
580 {
581 	for (; *in; in++) {
582 		if (is_dir_sep(*in))
583 			continue;
584 		if (*in == '.' && (!out->len || out->buf[out->len - 1] == '.'))
585 			continue;
586 		strbuf_addch(out, *in);
587 	}
588 
589 	while (out->len && out->buf[out->len - 1] == '.')
590 		strbuf_setlen(out, out->len - 1);
591 }
592 
593 /*
594  * Like sanitize_client, but we also perform any canonicalization
595  * to make life easier on the admin.
596  */
canonicalize_client(struct strbuf * out,const char * in)597 static void canonicalize_client(struct strbuf *out, const char *in)
598 {
599 	sanitize_client(out, in);
600 	strbuf_tolower(out);
601 }
602 
603 /*
604  * Read the host as supplied by the client connection.
605  *
606  * Returns a pointer to the character after the NUL byte terminating the host
607  * argument, or 'extra_args' if there is no host argument.
608  */
parse_host_arg(struct hostinfo * hi,char * extra_args,int buflen)609 static char *parse_host_arg(struct hostinfo *hi, char *extra_args, int buflen)
610 {
611 	char *val;
612 	int vallen;
613 	char *end = extra_args + buflen;
614 
615 	if (extra_args < end && *extra_args) {
616 		hi->saw_extended_args = 1;
617 		if (strncasecmp("host=", extra_args, 5) == 0) {
618 			val = extra_args + 5;
619 			vallen = strlen(val) + 1;
620 			loginfo("Extended attribute \"host\": %s", val);
621 			if (*val) {
622 				/* Split <host>:<port> at colon. */
623 				char *host;
624 				char *port;
625 				parse_host_and_port(val, &host, &port);
626 				if (port)
627 					sanitize_client(&hi->tcp_port, port);
628 				canonicalize_client(&hi->hostname, host);
629 				hi->hostname_lookup_done = 0;
630 			}
631 
632 			/* On to the next one */
633 			extra_args = val + vallen;
634 		}
635 		if (extra_args < end && *extra_args)
636 			die("Invalid request");
637 	}
638 
639 	return extra_args;
640 }
641 
parse_extra_args(struct hostinfo * hi,struct strvec * env,char * extra_args,int buflen)642 static void parse_extra_args(struct hostinfo *hi, struct strvec *env,
643 			     char *extra_args, int buflen)
644 {
645 	const char *end = extra_args + buflen;
646 	struct strbuf git_protocol = STRBUF_INIT;
647 
648 	/* First look for the host argument */
649 	extra_args = parse_host_arg(hi, extra_args, buflen);
650 
651 	/* Look for additional arguments places after a second NUL byte */
652 	for (; extra_args < end; extra_args += strlen(extra_args) + 1) {
653 		const char *arg = extra_args;
654 
655 		/*
656 		 * Parse the extra arguments, adding most to 'git_protocol'
657 		 * which will be used to set the 'GIT_PROTOCOL' envvar in the
658 		 * service that will be run.
659 		 *
660 		 * If there ends up being a particular arg in the future that
661 		 * git-daemon needs to parse specifically (like the 'host' arg)
662 		 * then it can be parsed here and not added to 'git_protocol'.
663 		 */
664 		if (*arg) {
665 			if (git_protocol.len > 0)
666 				strbuf_addch(&git_protocol, ':');
667 			strbuf_addstr(&git_protocol, arg);
668 		}
669 	}
670 
671 	if (git_protocol.len > 0) {
672 		loginfo("Extended attribute \"protocol\": %s", git_protocol.buf);
673 		strvec_pushf(env, GIT_PROTOCOL_ENVIRONMENT "=%s",
674 			     git_protocol.buf);
675 	}
676 	strbuf_release(&git_protocol);
677 }
678 
679 /*
680  * Locate canonical hostname and its IP address.
681  */
lookup_hostname(struct hostinfo * hi)682 static void lookup_hostname(struct hostinfo *hi)
683 {
684 	if (!hi->hostname_lookup_done && hi->hostname.len) {
685 #ifndef NO_IPV6
686 		struct addrinfo hints;
687 		struct addrinfo *ai;
688 		int gai;
689 		static char addrbuf[HOST_NAME_MAX + 1];
690 
691 		memset(&hints, 0, sizeof(hints));
692 		hints.ai_flags = AI_CANONNAME;
693 
694 		gai = getaddrinfo(hi->hostname.buf, NULL, &hints, &ai);
695 		if (!gai) {
696 			struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
697 
698 			inet_ntop(AF_INET, &sin_addr->sin_addr,
699 				  addrbuf, sizeof(addrbuf));
700 			strbuf_addstr(&hi->ip_address, addrbuf);
701 
702 			if (ai->ai_canonname)
703 				sanitize_client(&hi->canon_hostname,
704 						ai->ai_canonname);
705 			else
706 				strbuf_addbuf(&hi->canon_hostname,
707 					      &hi->ip_address);
708 
709 			freeaddrinfo(ai);
710 		}
711 #else
712 		struct hostent *hent;
713 		struct sockaddr_in sa;
714 		char **ap;
715 		static char addrbuf[HOST_NAME_MAX + 1];
716 
717 		hent = gethostbyname(hi->hostname.buf);
718 		if (hent) {
719 			ap = hent->h_addr_list;
720 			memset(&sa, 0, sizeof sa);
721 			sa.sin_family = hent->h_addrtype;
722 			sa.sin_port = htons(0);
723 			memcpy(&sa.sin_addr, *ap, hent->h_length);
724 
725 			inet_ntop(hent->h_addrtype, &sa.sin_addr,
726 				  addrbuf, sizeof(addrbuf));
727 
728 			sanitize_client(&hi->canon_hostname, hent->h_name);
729 			strbuf_addstr(&hi->ip_address, addrbuf);
730 		}
731 #endif
732 		hi->hostname_lookup_done = 1;
733 	}
734 }
735 
hostinfo_clear(struct hostinfo * hi)736 static void hostinfo_clear(struct hostinfo *hi)
737 {
738 	strbuf_release(&hi->hostname);
739 	strbuf_release(&hi->canon_hostname);
740 	strbuf_release(&hi->ip_address);
741 	strbuf_release(&hi->tcp_port);
742 }
743 
set_keep_alive(int sockfd)744 static void set_keep_alive(int sockfd)
745 {
746 	int ka = 1;
747 
748 	if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0) {
749 		if (errno != ENOTSOCK)
750 			logerror("unable to set SO_KEEPALIVE on socket: %s",
751 				strerror(errno));
752 	}
753 }
754 
execute(void)755 static int execute(void)
756 {
757 	char *line = packet_buffer;
758 	int pktlen, len, i;
759 	char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
760 	struct hostinfo hi = HOSTINFO_INIT;
761 	struct strvec env = STRVEC_INIT;
762 
763 	if (addr)
764 		loginfo("Connection from %s:%s", addr, port);
765 
766 	set_keep_alive(0);
767 	alarm(init_timeout ? init_timeout : timeout);
768 	pktlen = packet_read(0, packet_buffer, sizeof(packet_buffer), 0);
769 	alarm(0);
770 
771 	len = strlen(line);
772 	if (len && line[len-1] == '\n')
773 		line[len-1] = 0;
774 
775 	/* parse additional args hidden behind a NUL byte */
776 	if (len != pktlen)
777 		parse_extra_args(&hi, &env, line + len + 1, pktlen - len - 1);
778 
779 	for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
780 		struct daemon_service *s = &(daemon_service[i]);
781 		const char *arg;
782 
783 		if (skip_prefix(line, "git-", &arg) &&
784 		    skip_prefix(arg, s->name, &arg) &&
785 		    *arg++ == ' ') {
786 			/*
787 			 * Note: The directory here is probably context sensitive,
788 			 * and might depend on the actual service being performed.
789 			 */
790 			int rc = run_service(arg, s, &hi, &env);
791 			hostinfo_clear(&hi);
792 			strvec_clear(&env);
793 			return rc;
794 		}
795 	}
796 
797 	hostinfo_clear(&hi);
798 	strvec_clear(&env);
799 	logerror("Protocol error: '%s'", line);
800 	return -1;
801 }
802 
addrcmp(const struct sockaddr_storage * s1,const struct sockaddr_storage * s2)803 static int addrcmp(const struct sockaddr_storage *s1,
804     const struct sockaddr_storage *s2)
805 {
806 	const struct sockaddr *sa1 = (const struct sockaddr*) s1;
807 	const struct sockaddr *sa2 = (const struct sockaddr*) s2;
808 
809 	if (sa1->sa_family != sa2->sa_family)
810 		return sa1->sa_family - sa2->sa_family;
811 	if (sa1->sa_family == AF_INET)
812 		return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
813 		    &((struct sockaddr_in *)s2)->sin_addr,
814 		    sizeof(struct in_addr));
815 #ifndef NO_IPV6
816 	if (sa1->sa_family == AF_INET6)
817 		return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
818 		    &((struct sockaddr_in6 *)s2)->sin6_addr,
819 		    sizeof(struct in6_addr));
820 #endif
821 	return 0;
822 }
823 
824 static int max_connections = 32;
825 
826 static unsigned int live_children;
827 
828 static struct child {
829 	struct child *next;
830 	struct child_process cld;
831 	struct sockaddr_storage address;
832 } *firstborn;
833 
add_child(struct child_process * cld,struct sockaddr * addr,socklen_t addrlen)834 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
835 {
836 	struct child *newborn, **cradle;
837 
838 	CALLOC_ARRAY(newborn, 1);
839 	live_children++;
840 	memcpy(&newborn->cld, cld, sizeof(*cld));
841 	memcpy(&newborn->address, addr, addrlen);
842 	for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
843 		if (!addrcmp(&(*cradle)->address, &newborn->address))
844 			break;
845 	newborn->next = *cradle;
846 	*cradle = newborn;
847 }
848 
849 /*
850  * This gets called if the number of connections grows
851  * past "max_connections".
852  *
853  * We kill the newest connection from a duplicate IP.
854  */
kill_some_child(void)855 static void kill_some_child(void)
856 {
857 	const struct child *blanket, *next;
858 
859 	if (!(blanket = firstborn))
860 		return;
861 
862 	for (; (next = blanket->next); blanket = next)
863 		if (!addrcmp(&blanket->address, &next->address)) {
864 			kill(blanket->cld.pid, SIGTERM);
865 			break;
866 		}
867 }
868 
check_dead_children(void)869 static void check_dead_children(void)
870 {
871 	int status;
872 	pid_t pid;
873 
874 	struct child **cradle, *blanket;
875 	for (cradle = &firstborn; (blanket = *cradle);)
876 		if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
877 			const char *dead = "";
878 			if (status)
879 				dead = " (with error)";
880 			loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
881 
882 			/* remove the child */
883 			*cradle = blanket->next;
884 			live_children--;
885 			child_process_clear(&blanket->cld);
886 			free(blanket);
887 		} else
888 			cradle = &blanket->next;
889 }
890 
891 static struct strvec cld_argv = STRVEC_INIT;
handle(int incoming,struct sockaddr * addr,socklen_t addrlen)892 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
893 {
894 	struct child_process cld = CHILD_PROCESS_INIT;
895 
896 	if (max_connections && live_children >= max_connections) {
897 		kill_some_child();
898 		sleep(1);  /* give it some time to die */
899 		check_dead_children();
900 		if (live_children >= max_connections) {
901 			close(incoming);
902 			logerror("Too many children, dropping connection");
903 			return;
904 		}
905 	}
906 
907 	if (addr->sa_family == AF_INET) {
908 		char buf[128] = "";
909 		struct sockaddr_in *sin_addr = (void *) addr;
910 		inet_ntop(addr->sa_family, &sin_addr->sin_addr, buf, sizeof(buf));
911 		strvec_pushf(&cld.env_array, "REMOTE_ADDR=%s", buf);
912 		strvec_pushf(&cld.env_array, "REMOTE_PORT=%d",
913 			     ntohs(sin_addr->sin_port));
914 #ifndef NO_IPV6
915 	} else if (addr->sa_family == AF_INET6) {
916 		char buf[128] = "";
917 		struct sockaddr_in6 *sin6_addr = (void *) addr;
918 		inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(buf));
919 		strvec_pushf(&cld.env_array, "REMOTE_ADDR=[%s]", buf);
920 		strvec_pushf(&cld.env_array, "REMOTE_PORT=%d",
921 			     ntohs(sin6_addr->sin6_port));
922 #endif
923 	}
924 
925 	cld.argv = cld_argv.v;
926 	cld.in = incoming;
927 	cld.out = dup(incoming);
928 
929 	if (start_command(&cld))
930 		logerror("unable to fork");
931 	else
932 		add_child(&cld, addr, addrlen);
933 }
934 
child_handler(int signo)935 static void child_handler(int signo)
936 {
937 	/*
938 	 * Otherwise empty handler because systemcalls will get interrupted
939 	 * upon signal receipt
940 	 * SysV needs the handler to be rearmed
941 	 */
942 	signal(SIGCHLD, child_handler);
943 }
944 
set_reuse_addr(int sockfd)945 static int set_reuse_addr(int sockfd)
946 {
947 	int on = 1;
948 
949 	if (!reuseaddr)
950 		return 0;
951 	return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
952 			  &on, sizeof(on));
953 }
954 
955 struct socketlist {
956 	int *list;
957 	size_t nr;
958 	size_t alloc;
959 };
960 
ip2str(int family,struct sockaddr * sin,socklen_t len)961 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
962 {
963 #ifdef NO_IPV6
964 	static char ip[INET_ADDRSTRLEN];
965 #else
966 	static char ip[INET6_ADDRSTRLEN];
967 #endif
968 
969 	switch (family) {
970 #ifndef NO_IPV6
971 	case AF_INET6:
972 		inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
973 		break;
974 #endif
975 	case AF_INET:
976 		inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
977 		break;
978 	default:
979 		xsnprintf(ip, sizeof(ip), "<unknown>");
980 	}
981 	return ip;
982 }
983 
984 #ifndef NO_IPV6
985 
setup_named_sock(char * listen_addr,int listen_port,struct socketlist * socklist)986 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
987 {
988 	int socknum = 0;
989 	char pbuf[NI_MAXSERV];
990 	struct addrinfo hints, *ai0, *ai;
991 	int gai;
992 	long flags;
993 
994 	xsnprintf(pbuf, sizeof(pbuf), "%d", listen_port);
995 	memset(&hints, 0, sizeof(hints));
996 	hints.ai_family = AF_UNSPEC;
997 	hints.ai_socktype = SOCK_STREAM;
998 	hints.ai_protocol = IPPROTO_TCP;
999 	hints.ai_flags = AI_PASSIVE;
1000 
1001 	gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
1002 	if (gai) {
1003 		logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
1004 		return 0;
1005 	}
1006 
1007 	for (ai = ai0; ai; ai = ai->ai_next) {
1008 		int sockfd;
1009 
1010 		sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1011 		if (sockfd < 0)
1012 			continue;
1013 		if (sockfd >= FD_SETSIZE) {
1014 			logerror("Socket descriptor too large");
1015 			close(sockfd);
1016 			continue;
1017 		}
1018 
1019 #ifdef IPV6_V6ONLY
1020 		if (ai->ai_family == AF_INET6) {
1021 			int on = 1;
1022 			setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
1023 				   &on, sizeof(on));
1024 			/* Note: error is not fatal */
1025 		}
1026 #endif
1027 
1028 		if (set_reuse_addr(sockfd)) {
1029 			logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1030 			close(sockfd);
1031 			continue;
1032 		}
1033 
1034 		set_keep_alive(sockfd);
1035 
1036 		if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
1037 			logerror("Could not bind to %s: %s",
1038 				 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
1039 				 strerror(errno));
1040 			close(sockfd);
1041 			continue;	/* not fatal */
1042 		}
1043 		if (listen(sockfd, 5) < 0) {
1044 			logerror("Could not listen to %s: %s",
1045 				 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
1046 				 strerror(errno));
1047 			close(sockfd);
1048 			continue;	/* not fatal */
1049 		}
1050 
1051 		flags = fcntl(sockfd, F_GETFD, 0);
1052 		if (flags >= 0)
1053 			fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1054 
1055 		ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1056 		socklist->list[socklist->nr++] = sockfd;
1057 		socknum++;
1058 	}
1059 
1060 	freeaddrinfo(ai0);
1061 
1062 	return socknum;
1063 }
1064 
1065 #else /* NO_IPV6 */
1066 
setup_named_sock(char * listen_addr,int listen_port,struct socketlist * socklist)1067 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
1068 {
1069 	struct sockaddr_in sin;
1070 	int sockfd;
1071 	long flags;
1072 
1073 	memset(&sin, 0, sizeof sin);
1074 	sin.sin_family = AF_INET;
1075 	sin.sin_port = htons(listen_port);
1076 
1077 	if (listen_addr) {
1078 		/* Well, host better be an IP address here. */
1079 		if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
1080 			return 0;
1081 	} else {
1082 		sin.sin_addr.s_addr = htonl(INADDR_ANY);
1083 	}
1084 
1085 	sockfd = socket(AF_INET, SOCK_STREAM, 0);
1086 	if (sockfd < 0)
1087 		return 0;
1088 
1089 	if (set_reuse_addr(sockfd)) {
1090 		logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1091 		close(sockfd);
1092 		return 0;
1093 	}
1094 
1095 	set_keep_alive(sockfd);
1096 
1097 	if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
1098 		logerror("Could not bind to %s: %s",
1099 			 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1100 			 strerror(errno));
1101 		close(sockfd);
1102 		return 0;
1103 	}
1104 
1105 	if (listen(sockfd, 5) < 0) {
1106 		logerror("Could not listen to %s: %s",
1107 			 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1108 			 strerror(errno));
1109 		close(sockfd);
1110 		return 0;
1111 	}
1112 
1113 	flags = fcntl(sockfd, F_GETFD, 0);
1114 	if (flags >= 0)
1115 		fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1116 
1117 	ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1118 	socklist->list[socklist->nr++] = sockfd;
1119 	return 1;
1120 }
1121 
1122 #endif
1123 
socksetup(struct string_list * listen_addr,int listen_port,struct socketlist * socklist)1124 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
1125 {
1126 	if (!listen_addr->nr)
1127 		setup_named_sock(NULL, listen_port, socklist);
1128 	else {
1129 		int i, socknum;
1130 		for (i = 0; i < listen_addr->nr; i++) {
1131 			socknum = setup_named_sock(listen_addr->items[i].string,
1132 						   listen_port, socklist);
1133 
1134 			if (socknum == 0)
1135 				logerror("unable to allocate any listen sockets for host %s on port %u",
1136 					 listen_addr->items[i].string, listen_port);
1137 		}
1138 	}
1139 }
1140 
service_loop(struct socketlist * socklist)1141 static int service_loop(struct socketlist *socklist)
1142 {
1143 	struct pollfd *pfd;
1144 	int i;
1145 
1146 	CALLOC_ARRAY(pfd, socklist->nr);
1147 
1148 	for (i = 0; i < socklist->nr; i++) {
1149 		pfd[i].fd = socklist->list[i];
1150 		pfd[i].events = POLLIN;
1151 	}
1152 
1153 	signal(SIGCHLD, child_handler);
1154 
1155 	for (;;) {
1156 		int i;
1157 
1158 		check_dead_children();
1159 
1160 		if (poll(pfd, socklist->nr, -1) < 0) {
1161 			if (errno != EINTR) {
1162 				logerror("Poll failed, resuming: %s",
1163 				      strerror(errno));
1164 				sleep(1);
1165 			}
1166 			continue;
1167 		}
1168 
1169 		for (i = 0; i < socklist->nr; i++) {
1170 			if (pfd[i].revents & POLLIN) {
1171 				union {
1172 					struct sockaddr sa;
1173 					struct sockaddr_in sai;
1174 #ifndef NO_IPV6
1175 					struct sockaddr_in6 sai6;
1176 #endif
1177 				} ss;
1178 				socklen_t sslen = sizeof(ss);
1179 				int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1180 				if (incoming < 0) {
1181 					switch (errno) {
1182 					case EAGAIN:
1183 					case EINTR:
1184 					case ECONNABORTED:
1185 						continue;
1186 					default:
1187 						die_errno("accept returned");
1188 					}
1189 				}
1190 				handle(incoming, &ss.sa, sslen);
1191 			}
1192 		}
1193 	}
1194 }
1195 
1196 #ifdef NO_POSIX_GOODIES
1197 
1198 struct credentials;
1199 
drop_privileges(struct credentials * cred)1200 static void drop_privileges(struct credentials *cred)
1201 {
1202 	/* nothing */
1203 }
1204 
prepare_credentials(const char * user_name,const char * group_name)1205 static struct credentials *prepare_credentials(const char *user_name,
1206     const char *group_name)
1207 {
1208 	die("--user not supported on this platform");
1209 }
1210 
1211 #else
1212 
1213 struct credentials {
1214 	struct passwd *pass;
1215 	gid_t gid;
1216 };
1217 
drop_privileges(struct credentials * cred)1218 static void drop_privileges(struct credentials *cred)
1219 {
1220 	if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1221 	    setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1222 		die("cannot drop privileges");
1223 }
1224 
prepare_credentials(const char * user_name,const char * group_name)1225 static struct credentials *prepare_credentials(const char *user_name,
1226     const char *group_name)
1227 {
1228 	static struct credentials c;
1229 
1230 	c.pass = getpwnam(user_name);
1231 	if (!c.pass)
1232 		die("user not found - %s", user_name);
1233 
1234 	if (!group_name)
1235 		c.gid = c.pass->pw_gid;
1236 	else {
1237 		struct group *group = getgrnam(group_name);
1238 		if (!group)
1239 			die("group not found - %s", group_name);
1240 
1241 		c.gid = group->gr_gid;
1242 	}
1243 
1244 	return &c;
1245 }
1246 #endif
1247 
serve(struct string_list * listen_addr,int listen_port,struct credentials * cred)1248 static int serve(struct string_list *listen_addr, int listen_port,
1249     struct credentials *cred)
1250 {
1251 	struct socketlist socklist = { NULL, 0, 0 };
1252 
1253 	socksetup(listen_addr, listen_port, &socklist);
1254 	if (socklist.nr == 0)
1255 		die("unable to allocate any listen sockets on port %u",
1256 		    listen_port);
1257 
1258 	drop_privileges(cred);
1259 
1260 	loginfo("Ready to rumble");
1261 
1262 	return service_loop(&socklist);
1263 }
1264 
cmd_main(int argc,const char ** argv)1265 int cmd_main(int argc, const char **argv)
1266 {
1267 	int listen_port = 0;
1268 	struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1269 	int serve_mode = 0, inetd_mode = 0;
1270 	const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1271 	int detach = 0;
1272 	struct credentials *cred = NULL;
1273 	int i;
1274 
1275 	for (i = 1; i < argc; i++) {
1276 		const char *arg = argv[i];
1277 		const char *v;
1278 
1279 		if (skip_prefix(arg, "--listen=", &v)) {
1280 			string_list_append(&listen_addr, xstrdup_tolower(v));
1281 			continue;
1282 		}
1283 		if (skip_prefix(arg, "--port=", &v)) {
1284 			char *end;
1285 			unsigned long n;
1286 			n = strtoul(v, &end, 0);
1287 			if (*v && !*end) {
1288 				listen_port = n;
1289 				continue;
1290 			}
1291 		}
1292 		if (!strcmp(arg, "--serve")) {
1293 			serve_mode = 1;
1294 			continue;
1295 		}
1296 		if (!strcmp(arg, "--inetd")) {
1297 			inetd_mode = 1;
1298 			continue;
1299 		}
1300 		if (!strcmp(arg, "--verbose")) {
1301 			verbose = 1;
1302 			continue;
1303 		}
1304 		if (!strcmp(arg, "--syslog")) {
1305 			log_destination = LOG_DESTINATION_SYSLOG;
1306 			continue;
1307 		}
1308 		if (skip_prefix(arg, "--log-destination=", &v)) {
1309 			if (!strcmp(v, "syslog")) {
1310 				log_destination = LOG_DESTINATION_SYSLOG;
1311 				continue;
1312 			} else if (!strcmp(v, "stderr")) {
1313 				log_destination = LOG_DESTINATION_STDERR;
1314 				continue;
1315 			} else if (!strcmp(v, "none")) {
1316 				log_destination = LOG_DESTINATION_NONE;
1317 				continue;
1318 			} else
1319 				die("unknown log destination '%s'", v);
1320 		}
1321 		if (!strcmp(arg, "--export-all")) {
1322 			export_all_trees = 1;
1323 			continue;
1324 		}
1325 		if (skip_prefix(arg, "--access-hook=", &v)) {
1326 			access_hook = v;
1327 			continue;
1328 		}
1329 		if (skip_prefix(arg, "--timeout=", &v)) {
1330 			timeout = atoi(v);
1331 			continue;
1332 		}
1333 		if (skip_prefix(arg, "--init-timeout=", &v)) {
1334 			init_timeout = atoi(v);
1335 			continue;
1336 		}
1337 		if (skip_prefix(arg, "--max-connections=", &v)) {
1338 			max_connections = atoi(v);
1339 			if (max_connections < 0)
1340 				max_connections = 0;	        /* unlimited */
1341 			continue;
1342 		}
1343 		if (!strcmp(arg, "--strict-paths")) {
1344 			strict_paths = 1;
1345 			continue;
1346 		}
1347 		if (skip_prefix(arg, "--base-path=", &v)) {
1348 			base_path = v;
1349 			continue;
1350 		}
1351 		if (!strcmp(arg, "--base-path-relaxed")) {
1352 			base_path_relaxed = 1;
1353 			continue;
1354 		}
1355 		if (skip_prefix(arg, "--interpolated-path=", &v)) {
1356 			interpolated_path = v;
1357 			continue;
1358 		}
1359 		if (!strcmp(arg, "--reuseaddr")) {
1360 			reuseaddr = 1;
1361 			continue;
1362 		}
1363 		if (!strcmp(arg, "--user-path")) {
1364 			user_path = "";
1365 			continue;
1366 		}
1367 		if (skip_prefix(arg, "--user-path=", &v)) {
1368 			user_path = v;
1369 			continue;
1370 		}
1371 		if (skip_prefix(arg, "--pid-file=", &v)) {
1372 			pid_file = v;
1373 			continue;
1374 		}
1375 		if (!strcmp(arg, "--detach")) {
1376 			detach = 1;
1377 			continue;
1378 		}
1379 		if (skip_prefix(arg, "--user=", &v)) {
1380 			user_name = v;
1381 			continue;
1382 		}
1383 		if (skip_prefix(arg, "--group=", &v)) {
1384 			group_name = v;
1385 			continue;
1386 		}
1387 		if (skip_prefix(arg, "--enable=", &v)) {
1388 			enable_service(v, 1);
1389 			continue;
1390 		}
1391 		if (skip_prefix(arg, "--disable=", &v)) {
1392 			enable_service(v, 0);
1393 			continue;
1394 		}
1395 		if (skip_prefix(arg, "--allow-override=", &v)) {
1396 			make_service_overridable(v, 1);
1397 			continue;
1398 		}
1399 		if (skip_prefix(arg, "--forbid-override=", &v)) {
1400 			make_service_overridable(v, 0);
1401 			continue;
1402 		}
1403 		if (!strcmp(arg, "--informative-errors")) {
1404 			informative_errors = 1;
1405 			continue;
1406 		}
1407 		if (!strcmp(arg, "--no-informative-errors")) {
1408 			informative_errors = 0;
1409 			continue;
1410 		}
1411 		if (!strcmp(arg, "--")) {
1412 			ok_paths = &argv[i+1];
1413 			break;
1414 		} else if (arg[0] != '-') {
1415 			ok_paths = &argv[i];
1416 			break;
1417 		}
1418 
1419 		usage(daemon_usage);
1420 	}
1421 
1422 	if (log_destination == LOG_DESTINATION_UNSET) {
1423 		if (inetd_mode || detach)
1424 			log_destination = LOG_DESTINATION_SYSLOG;
1425 		else
1426 			log_destination = LOG_DESTINATION_STDERR;
1427 	}
1428 
1429 	if (log_destination == LOG_DESTINATION_SYSLOG) {
1430 		openlog("git-daemon", LOG_PID, LOG_DAEMON);
1431 		set_die_routine(daemon_die);
1432 	} else
1433 		/* avoid splitting a message in the middle */
1434 		setvbuf(stderr, NULL, _IOFBF, 4096);
1435 
1436 	if (inetd_mode && (detach || group_name || user_name))
1437 		die("--detach, --user and --group are incompatible with --inetd");
1438 
1439 	if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1440 		die("--listen= and --port= are incompatible with --inetd");
1441 	else if (listen_port == 0)
1442 		listen_port = DEFAULT_GIT_PORT;
1443 
1444 	if (group_name && !user_name)
1445 		die("--group supplied without --user");
1446 
1447 	if (user_name)
1448 		cred = prepare_credentials(user_name, group_name);
1449 
1450 	if (strict_paths && (!ok_paths || !*ok_paths))
1451 		die("option --strict-paths requires a whitelist");
1452 
1453 	if (base_path && !is_directory(base_path))
1454 		die("base-path '%s' does not exist or is not a directory",
1455 		    base_path);
1456 
1457 	if (log_destination != LOG_DESTINATION_STDERR) {
1458 		if (!freopen("/dev/null", "w", stderr))
1459 			die_errno("failed to redirect stderr to /dev/null");
1460 	}
1461 
1462 	if (inetd_mode || serve_mode)
1463 		return execute();
1464 
1465 	if (detach) {
1466 		if (daemonize())
1467 			die("--detach not supported on this platform");
1468 	}
1469 
1470 	if (pid_file)
1471 		write_file(pid_file, "%"PRIuMAX, (uintmax_t) getpid());
1472 
1473 	/* prepare argv for serving-processes */
1474 	strvec_push(&cld_argv, argv[0]); /* git-daemon */
1475 	strvec_push(&cld_argv, "--serve");
1476 	for (i = 1; i < argc; ++i)
1477 		strvec_push(&cld_argv, argv[i]);
1478 
1479 	return serve(&listen_addr, listen_port, cred);
1480 }
1481