4 #include "run-command.h"
6 #include "string-list.h"
9 #define HOST_NAME_MAX 256
13 #define initgroups(x, y) (0) /* nothing */
16 static int log_syslog;
19 static int informative_errors;
21 static const char daemon_usage[] =
22 "git daemon [--verbose] [--syslog] [--export-all]\n"
23 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
24 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
25 " [--user-path | --user-path=<path>]\n"
26 " [--interpolated-path=<path>]\n"
27 " [--reuseaddr] [--pid-file=<file>]\n"
28 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
29 " [--access-hook=<path>]\n"
30 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
31 " [--detach] [--user=<user> [--group=<group>]]\n"
34 /* List of acceptable pathname prefixes */
35 static char **ok_paths;
36 static int strict_paths;
38 /* If this is set, git-daemon-export-ok is not required */
39 static int export_all_trees;
41 /* Take all paths relative to this one if non-NULL */
42 static const char *base_path;
43 static const char *interpolated_path;
44 static int base_path_relaxed;
46 /* Flag indicating client sent extra args. */
47 static int saw_extended_args;
49 /* If defined, ~user notation is allowed and the string is inserted
50 * after ~user/. E.g. a request to git://host/~alice/frotz would
51 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
53 static const char *user_path;
55 /* Timeout, and initial timeout */
56 static unsigned int timeout;
57 static unsigned int init_timeout;
59 static struct strbuf hostname = STRBUF_INIT;
60 static struct strbuf canon_hostname = STRBUF_INIT;
61 static struct strbuf ip_address = STRBUF_INIT;
62 static struct strbuf tcp_port = STRBUF_INIT;
64 static int hostname_lookup_done;
66 static void lookup_hostname(void);
68 static const char *get_canon_hostname(void)
71 return canon_hostname.buf;
74 static const char *get_ip_address(void)
77 return ip_address.buf;
80 static void logreport(int priority, const char *err, va_list params)
84 vsnprintf(buf, sizeof(buf), err, params);
85 syslog(priority, "%s", buf);
88 * Since stderr is set to buffered mode, the
89 * logging of different processes will not overlap
90 * unless they overflow the (rather big) buffers.
92 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
93 vfprintf(stderr, err, params);
99 __attribute__((format (printf, 1, 2)))
100 static void logerror(const char *err, ...)
103 va_start(params, err);
104 logreport(LOG_ERR, err, params);
108 __attribute__((format (printf, 1, 2)))
109 static void loginfo(const char *err, ...)
114 va_start(params, err);
115 logreport(LOG_INFO, err, params);
119 static void NORETURN daemon_die(const char *err, va_list params)
121 logreport(LOG_ERR, err, params);
125 struct expand_path_context {
126 const char *directory;
129 static size_t expand_path(struct strbuf *sb, const char *placeholder, void *ctx)
131 struct expand_path_context *context = ctx;
133 switch (placeholder[0]) {
135 strbuf_addbuf(sb, &hostname);
138 if (placeholder[1] == 'H') {
139 strbuf_addstr(sb, get_canon_hostname());
144 if (placeholder[1] == 'P') {
145 strbuf_addstr(sb, get_ip_address());
150 strbuf_addbuf(sb, &tcp_port);
153 strbuf_addstr(sb, context->directory);
159 static const char *path_ok(const char *directory)
161 static char rpath[PATH_MAX];
162 static char interp_path[PATH_MAX];
168 if (daemon_avoid_alias(dir)) {
169 logerror("'%s': aliased", dir);
175 logerror("'%s': User-path not allowed", dir);
179 /* Got either "~alice" or "~alice/foo";
180 * rewrite them to "~alice/%s" or
183 int namlen, restlen = strlen(dir);
184 const char *slash = strchr(dir, '/');
186 slash = dir + restlen;
187 namlen = slash - dir;
189 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
190 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
191 namlen, dir, user_path, restlen, slash);
195 else if (interpolated_path && saw_extended_args) {
196 struct strbuf expanded_path = STRBUF_INIT;
197 struct expand_path_context context;
199 context.directory = directory;
202 /* Allow only absolute */
203 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
207 strbuf_expand(&expanded_path, interpolated_path,
208 expand_path, &context);
209 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
210 strbuf_release(&expanded_path);
211 loginfo("Interpolated dir '%s'", interp_path);
215 else if (base_path) {
217 /* Allow only absolute */
218 logerror("'%s': Non-absolute path denied (base-path active)", dir);
221 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
225 path = enter_repo(dir, strict_paths);
226 if (!path && base_path && base_path_relaxed) {
228 * if we fail and base_path_relaxed is enabled, try without
229 * prefixing the base path
232 path = enter_repo(dir, strict_paths);
236 logerror("'%s' does not appear to be a git repository", dir);
240 if ( ok_paths && *ok_paths ) {
242 int pathlen = strlen(path);
244 /* The validation is done on the paths after enter_repo
245 * appends optional {.git,.git/.git} and friends, but
246 * it does not use getcwd(). So if your /pub is
247 * a symlink to /mnt/pub, you can whitelist /pub and
248 * do not have to say /mnt/pub.
251 for ( pp = ok_paths ; *pp ; pp++ ) {
252 int len = strlen(*pp);
253 if (len <= pathlen &&
254 !memcmp(*pp, path, len) &&
255 (path[len] == '\0' ||
256 (!strict_paths && path[len] == '/')))
261 /* be backwards compatible */
266 logerror("'%s': not in whitelist", path);
267 return NULL; /* Fallthrough. Deny by default */
270 typedef int (*daemon_service_fn)(void);
271 struct daemon_service {
273 const char *config_name;
274 daemon_service_fn fn;
279 static int daemon_error(const char *dir, const char *msg)
281 if (!informative_errors)
282 msg = "access denied or repository not exported";
283 packet_write(1, "ERR %s: %s", msg, dir);
287 static const char *access_hook;
289 static int run_access_hook(struct daemon_service *service, const char *dir, const char *path)
291 struct child_process child = CHILD_PROCESS_INIT;
292 struct strbuf buf = STRBUF_INIT;
294 const char **arg = argv;
298 *arg++ = access_hook;
299 *arg++ = service->name;
301 *arg++ = hostname.buf;
302 *arg++ = get_canon_hostname();
303 *arg++ = get_ip_address();
304 *arg++ = tcp_port.buf;
312 if (start_command(&child)) {
313 logerror("daemon access hook '%s' failed to start",
317 if (strbuf_read(&buf, child.out, 0) < 0) {
318 logerror("failed to read from pipe to daemon access hook '%s'",
323 if (close(child.out) < 0) {
324 logerror("failed to close pipe to daemon access hook '%s'",
328 if (finish_command(&child))
332 strbuf_release(&buf);
339 strbuf_addstr(&buf, "service rejected");
340 eol = strchr(buf.buf, '\n');
344 daemon_error(dir, buf.buf);
345 strbuf_release(&buf);
349 static int run_service(const char *dir, struct daemon_service *service)
352 int enabled = service->enabled;
353 struct strbuf var = STRBUF_INIT;
355 loginfo("Request %s for '%s'", service->name, dir);
357 if (!enabled && !service->overridable) {
358 logerror("'%s': service not enabled.", service->name);
360 return daemon_error(dir, "service not enabled");
363 if (!(path = path_ok(dir)))
364 return daemon_error(dir, "no such repository");
367 * Security on the cheap.
369 * We want a readable HEAD, usable "objects" directory, and
370 * a "git-daemon-export-ok" flag that says that the other side
371 * is ok with us doing this.
373 * path_ok() uses enter_repo() and does whitelist checking.
374 * We only need to make sure the repository is exported.
377 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
378 logerror("'%s': repository not exported.", path);
380 return daemon_error(dir, "repository not exported");
383 if (service->overridable) {
384 strbuf_addf(&var, "daemon.%s", service->config_name);
385 git_config_get_bool(var.buf, &enabled);
386 strbuf_release(&var);
389 logerror("'%s': service not enabled for '%s'",
390 service->name, path);
392 return daemon_error(dir, "service not enabled");
396 * Optionally, a hook can choose to deny access to the
397 * repository depending on the phase of the moon.
399 if (access_hook && run_access_hook(service, dir, path))
403 * We'll ignore SIGTERM from now on, we have a
406 signal(SIGTERM, SIG_IGN);
408 return service->fn();
411 static void copy_to_log(int fd)
413 struct strbuf line = STRBUF_INIT;
416 fp = fdopen(fd, "r");
418 logerror("fdopen of error channel failed");
423 while (strbuf_getline(&line, fp, '\n') != EOF) {
424 logerror("%s", line.buf);
425 strbuf_setlen(&line, 0);
428 strbuf_release(&line);
432 static int run_service_command(const char **argv)
434 struct child_process cld = CHILD_PROCESS_INIT;
439 if (start_command(&cld))
445 copy_to_log(cld.err);
447 return finish_command(&cld);
450 static int upload_pack(void)
452 /* Timeout as string */
453 char timeout_buf[64];
454 const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
456 argv[2] = timeout_buf;
458 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
459 return run_service_command(argv);
462 static int upload_archive(void)
464 static const char *argv[] = { "upload-archive", ".", NULL };
465 return run_service_command(argv);
468 static int receive_pack(void)
470 static const char *argv[] = { "receive-pack", ".", NULL };
471 return run_service_command(argv);
474 static struct daemon_service daemon_service[] = {
475 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
476 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
477 { "receive-pack", "receivepack", receive_pack, 0, 1 },
480 static void enable_service(const char *name, int ena)
483 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
484 if (!strcmp(daemon_service[i].name, name)) {
485 daemon_service[i].enabled = ena;
489 die("No such service %s", name);
492 static void make_service_overridable(const char *name, int ena)
495 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
496 if (!strcmp(daemon_service[i].name, name)) {
497 daemon_service[i].overridable = ena;
501 die("No such service %s", name);
504 static void parse_host_and_port(char *hostport, char **host,
507 if (*hostport == '[') {
510 end = strchr(hostport, ']');
512 die("Invalid request ('[' without ']')");
514 *host = hostport + 1;
517 else if (end[1] == ':')
520 die("Garbage after end of host part");
523 *port = strrchr(hostport, ':');
532 * Sanitize a string from the client so that it's OK to be inserted into a
533 * filesystem path. Specifically, we disallow slashes, runs of "..", and
534 * trailing and leading dots, which means that the client cannot escape
535 * our base path via ".." traversal.
537 static void sanitize_client(struct strbuf *out, const char *in)
542 if (*in == '.' && (!out->len || out->buf[out->len - 1] == '.'))
544 strbuf_addch(out, *in);
547 while (out->len && out->buf[out->len - 1] == '.')
548 strbuf_setlen(out, out->len - 1);
552 * Like sanitize_client, but we also perform any canonicalization
553 * to make life easier on the admin.
555 static void canonicalize_client(struct strbuf *out, const char *in)
557 sanitize_client(out, in);
562 * Read the host as supplied by the client connection.
564 static void parse_host_arg(char *extra_args, int buflen)
568 char *end = extra_args + buflen;
570 if (extra_args < end && *extra_args) {
571 saw_extended_args = 1;
572 if (strncasecmp("host=", extra_args, 5) == 0) {
573 val = extra_args + 5;
574 vallen = strlen(val) + 1;
576 /* Split <host>:<port> at colon. */
579 parse_host_and_port(val, &host, &port);
581 strbuf_reset(&tcp_port);
582 sanitize_client(&tcp_port, port);
584 strbuf_reset(&hostname);
585 canonicalize_client(&hostname, host);
586 hostname_lookup_done = 0;
589 /* On to the next one */
590 extra_args = val + vallen;
592 if (extra_args < end && *extra_args)
593 die("Invalid request");
598 * Locate canonical hostname and its IP address.
600 static void lookup_hostname(void)
602 if (!hostname_lookup_done && hostname.len) {
604 struct addrinfo hints;
607 static char addrbuf[HOST_NAME_MAX + 1];
609 memset(&hints, 0, sizeof(hints));
610 hints.ai_flags = AI_CANONNAME;
612 gai = getaddrinfo(hostname.buf, NULL, &hints, &ai);
614 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
616 inet_ntop(AF_INET, &sin_addr->sin_addr,
617 addrbuf, sizeof(addrbuf));
618 strbuf_reset(&ip_address);
619 strbuf_addstr(&ip_address, addrbuf);
621 strbuf_reset(&canon_hostname);
622 if (ai->ai_canonname)
623 sanitize_client(&canon_hostname,
626 strbuf_addbuf(&canon_hostname, &ip_address);
631 struct hostent *hent;
632 struct sockaddr_in sa;
634 static char addrbuf[HOST_NAME_MAX + 1];
636 hent = gethostbyname(hostname.buf);
638 ap = hent->h_addr_list;
639 memset(&sa, 0, sizeof sa);
640 sa.sin_family = hent->h_addrtype;
641 sa.sin_port = htons(0);
642 memcpy(&sa.sin_addr, *ap, hent->h_length);
644 inet_ntop(hent->h_addrtype, &sa.sin_addr,
645 addrbuf, sizeof(addrbuf));
647 strbuf_reset(&canon_hostname);
648 sanitize_client(&canon_hostname, hent->h_name);
649 strbuf_reset(&ip_address);
650 strbuf_addstr(&ip_address, addrbuf);
653 hostname_lookup_done = 1;
658 static int execute(void)
660 char *line = packet_buffer;
662 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
665 loginfo("Connection from %s:%s", addr, port);
667 alarm(init_timeout ? init_timeout : timeout);
668 pktlen = packet_read(0, NULL, NULL, packet_buffer, sizeof(packet_buffer), 0);
673 loginfo("Extended attributes (%d bytes) exist <%.*s>",
675 (int) pktlen - len, line + len + 1);
676 if (len && line[len-1] == '\n') {
681 strbuf_release(&hostname);
682 strbuf_release(&canon_hostname);
683 strbuf_release(&ip_address);
684 strbuf_release(&tcp_port);
687 parse_host_arg(line + len + 1, pktlen - len - 1);
689 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
690 struct daemon_service *s = &(daemon_service[i]);
693 if (skip_prefix(line, "git-", &arg) &&
694 skip_prefix(arg, s->name, &arg) &&
697 * Note: The directory here is probably context sensitive,
698 * and might depend on the actual service being performed.
700 return run_service(arg, s);
704 logerror("Protocol error: '%s'", line);
708 static int addrcmp(const struct sockaddr_storage *s1,
709 const struct sockaddr_storage *s2)
711 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
712 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
714 if (sa1->sa_family != sa2->sa_family)
715 return sa1->sa_family - sa2->sa_family;
716 if (sa1->sa_family == AF_INET)
717 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
718 &((struct sockaddr_in *)s2)->sin_addr,
719 sizeof(struct in_addr));
721 if (sa1->sa_family == AF_INET6)
722 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
723 &((struct sockaddr_in6 *)s2)->sin6_addr,
724 sizeof(struct in6_addr));
729 static int max_connections = 32;
731 static unsigned int live_children;
733 static struct child {
735 struct child_process cld;
736 struct sockaddr_storage address;
739 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
741 struct child *newborn, **cradle;
743 newborn = xcalloc(1, sizeof(*newborn));
745 memcpy(&newborn->cld, cld, sizeof(*cld));
746 memcpy(&newborn->address, addr, addrlen);
747 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
748 if (!addrcmp(&(*cradle)->address, &newborn->address))
750 newborn->next = *cradle;
755 * This gets called if the number of connections grows
756 * past "max_connections".
758 * We kill the newest connection from a duplicate IP.
760 static void kill_some_child(void)
762 const struct child *blanket, *next;
764 if (!(blanket = firstborn))
767 for (; (next = blanket->next); blanket = next)
768 if (!addrcmp(&blanket->address, &next->address)) {
769 kill(blanket->cld.pid, SIGTERM);
774 static void check_dead_children(void)
779 struct child **cradle, *blanket;
780 for (cradle = &firstborn; (blanket = *cradle);)
781 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
782 const char *dead = "";
784 dead = " (with error)";
785 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
787 /* remove the child */
788 *cradle = blanket->next;
792 cradle = &blanket->next;
795 static char **cld_argv;
796 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
798 struct child_process cld = CHILD_PROCESS_INIT;
799 char addrbuf[300] = "REMOTE_ADDR=", portbuf[300];
800 char *env[] = { addrbuf, portbuf, NULL };
802 if (max_connections && live_children >= max_connections) {
804 sleep(1); /* give it some time to die */
805 check_dead_children();
806 if (live_children >= max_connections) {
808 logerror("Too many children, dropping connection");
813 if (addr->sa_family == AF_INET) {
814 struct sockaddr_in *sin_addr = (void *) addr;
815 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf + 12,
816 sizeof(addrbuf) - 12);
817 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
818 ntohs(sin_addr->sin_port));
820 } else if (addr->sa_family == AF_INET6) {
821 struct sockaddr_in6 *sin6_addr = (void *) addr;
823 char *buf = addrbuf + 12;
824 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
825 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf,
826 sizeof(addrbuf) - 13);
829 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
830 ntohs(sin6_addr->sin6_port));
834 cld.env = (const char **)env;
835 cld.argv = (const char **)cld_argv;
837 cld.out = dup(incoming);
839 if (start_command(&cld))
840 logerror("unable to fork");
842 add_child(&cld, addr, addrlen);
845 static void child_handler(int signo)
848 * Otherwise empty handler because systemcalls will get interrupted
849 * upon signal receipt
850 * SysV needs the handler to be rearmed
852 signal(SIGCHLD, child_handler);
855 static int set_reuse_addr(int sockfd)
861 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
871 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
874 static char ip[INET_ADDRSTRLEN];
876 static char ip[INET6_ADDRSTRLEN];
882 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
886 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
889 strcpy(ip, "<unknown>");
896 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
899 char pbuf[NI_MAXSERV];
900 struct addrinfo hints, *ai0, *ai;
904 sprintf(pbuf, "%d", listen_port);
905 memset(&hints, 0, sizeof(hints));
906 hints.ai_family = AF_UNSPEC;
907 hints.ai_socktype = SOCK_STREAM;
908 hints.ai_protocol = IPPROTO_TCP;
909 hints.ai_flags = AI_PASSIVE;
911 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
913 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
917 for (ai = ai0; ai; ai = ai->ai_next) {
920 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
923 if (sockfd >= FD_SETSIZE) {
924 logerror("Socket descriptor too large");
930 if (ai->ai_family == AF_INET6) {
932 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
934 /* Note: error is not fatal */
938 if (set_reuse_addr(sockfd)) {
939 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
944 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
945 logerror("Could not bind to %s: %s",
946 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
949 continue; /* not fatal */
951 if (listen(sockfd, 5) < 0) {
952 logerror("Could not listen to %s: %s",
953 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
956 continue; /* not fatal */
959 flags = fcntl(sockfd, F_GETFD, 0);
961 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
963 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
964 socklist->list[socklist->nr++] = sockfd;
975 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
977 struct sockaddr_in sin;
981 memset(&sin, 0, sizeof sin);
982 sin.sin_family = AF_INET;
983 sin.sin_port = htons(listen_port);
986 /* Well, host better be an IP address here. */
987 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
990 sin.sin_addr.s_addr = htonl(INADDR_ANY);
993 sockfd = socket(AF_INET, SOCK_STREAM, 0);
997 if (set_reuse_addr(sockfd)) {
998 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1003 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
1004 logerror("Could not bind to %s: %s",
1005 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1011 if (listen(sockfd, 5) < 0) {
1012 logerror("Could not listen to %s: %s",
1013 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1019 flags = fcntl(sockfd, F_GETFD, 0);
1021 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1023 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1024 socklist->list[socklist->nr++] = sockfd;
1030 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
1032 if (!listen_addr->nr)
1033 setup_named_sock(NULL, listen_port, socklist);
1036 for (i = 0; i < listen_addr->nr; i++) {
1037 socknum = setup_named_sock(listen_addr->items[i].string,
1038 listen_port, socklist);
1041 logerror("unable to allocate any listen sockets for host %s on port %u",
1042 listen_addr->items[i].string, listen_port);
1047 static int service_loop(struct socketlist *socklist)
1052 pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
1054 for (i = 0; i < socklist->nr; i++) {
1055 pfd[i].fd = socklist->list[i];
1056 pfd[i].events = POLLIN;
1059 signal(SIGCHLD, child_handler);
1064 check_dead_children();
1066 if (poll(pfd, socklist->nr, -1) < 0) {
1067 if (errno != EINTR) {
1068 logerror("Poll failed, resuming: %s",
1075 for (i = 0; i < socklist->nr; i++) {
1076 if (pfd[i].revents & POLLIN) {
1079 struct sockaddr_in sai;
1081 struct sockaddr_in6 sai6;
1084 socklen_t sslen = sizeof(ss);
1085 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1093 die_errno("accept returned");
1096 handle(incoming, &ss.sa, sslen);
1102 #ifdef NO_POSIX_GOODIES
1106 static void drop_privileges(struct credentials *cred)
1111 static struct credentials *prepare_credentials(const char *user_name,
1112 const char *group_name)
1114 die("--user not supported on this platform");
1119 struct credentials {
1120 struct passwd *pass;
1124 static void drop_privileges(struct credentials *cred)
1126 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1127 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1128 die("cannot drop privileges");
1131 static struct credentials *prepare_credentials(const char *user_name,
1132 const char *group_name)
1134 static struct credentials c;
1136 c.pass = getpwnam(user_name);
1138 die("user not found - %s", user_name);
1141 c.gid = c.pass->pw_gid;
1143 struct group *group = getgrnam(group_name);
1145 die("group not found - %s", group_name);
1147 c.gid = group->gr_gid;
1154 static void store_pid(const char *path)
1156 FILE *f = fopen(path, "w");
1158 die_errno("cannot open pid file '%s'", path);
1159 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
1160 die_errno("failed to write pid file '%s'", path);
1163 static int serve(struct string_list *listen_addr, int listen_port,
1164 struct credentials *cred)
1166 struct socketlist socklist = { NULL, 0, 0 };
1168 socksetup(listen_addr, listen_port, &socklist);
1169 if (socklist.nr == 0)
1170 die("unable to allocate any listen sockets on port %u",
1173 drop_privileges(cred);
1175 loginfo("Ready to rumble");
1177 return service_loop(&socklist);
1180 int main(int argc, char **argv)
1182 int listen_port = 0;
1183 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1184 int serve_mode = 0, inetd_mode = 0;
1185 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1187 struct credentials *cred = NULL;
1190 git_setup_gettext();
1192 git_extract_argv0_path(argv[0]);
1194 for (i = 1; i < argc; i++) {
1195 char *arg = argv[i];
1198 if (skip_prefix(arg, "--listen=", &v)) {
1199 string_list_append(&listen_addr, xstrdup_tolower(v));
1202 if (skip_prefix(arg, "--port=", &v)) {
1205 n = strtoul(v, &end, 0);
1211 if (!strcmp(arg, "--serve")) {
1215 if (!strcmp(arg, "--inetd")) {
1220 if (!strcmp(arg, "--verbose")) {
1224 if (!strcmp(arg, "--syslog")) {
1228 if (!strcmp(arg, "--export-all")) {
1229 export_all_trees = 1;
1232 if (skip_prefix(arg, "--access-hook=", &v)) {
1236 if (skip_prefix(arg, "--timeout=", &v)) {
1240 if (skip_prefix(arg, "--init-timeout=", &v)) {
1241 init_timeout = atoi(v);
1244 if (skip_prefix(arg, "--max-connections=", &v)) {
1245 max_connections = atoi(v);
1246 if (max_connections < 0)
1247 max_connections = 0; /* unlimited */
1250 if (!strcmp(arg, "--strict-paths")) {
1254 if (skip_prefix(arg, "--base-path=", &v)) {
1258 if (!strcmp(arg, "--base-path-relaxed")) {
1259 base_path_relaxed = 1;
1262 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1263 interpolated_path = v;
1266 if (!strcmp(arg, "--reuseaddr")) {
1270 if (!strcmp(arg, "--user-path")) {
1274 if (skip_prefix(arg, "--user-path=", &v)) {
1278 if (skip_prefix(arg, "--pid-file=", &v)) {
1282 if (!strcmp(arg, "--detach")) {
1287 if (skip_prefix(arg, "--user=", &v)) {
1291 if (skip_prefix(arg, "--group=", &v)) {
1295 if (skip_prefix(arg, "--enable=", &v)) {
1296 enable_service(v, 1);
1299 if (skip_prefix(arg, "--disable=", &v)) {
1300 enable_service(v, 0);
1303 if (skip_prefix(arg, "--allow-override=", &v)) {
1304 make_service_overridable(v, 1);
1307 if (skip_prefix(arg, "--forbid-override=", &v)) {
1308 make_service_overridable(v, 0);
1311 if (!strcmp(arg, "--informative-errors")) {
1312 informative_errors = 1;
1315 if (!strcmp(arg, "--no-informative-errors")) {
1316 informative_errors = 0;
1319 if (!strcmp(arg, "--")) {
1320 ok_paths = &argv[i+1];
1322 } else if (arg[0] != '-') {
1323 ok_paths = &argv[i];
1327 usage(daemon_usage);
1331 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1332 set_die_routine(daemon_die);
1334 /* avoid splitting a message in the middle */
1335 setvbuf(stderr, NULL, _IOFBF, 4096);
1337 if (inetd_mode && (detach || group_name || user_name))
1338 die("--detach, --user and --group are incompatible with --inetd");
1340 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1341 die("--listen= and --port= are incompatible with --inetd");
1342 else if (listen_port == 0)
1343 listen_port = DEFAULT_GIT_PORT;
1345 if (group_name && !user_name)
1346 die("--group supplied without --user");
1349 cred = prepare_credentials(user_name, group_name);
1351 if (strict_paths && (!ok_paths || !*ok_paths))
1352 die("option --strict-paths requires a whitelist");
1354 if (base_path && !is_directory(base_path))
1355 die("base-path '%s' does not exist or is not a directory",
1359 if (!freopen("/dev/null", "w", stderr))
1360 die_errno("failed to redirect stderr to /dev/null");
1363 if (inetd_mode || serve_mode)
1368 die("--detach not supported on this platform");
1373 store_pid(pid_file);
1375 /* prepare argv for serving-processes */
1376 cld_argv = xmalloc(sizeof (char *) * (argc + 2));
1377 cld_argv[0] = argv[0]; /* git-daemon */
1378 cld_argv[1] = "--serve";
1379 for (i = 1; i < argc; ++i)
1380 cld_argv[i+1] = argv[i];
1381 cld_argv[argc+1] = NULL;
1383 return serve(&listen_addr, listen_port, cred);