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