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 char *hostname;
60 static char *canon_hostname;
61 static char *ip_address;
62 static char *tcp_port;
64 static int hostname_lookup_done;
66 static void lookup_hostname(void);
68 static const char *get_canon_hostname(void)
71 return canon_hostname;
74 static const char *get_ip_address(void)
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 static void strbuf_addstr_or_null(struct strbuf *sb, const char *s)
128 strbuf_addstr(sb, s);
131 struct expand_path_context {
132 const char *directory;
135 static size_t expand_path(struct strbuf *sb, const char *placeholder, void *ctx)
137 struct expand_path_context *context = ctx;
139 switch (placeholder[0]) {
141 strbuf_addstr_or_null(sb, hostname);
144 if (placeholder[1] == 'H') {
145 strbuf_addstr_or_null(sb, get_canon_hostname());
150 if (placeholder[1] == 'P') {
151 strbuf_addstr_or_null(sb, get_ip_address());
156 strbuf_addstr_or_null(sb, tcp_port);
159 strbuf_addstr(sb, context->directory);
165 static const char *path_ok(const char *directory)
167 static char rpath[PATH_MAX];
168 static char interp_path[PATH_MAX];
174 if (daemon_avoid_alias(dir)) {
175 logerror("'%s': aliased", dir);
181 logerror("'%s': User-path not allowed", dir);
185 /* Got either "~alice" or "~alice/foo";
186 * rewrite them to "~alice/%s" or
189 int namlen, restlen = strlen(dir);
190 const char *slash = strchr(dir, '/');
192 slash = dir + restlen;
193 namlen = slash - dir;
195 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
196 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
197 namlen, dir, user_path, restlen, slash);
201 else if (interpolated_path && saw_extended_args) {
202 struct strbuf expanded_path = STRBUF_INIT;
203 struct expand_path_context context;
205 context.directory = directory;
208 /* Allow only absolute */
209 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
213 strbuf_expand(&expanded_path, interpolated_path,
214 expand_path, &context);
215 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
216 strbuf_release(&expanded_path);
217 loginfo("Interpolated dir '%s'", interp_path);
221 else if (base_path) {
223 /* Allow only absolute */
224 logerror("'%s': Non-absolute path denied (base-path active)", dir);
227 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
231 path = enter_repo(dir, strict_paths);
232 if (!path && base_path && base_path_relaxed) {
234 * if we fail and base_path_relaxed is enabled, try without
235 * prefixing the base path
238 path = enter_repo(dir, strict_paths);
242 logerror("'%s' does not appear to be a git repository", dir);
246 if ( ok_paths && *ok_paths ) {
248 int pathlen = strlen(path);
250 /* The validation is done on the paths after enter_repo
251 * appends optional {.git,.git/.git} and friends, but
252 * it does not use getcwd(). So if your /pub is
253 * a symlink to /mnt/pub, you can whitelist /pub and
254 * do not have to say /mnt/pub.
257 for ( pp = ok_paths ; *pp ; pp++ ) {
258 int len = strlen(*pp);
259 if (len <= pathlen &&
260 !memcmp(*pp, path, len) &&
261 (path[len] == '\0' ||
262 (!strict_paths && path[len] == '/')))
267 /* be backwards compatible */
272 logerror("'%s': not in whitelist", path);
273 return NULL; /* Fallthrough. Deny by default */
276 typedef int (*daemon_service_fn)(void);
277 struct daemon_service {
279 const char *config_name;
280 daemon_service_fn fn;
285 static int daemon_error(const char *dir, const char *msg)
287 if (!informative_errors)
288 msg = "access denied or repository not exported";
289 packet_write(1, "ERR %s: %s", msg, dir);
293 static const char *access_hook;
295 static int run_access_hook(struct daemon_service *service, const char *dir, const char *path)
297 struct child_process child = CHILD_PROCESS_INIT;
298 struct strbuf buf = STRBUF_INIT;
300 const char **arg = argv;
304 #define STRARG(x) ((x) ? (x) : "")
305 *arg++ = access_hook;
306 *arg++ = service->name;
308 *arg++ = STRARG(hostname);
309 *arg++ = STRARG(get_canon_hostname());
310 *arg++ = STRARG(get_ip_address());
311 *arg++ = STRARG(tcp_port);
320 if (start_command(&child)) {
321 logerror("daemon access hook '%s' failed to start",
325 if (strbuf_read(&buf, child.out, 0) < 0) {
326 logerror("failed to read from pipe to daemon access hook '%s'",
331 if (close(child.out) < 0) {
332 logerror("failed to close pipe to daemon access hook '%s'",
336 if (finish_command(&child))
340 strbuf_release(&buf);
347 strbuf_addstr(&buf, "service rejected");
348 eol = strchr(buf.buf, '\n');
352 daemon_error(dir, buf.buf);
353 strbuf_release(&buf);
357 static int run_service(const char *dir, struct daemon_service *service)
360 int enabled = service->enabled;
361 struct strbuf var = STRBUF_INIT;
363 loginfo("Request %s for '%s'", service->name, dir);
365 if (!enabled && !service->overridable) {
366 logerror("'%s': service not enabled.", service->name);
368 return daemon_error(dir, "service not enabled");
371 if (!(path = path_ok(dir)))
372 return daemon_error(dir, "no such repository");
375 * Security on the cheap.
377 * We want a readable HEAD, usable "objects" directory, and
378 * a "git-daemon-export-ok" flag that says that the other side
379 * is ok with us doing this.
381 * path_ok() uses enter_repo() and does whitelist checking.
382 * We only need to make sure the repository is exported.
385 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
386 logerror("'%s': repository not exported.", path);
388 return daemon_error(dir, "repository not exported");
391 if (service->overridable) {
392 strbuf_addf(&var, "daemon.%s", service->config_name);
393 git_config_get_bool(var.buf, &enabled);
394 strbuf_release(&var);
397 logerror("'%s': service not enabled for '%s'",
398 service->name, path);
400 return daemon_error(dir, "service not enabled");
404 * Optionally, a hook can choose to deny access to the
405 * repository depending on the phase of the moon.
407 if (access_hook && run_access_hook(service, dir, path))
411 * We'll ignore SIGTERM from now on, we have a
414 signal(SIGTERM, SIG_IGN);
416 return service->fn();
419 static void copy_to_log(int fd)
421 struct strbuf line = STRBUF_INIT;
424 fp = fdopen(fd, "r");
426 logerror("fdopen of error channel failed");
431 while (strbuf_getline(&line, fp, '\n') != EOF) {
432 logerror("%s", line.buf);
433 strbuf_setlen(&line, 0);
436 strbuf_release(&line);
440 static int run_service_command(const char **argv)
442 struct child_process cld = CHILD_PROCESS_INIT;
447 if (start_command(&cld))
453 copy_to_log(cld.err);
455 return finish_command(&cld);
458 static int upload_pack(void)
460 /* Timeout as string */
461 char timeout_buf[64];
462 const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
464 argv[2] = timeout_buf;
466 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
467 return run_service_command(argv);
470 static int upload_archive(void)
472 static const char *argv[] = { "upload-archive", ".", NULL };
473 return run_service_command(argv);
476 static int receive_pack(void)
478 static const char *argv[] = { "receive-pack", ".", NULL };
479 return run_service_command(argv);
482 static struct daemon_service daemon_service[] = {
483 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
484 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
485 { "receive-pack", "receivepack", receive_pack, 0, 1 },
488 static void enable_service(const char *name, int ena)
491 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
492 if (!strcmp(daemon_service[i].name, name)) {
493 daemon_service[i].enabled = ena;
497 die("No such service %s", name);
500 static void make_service_overridable(const char *name, int ena)
503 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
504 if (!strcmp(daemon_service[i].name, name)) {
505 daemon_service[i].overridable = ena;
509 die("No such service %s", name);
512 static void parse_host_and_port(char *hostport, char **host,
515 if (*hostport == '[') {
518 end = strchr(hostport, ']');
520 die("Invalid request ('[' without ']')");
522 *host = hostport + 1;
525 else if (end[1] == ':')
528 die("Garbage after end of host part");
531 *port = strrchr(hostport, ':');
540 * Sanitize a string from the client so that it's OK to be inserted into a
541 * filesystem path. Specifically, we disallow slashes, runs of "..", and
542 * trailing and leading dots, which means that the client cannot escape
543 * our base path via ".." traversal.
545 static void sanitize_client_strbuf(struct strbuf *out, const char *in)
550 if (*in == '.' && (!out->len || out->buf[out->len - 1] == '.'))
552 strbuf_addch(out, *in);
555 while (out->len && out->buf[out->len - 1] == '.')
556 strbuf_setlen(out, out->len - 1);
559 static char *sanitize_client(const char *in)
561 struct strbuf out = STRBUF_INIT;
562 sanitize_client_strbuf(&out, in);
563 return strbuf_detach(&out, NULL);
567 * Like sanitize_client, but we also perform any canonicalization
568 * to make life easier on the admin.
570 static char *canonicalize_client(const char *in)
572 struct strbuf out = STRBUF_INIT;
573 sanitize_client_strbuf(&out, in);
574 strbuf_tolower(&out);
575 return strbuf_detach(&out, NULL);
579 * Read the host as supplied by the client connection.
581 static void parse_host_arg(char *extra_args, int buflen)
585 char *end = extra_args + buflen;
587 if (extra_args < end && *extra_args) {
588 saw_extended_args = 1;
589 if (strncasecmp("host=", extra_args, 5) == 0) {
590 val = extra_args + 5;
591 vallen = strlen(val) + 1;
593 /* Split <host>:<port> at colon. */
596 parse_host_and_port(val, &host, &port);
599 tcp_port = sanitize_client(port);
602 hostname = canonicalize_client(host);
603 hostname_lookup_done = 0;
606 /* On to the next one */
607 extra_args = val + vallen;
609 if (extra_args < end && *extra_args)
610 die("Invalid request");
615 * Locate canonical hostname and its IP address.
617 static void lookup_hostname(void)
619 if (!hostname_lookup_done && hostname) {
621 struct addrinfo hints;
624 static char addrbuf[HOST_NAME_MAX + 1];
626 memset(&hints, 0, sizeof(hints));
627 hints.ai_flags = AI_CANONNAME;
629 gai = getaddrinfo(hostname, NULL, &hints, &ai);
631 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
633 inet_ntop(AF_INET, &sin_addr->sin_addr,
634 addrbuf, sizeof(addrbuf));
636 ip_address = xstrdup(addrbuf);
638 free(canon_hostname);
639 canon_hostname = ai->ai_canonname ?
640 sanitize_client(ai->ai_canonname) :
646 struct hostent *hent;
647 struct sockaddr_in sa;
649 static char addrbuf[HOST_NAME_MAX + 1];
651 hent = gethostbyname(hostname);
653 ap = hent->h_addr_list;
654 memset(&sa, 0, sizeof sa);
655 sa.sin_family = hent->h_addrtype;
656 sa.sin_port = htons(0);
657 memcpy(&sa.sin_addr, *ap, hent->h_length);
659 inet_ntop(hent->h_addrtype, &sa.sin_addr,
660 addrbuf, sizeof(addrbuf));
662 free(canon_hostname);
663 canon_hostname = sanitize_client(hent->h_name);
665 ip_address = xstrdup(addrbuf);
668 hostname_lookup_done = 1;
673 static int execute(void)
675 char *line = packet_buffer;
677 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
680 loginfo("Connection from %s:%s", addr, port);
682 alarm(init_timeout ? init_timeout : timeout);
683 pktlen = packet_read(0, NULL, NULL, packet_buffer, sizeof(packet_buffer), 0);
688 loginfo("Extended attributes (%d bytes) exist <%.*s>",
690 (int) pktlen - len, line + len + 1);
691 if (len && line[len-1] == '\n') {
697 free(canon_hostname);
700 hostname = canon_hostname = ip_address = tcp_port = NULL;
703 parse_host_arg(line + len + 1, pktlen - len - 1);
705 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
706 struct daemon_service *s = &(daemon_service[i]);
709 if (skip_prefix(line, "git-", &arg) &&
710 skip_prefix(arg, s->name, &arg) &&
713 * Note: The directory here is probably context sensitive,
714 * and might depend on the actual service being performed.
716 return run_service(arg, s);
720 logerror("Protocol error: '%s'", line);
724 static int addrcmp(const struct sockaddr_storage *s1,
725 const struct sockaddr_storage *s2)
727 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
728 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
730 if (sa1->sa_family != sa2->sa_family)
731 return sa1->sa_family - sa2->sa_family;
732 if (sa1->sa_family == AF_INET)
733 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
734 &((struct sockaddr_in *)s2)->sin_addr,
735 sizeof(struct in_addr));
737 if (sa1->sa_family == AF_INET6)
738 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
739 &((struct sockaddr_in6 *)s2)->sin6_addr,
740 sizeof(struct in6_addr));
745 static int max_connections = 32;
747 static unsigned int live_children;
749 static struct child {
751 struct child_process cld;
752 struct sockaddr_storage address;
755 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
757 struct child *newborn, **cradle;
759 newborn = xcalloc(1, sizeof(*newborn));
761 memcpy(&newborn->cld, cld, sizeof(*cld));
762 memcpy(&newborn->address, addr, addrlen);
763 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
764 if (!addrcmp(&(*cradle)->address, &newborn->address))
766 newborn->next = *cradle;
771 * This gets called if the number of connections grows
772 * past "max_connections".
774 * We kill the newest connection from a duplicate IP.
776 static void kill_some_child(void)
778 const struct child *blanket, *next;
780 if (!(blanket = firstborn))
783 for (; (next = blanket->next); blanket = next)
784 if (!addrcmp(&blanket->address, &next->address)) {
785 kill(blanket->cld.pid, SIGTERM);
790 static void check_dead_children(void)
795 struct child **cradle, *blanket;
796 for (cradle = &firstborn; (blanket = *cradle);)
797 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
798 const char *dead = "";
800 dead = " (with error)";
801 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
803 /* remove the child */
804 *cradle = blanket->next;
808 cradle = &blanket->next;
811 static char **cld_argv;
812 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
814 struct child_process cld = CHILD_PROCESS_INIT;
815 char addrbuf[300] = "REMOTE_ADDR=", portbuf[300];
816 char *env[] = { addrbuf, portbuf, NULL };
818 if (max_connections && live_children >= max_connections) {
820 sleep(1); /* give it some time to die */
821 check_dead_children();
822 if (live_children >= max_connections) {
824 logerror("Too many children, dropping connection");
829 if (addr->sa_family == AF_INET) {
830 struct sockaddr_in *sin_addr = (void *) addr;
831 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf + 12,
832 sizeof(addrbuf) - 12);
833 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
834 ntohs(sin_addr->sin_port));
836 } else if (addr->sa_family == AF_INET6) {
837 struct sockaddr_in6 *sin6_addr = (void *) addr;
839 char *buf = addrbuf + 12;
840 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
841 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf,
842 sizeof(addrbuf) - 13);
845 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
846 ntohs(sin6_addr->sin6_port));
850 cld.env = (const char **)env;
851 cld.argv = (const char **)cld_argv;
853 cld.out = dup(incoming);
855 if (start_command(&cld))
856 logerror("unable to fork");
858 add_child(&cld, addr, addrlen);
861 static void child_handler(int signo)
864 * Otherwise empty handler because systemcalls will get interrupted
865 * upon signal receipt
866 * SysV needs the handler to be rearmed
868 signal(SIGCHLD, child_handler);
871 static int set_reuse_addr(int sockfd)
877 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
887 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
890 static char ip[INET_ADDRSTRLEN];
892 static char ip[INET6_ADDRSTRLEN];
898 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
902 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
905 strcpy(ip, "<unknown>");
912 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
915 char pbuf[NI_MAXSERV];
916 struct addrinfo hints, *ai0, *ai;
920 sprintf(pbuf, "%d", listen_port);
921 memset(&hints, 0, sizeof(hints));
922 hints.ai_family = AF_UNSPEC;
923 hints.ai_socktype = SOCK_STREAM;
924 hints.ai_protocol = IPPROTO_TCP;
925 hints.ai_flags = AI_PASSIVE;
927 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
929 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
933 for (ai = ai0; ai; ai = ai->ai_next) {
936 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
939 if (sockfd >= FD_SETSIZE) {
940 logerror("Socket descriptor too large");
946 if (ai->ai_family == AF_INET6) {
948 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
950 /* Note: error is not fatal */
954 if (set_reuse_addr(sockfd)) {
955 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
960 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
961 logerror("Could not bind to %s: %s",
962 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
965 continue; /* not fatal */
967 if (listen(sockfd, 5) < 0) {
968 logerror("Could not listen to %s: %s",
969 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
972 continue; /* not fatal */
975 flags = fcntl(sockfd, F_GETFD, 0);
977 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
979 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
980 socklist->list[socklist->nr++] = sockfd;
991 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
993 struct sockaddr_in sin;
997 memset(&sin, 0, sizeof sin);
998 sin.sin_family = AF_INET;
999 sin.sin_port = htons(listen_port);
1002 /* Well, host better be an IP address here. */
1003 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
1006 sin.sin_addr.s_addr = htonl(INADDR_ANY);
1009 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1013 if (set_reuse_addr(sockfd)) {
1014 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1019 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
1020 logerror("Could not bind to %s: %s",
1021 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1027 if (listen(sockfd, 5) < 0) {
1028 logerror("Could not listen to %s: %s",
1029 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1035 flags = fcntl(sockfd, F_GETFD, 0);
1037 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1039 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1040 socklist->list[socklist->nr++] = sockfd;
1046 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
1048 if (!listen_addr->nr)
1049 setup_named_sock(NULL, listen_port, socklist);
1052 for (i = 0; i < listen_addr->nr; i++) {
1053 socknum = setup_named_sock(listen_addr->items[i].string,
1054 listen_port, socklist);
1057 logerror("unable to allocate any listen sockets for host %s on port %u",
1058 listen_addr->items[i].string, listen_port);
1063 static int service_loop(struct socketlist *socklist)
1068 pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
1070 for (i = 0; i < socklist->nr; i++) {
1071 pfd[i].fd = socklist->list[i];
1072 pfd[i].events = POLLIN;
1075 signal(SIGCHLD, child_handler);
1080 check_dead_children();
1082 if (poll(pfd, socklist->nr, -1) < 0) {
1083 if (errno != EINTR) {
1084 logerror("Poll failed, resuming: %s",
1091 for (i = 0; i < socklist->nr; i++) {
1092 if (pfd[i].revents & POLLIN) {
1095 struct sockaddr_in sai;
1097 struct sockaddr_in6 sai6;
1100 socklen_t sslen = sizeof(ss);
1101 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1109 die_errno("accept returned");
1112 handle(incoming, &ss.sa, sslen);
1118 #ifdef NO_POSIX_GOODIES
1122 static void drop_privileges(struct credentials *cred)
1127 static struct credentials *prepare_credentials(const char *user_name,
1128 const char *group_name)
1130 die("--user not supported on this platform");
1135 struct credentials {
1136 struct passwd *pass;
1140 static void drop_privileges(struct credentials *cred)
1142 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1143 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1144 die("cannot drop privileges");
1147 static struct credentials *prepare_credentials(const char *user_name,
1148 const char *group_name)
1150 static struct credentials c;
1152 c.pass = getpwnam(user_name);
1154 die("user not found - %s", user_name);
1157 c.gid = c.pass->pw_gid;
1159 struct group *group = getgrnam(group_name);
1161 die("group not found - %s", group_name);
1163 c.gid = group->gr_gid;
1170 static void store_pid(const char *path)
1172 FILE *f = fopen(path, "w");
1174 die_errno("cannot open pid file '%s'", path);
1175 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
1176 die_errno("failed to write pid file '%s'", path);
1179 static int serve(struct string_list *listen_addr, int listen_port,
1180 struct credentials *cred)
1182 struct socketlist socklist = { NULL, 0, 0 };
1184 socksetup(listen_addr, listen_port, &socklist);
1185 if (socklist.nr == 0)
1186 die("unable to allocate any listen sockets on port %u",
1189 drop_privileges(cred);
1191 loginfo("Ready to rumble");
1193 return service_loop(&socklist);
1196 int main(int argc, char **argv)
1198 int listen_port = 0;
1199 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1200 int serve_mode = 0, inetd_mode = 0;
1201 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1203 struct credentials *cred = NULL;
1206 git_setup_gettext();
1208 git_extract_argv0_path(argv[0]);
1210 for (i = 1; i < argc; i++) {
1211 char *arg = argv[i];
1214 if (skip_prefix(arg, "--listen=", &v)) {
1215 string_list_append(&listen_addr, xstrdup_tolower(v));
1218 if (skip_prefix(arg, "--port=", &v)) {
1221 n = strtoul(v, &end, 0);
1227 if (!strcmp(arg, "--serve")) {
1231 if (!strcmp(arg, "--inetd")) {
1236 if (!strcmp(arg, "--verbose")) {
1240 if (!strcmp(arg, "--syslog")) {
1244 if (!strcmp(arg, "--export-all")) {
1245 export_all_trees = 1;
1248 if (skip_prefix(arg, "--access-hook=", &v)) {
1252 if (skip_prefix(arg, "--timeout=", &v)) {
1256 if (skip_prefix(arg, "--init-timeout=", &v)) {
1257 init_timeout = atoi(v);
1260 if (skip_prefix(arg, "--max-connections=", &v)) {
1261 max_connections = atoi(v);
1262 if (max_connections < 0)
1263 max_connections = 0; /* unlimited */
1266 if (!strcmp(arg, "--strict-paths")) {
1270 if (skip_prefix(arg, "--base-path=", &v)) {
1274 if (!strcmp(arg, "--base-path-relaxed")) {
1275 base_path_relaxed = 1;
1278 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1279 interpolated_path = v;
1282 if (!strcmp(arg, "--reuseaddr")) {
1286 if (!strcmp(arg, "--user-path")) {
1290 if (skip_prefix(arg, "--user-path=", &v)) {
1294 if (skip_prefix(arg, "--pid-file=", &v)) {
1298 if (!strcmp(arg, "--detach")) {
1303 if (skip_prefix(arg, "--user=", &v)) {
1307 if (skip_prefix(arg, "--group=", &v)) {
1311 if (skip_prefix(arg, "--enable=", &v)) {
1312 enable_service(v, 1);
1315 if (skip_prefix(arg, "--disable=", &v)) {
1316 enable_service(v, 0);
1319 if (skip_prefix(arg, "--allow-override=", &v)) {
1320 make_service_overridable(v, 1);
1323 if (skip_prefix(arg, "--forbid-override=", &v)) {
1324 make_service_overridable(v, 0);
1327 if (!strcmp(arg, "--informative-errors")) {
1328 informative_errors = 1;
1331 if (!strcmp(arg, "--no-informative-errors")) {
1332 informative_errors = 0;
1335 if (!strcmp(arg, "--")) {
1336 ok_paths = &argv[i+1];
1338 } else if (arg[0] != '-') {
1339 ok_paths = &argv[i];
1343 usage(daemon_usage);
1347 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1348 set_die_routine(daemon_die);
1350 /* avoid splitting a message in the middle */
1351 setvbuf(stderr, NULL, _IOFBF, 4096);
1353 if (inetd_mode && (detach || group_name || user_name))
1354 die("--detach, --user and --group are incompatible with --inetd");
1356 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1357 die("--listen= and --port= are incompatible with --inetd");
1358 else if (listen_port == 0)
1359 listen_port = DEFAULT_GIT_PORT;
1361 if (group_name && !user_name)
1362 die("--group supplied without --user");
1365 cred = prepare_credentials(user_name, group_name);
1367 if (strict_paths && (!ok_paths || !*ok_paths))
1368 die("option --strict-paths requires a whitelist");
1370 if (base_path && !is_directory(base_path))
1371 die("base-path '%s' does not exist or is not a directory",
1375 if (!freopen("/dev/null", "w", stderr))
1376 die_errno("failed to redirect stderr to /dev/null");
1379 if (inetd_mode || serve_mode)
1384 die("--detach not supported on this platform");
1389 store_pid(pid_file);
1391 /* prepare argv for serving-processes */
1392 cld_argv = xmalloc(sizeof (char *) * (argc + 2));
1393 cld_argv[0] = argv[0]; /* git-daemon */
1394 cld_argv[1] = "--serve";
1395 for (i = 1; i < argc; ++i)
1396 cld_argv[i+1] = argv[i];
1397 cld_argv[argc+1] = NULL;
1399 return serve(&listen_addr, listen_port, cred);