3 #include "run-command.h"
5 #include "string-list.h"
8 #define HOST_NAME_MAX 256
12 #define initgroups(x, y) (0) /* nothing */
15 static int log_syslog;
18 static int informative_errors;
20 static const char daemon_usage[] =
21 "git daemon [--verbose] [--syslog] [--export-all]\n"
22 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
23 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
24 " [--user-path | --user-path=<path>]\n"
25 " [--interpolated-path=<path>]\n"
26 " [--reuseaddr] [--pid-file=<file>]\n"
27 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
28 " [--access-hook=<path>]\n"
29 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
30 " [--detach] [--user=<user> [--group=<group>]]\n"
33 /* List of acceptable pathname prefixes */
34 static const char **ok_paths;
35 static int strict_paths;
37 /* If this is set, git-daemon-export-ok is not required */
38 static int export_all_trees;
40 /* Take all paths relative to this one if non-NULL */
41 static const char *base_path;
42 static const char *interpolated_path;
43 static int base_path_relaxed;
45 /* If defined, ~user notation is allowed and the string is inserted
46 * after ~user/. E.g. a request to git://host/~alice/frotz would
47 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
49 static const char *user_path;
51 /* Timeout, and initial timeout */
52 static unsigned int timeout;
53 static unsigned int init_timeout;
56 struct strbuf hostname;
57 struct strbuf canon_hostname;
58 struct strbuf ip_address;
59 struct strbuf tcp_port;
60 unsigned int hostname_lookup_done:1;
61 unsigned int saw_extended_args:1;
64 static void lookup_hostname(struct hostinfo *hi);
66 static const char *get_canon_hostname(struct hostinfo *hi)
69 return hi->canon_hostname.buf;
72 static const char *get_ip_address(struct hostinfo *hi)
75 return hi->ip_address.buf;
78 static void logreport(int priority, const char *err, va_list params)
82 vsnprintf(buf, sizeof(buf), err, params);
83 syslog(priority, "%s", buf);
86 * Since stderr is set to buffered mode, the
87 * logging of different processes will not overlap
88 * unless they overflow the (rather big) buffers.
90 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
91 vfprintf(stderr, err, params);
97 __attribute__((format (printf, 1, 2)))
98 static void logerror(const char *err, ...)
101 va_start(params, err);
102 logreport(LOG_ERR, err, params);
106 __attribute__((format (printf, 1, 2)))
107 static void loginfo(const char *err, ...)
112 va_start(params, err);
113 logreport(LOG_INFO, err, params);
117 static void NORETURN daemon_die(const char *err, va_list params)
119 logreport(LOG_ERR, err, params);
123 struct expand_path_context {
124 const char *directory;
125 struct hostinfo *hostinfo;
128 static size_t expand_path(struct strbuf *sb, const char *placeholder, void *ctx)
130 struct expand_path_context *context = ctx;
131 struct hostinfo *hi = context->hostinfo;
133 switch (placeholder[0]) {
135 strbuf_addbuf(sb, &hi->hostname);
138 if (placeholder[1] == 'H') {
139 strbuf_addstr(sb, get_canon_hostname(hi));
144 if (placeholder[1] == 'P') {
145 strbuf_addstr(sb, get_ip_address(hi));
150 strbuf_addbuf(sb, &hi->tcp_port);
153 strbuf_addstr(sb, context->directory);
159 static const char *path_ok(const char *directory, struct hostinfo *hi)
161 static char rpath[PATH_MAX];
162 static char interp_path[PATH_MAX];
169 if (daemon_avoid_alias(dir)) {
170 logerror("'%s': aliased", dir);
176 logerror("'%s': User-path not allowed", dir);
180 /* Got either "~alice" or "~alice/foo";
181 * rewrite them to "~alice/%s" or
184 int namlen, restlen = strlen(dir);
185 const char *slash = strchr(dir, '/');
187 slash = dir + restlen;
188 namlen = slash - dir;
190 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
191 rlen = snprintf(rpath, sizeof(rpath), "%.*s/%s%.*s",
192 namlen, dir, user_path, restlen, slash);
193 if (rlen >= sizeof(rpath)) {
194 logerror("user-path too large: %s", rpath);
200 else if (interpolated_path && hi->saw_extended_args) {
201 struct strbuf expanded_path = STRBUF_INIT;
202 struct expand_path_context context;
204 context.directory = directory;
205 context.hostinfo = hi;
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);
216 rlen = strlcpy(interp_path, expanded_path.buf,
217 sizeof(interp_path));
218 if (rlen >= sizeof(interp_path)) {
219 logerror("interpolated path too large: %s",
224 strbuf_release(&expanded_path);
225 loginfo("Interpolated dir '%s'", interp_path);
229 else if (base_path) {
231 /* Allow only absolute */
232 logerror("'%s': Non-absolute path denied (base-path active)", dir);
235 rlen = snprintf(rpath, sizeof(rpath), "%s%s", base_path, dir);
236 if (rlen >= sizeof(rpath)) {
237 logerror("base-path too large: %s", rpath);
243 path = enter_repo(dir, strict_paths);
244 if (!path && base_path && base_path_relaxed) {
246 * if we fail and base_path_relaxed is enabled, try without
247 * prefixing the base path
250 path = enter_repo(dir, strict_paths);
254 logerror("'%s' does not appear to be a git repository", dir);
258 if ( ok_paths && *ok_paths ) {
260 int pathlen = strlen(path);
262 /* The validation is done on the paths after enter_repo
263 * appends optional {.git,.git/.git} and friends, but
264 * it does not use getcwd(). So if your /pub is
265 * a symlink to /mnt/pub, you can whitelist /pub and
266 * do not have to say /mnt/pub.
269 for ( pp = ok_paths ; *pp ; pp++ ) {
270 int len = strlen(*pp);
271 if (len <= pathlen &&
272 !memcmp(*pp, path, len) &&
273 (path[len] == '\0' ||
274 (!strict_paths && path[len] == '/')))
279 /* be backwards compatible */
284 logerror("'%s': not in whitelist", path);
285 return NULL; /* Fallthrough. Deny by default */
288 typedef int (*daemon_service_fn)(void);
289 struct daemon_service {
291 const char *config_name;
292 daemon_service_fn fn;
297 static int daemon_error(const char *dir, const char *msg)
299 if (!informative_errors)
300 msg = "access denied or repository not exported";
301 packet_write_fmt(1, "ERR %s: %s", msg, dir);
305 static const char *access_hook;
307 static int run_access_hook(struct daemon_service *service, const char *dir,
308 const char *path, struct hostinfo *hi)
310 struct child_process child = CHILD_PROCESS_INIT;
311 struct strbuf buf = STRBUF_INIT;
313 const char **arg = argv;
317 *arg++ = access_hook;
318 *arg++ = service->name;
320 *arg++ = hi->hostname.buf;
321 *arg++ = get_canon_hostname(hi);
322 *arg++ = get_ip_address(hi);
323 *arg++ = hi->tcp_port.buf;
331 if (start_command(&child)) {
332 logerror("daemon access hook '%s' failed to start",
336 if (strbuf_read(&buf, child.out, 0) < 0) {
337 logerror("failed to read from pipe to daemon access hook '%s'",
342 if (close(child.out) < 0) {
343 logerror("failed to close pipe to daemon access hook '%s'",
347 if (finish_command(&child))
351 strbuf_release(&buf);
358 strbuf_addstr(&buf, "service rejected");
359 eol = strchr(buf.buf, '\n');
363 daemon_error(dir, buf.buf);
364 strbuf_release(&buf);
368 static int run_service(const char *dir, struct daemon_service *service,
372 int enabled = service->enabled;
373 struct strbuf var = STRBUF_INIT;
375 loginfo("Request %s for '%s'", service->name, dir);
377 if (!enabled && !service->overridable) {
378 logerror("'%s': service not enabled.", service->name);
380 return daemon_error(dir, "service not enabled");
383 if (!(path = path_ok(dir, hi)))
384 return daemon_error(dir, "no such repository");
387 * Security on the cheap.
389 * We want a readable HEAD, usable "objects" directory, and
390 * a "git-daemon-export-ok" flag that says that the other side
391 * is ok with us doing this.
393 * path_ok() uses enter_repo() and does whitelist checking.
394 * We only need to make sure the repository is exported.
397 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
398 logerror("'%s': repository not exported.", path);
400 return daemon_error(dir, "repository not exported");
403 if (service->overridable) {
404 strbuf_addf(&var, "daemon.%s", service->config_name);
405 git_config_get_bool(var.buf, &enabled);
406 strbuf_release(&var);
409 logerror("'%s': service not enabled for '%s'",
410 service->name, path);
412 return daemon_error(dir, "service not enabled");
416 * Optionally, a hook can choose to deny access to the
417 * repository depending on the phase of the moon.
419 if (access_hook && run_access_hook(service, dir, path, hi))
423 * We'll ignore SIGTERM from now on, we have a
426 signal(SIGTERM, SIG_IGN);
428 return service->fn();
431 static void copy_to_log(int fd)
433 struct strbuf line = STRBUF_INIT;
436 fp = fdopen(fd, "r");
438 logerror("fdopen of error channel failed");
443 while (strbuf_getline_lf(&line, fp) != EOF) {
444 logerror("%s", line.buf);
445 strbuf_setlen(&line, 0);
448 strbuf_release(&line);
452 static int run_service_command(struct child_process *cld)
454 argv_array_push(&cld->args, ".");
457 if (start_command(cld))
463 copy_to_log(cld->err);
465 return finish_command(cld);
468 static int upload_pack(void)
470 struct child_process cld = CHILD_PROCESS_INIT;
471 argv_array_pushl(&cld.args, "upload-pack", "--strict", NULL);
472 argv_array_pushf(&cld.args, "--timeout=%u", timeout);
473 return run_service_command(&cld);
476 static int upload_archive(void)
478 struct child_process cld = CHILD_PROCESS_INIT;
479 argv_array_push(&cld.args, "upload-archive");
480 return run_service_command(&cld);
483 static int receive_pack(void)
485 struct child_process cld = CHILD_PROCESS_INIT;
486 argv_array_push(&cld.args, "receive-pack");
487 return run_service_command(&cld);
490 static struct daemon_service daemon_service[] = {
491 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
492 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
493 { "receive-pack", "receivepack", receive_pack, 0, 1 },
496 static void enable_service(const char *name, int ena)
499 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
500 if (!strcmp(daemon_service[i].name, name)) {
501 daemon_service[i].enabled = ena;
505 die("No such service %s", name);
508 static void make_service_overridable(const char *name, int ena)
511 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
512 if (!strcmp(daemon_service[i].name, name)) {
513 daemon_service[i].overridable = ena;
517 die("No such service %s", name);
520 static void parse_host_and_port(char *hostport, char **host,
523 if (*hostport == '[') {
526 end = strchr(hostport, ']');
528 die("Invalid request ('[' without ']')");
530 *host = hostport + 1;
533 else if (end[1] == ':')
536 die("Garbage after end of host part");
539 *port = strrchr(hostport, ':');
548 * Sanitize a string from the client so that it's OK to be inserted into a
549 * filesystem path. Specifically, we disallow slashes, runs of "..", and
550 * trailing and leading dots, which means that the client cannot escape
551 * our base path via ".." traversal.
553 static void sanitize_client(struct strbuf *out, const char *in)
558 if (*in == '.' && (!out->len || out->buf[out->len - 1] == '.'))
560 strbuf_addch(out, *in);
563 while (out->len && out->buf[out->len - 1] == '.')
564 strbuf_setlen(out, out->len - 1);
568 * Like sanitize_client, but we also perform any canonicalization
569 * to make life easier on the admin.
571 static void canonicalize_client(struct strbuf *out, const char *in)
573 sanitize_client(out, in);
578 * Read the host as supplied by the client connection.
580 static void parse_host_arg(struct hostinfo *hi, char *extra_args, int buflen)
584 char *end = extra_args + buflen;
586 if (extra_args < end && *extra_args) {
587 hi->saw_extended_args = 1;
588 if (strncasecmp("host=", extra_args, 5) == 0) {
589 val = extra_args + 5;
590 vallen = strlen(val) + 1;
592 /* Split <host>:<port> at colon. */
595 parse_host_and_port(val, &host, &port);
597 sanitize_client(&hi->tcp_port, port);
598 canonicalize_client(&hi->hostname, host);
599 hi->hostname_lookup_done = 0;
602 /* On to the next one */
603 extra_args = val + vallen;
605 if (extra_args < end && *extra_args)
606 die("Invalid request");
611 * Locate canonical hostname and its IP address.
613 static void lookup_hostname(struct hostinfo *hi)
615 if (!hi->hostname_lookup_done && hi->hostname.len) {
617 struct addrinfo hints;
620 static char addrbuf[HOST_NAME_MAX + 1];
622 memset(&hints, 0, sizeof(hints));
623 hints.ai_flags = AI_CANONNAME;
625 gai = getaddrinfo(hi->hostname.buf, NULL, &hints, &ai);
627 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
629 inet_ntop(AF_INET, &sin_addr->sin_addr,
630 addrbuf, sizeof(addrbuf));
631 strbuf_addstr(&hi->ip_address, addrbuf);
633 if (ai->ai_canonname)
634 sanitize_client(&hi->canon_hostname,
637 strbuf_addbuf(&hi->canon_hostname,
643 struct hostent *hent;
644 struct sockaddr_in sa;
646 static char addrbuf[HOST_NAME_MAX + 1];
648 hent = gethostbyname(hi->hostname.buf);
650 ap = hent->h_addr_list;
651 memset(&sa, 0, sizeof sa);
652 sa.sin_family = hent->h_addrtype;
653 sa.sin_port = htons(0);
654 memcpy(&sa.sin_addr, *ap, hent->h_length);
656 inet_ntop(hent->h_addrtype, &sa.sin_addr,
657 addrbuf, sizeof(addrbuf));
659 sanitize_client(&hi->canon_hostname, hent->h_name);
660 strbuf_addstr(&hi->ip_address, addrbuf);
663 hi->hostname_lookup_done = 1;
667 static void hostinfo_init(struct hostinfo *hi)
669 memset(hi, 0, sizeof(*hi));
670 strbuf_init(&hi->hostname, 0);
671 strbuf_init(&hi->canon_hostname, 0);
672 strbuf_init(&hi->ip_address, 0);
673 strbuf_init(&hi->tcp_port, 0);
676 static void hostinfo_clear(struct hostinfo *hi)
678 strbuf_release(&hi->hostname);
679 strbuf_release(&hi->canon_hostname);
680 strbuf_release(&hi->ip_address);
681 strbuf_release(&hi->tcp_port);
684 static void set_keep_alive(int sockfd)
688 if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0) {
689 if (errno != ENOTSOCK)
690 logerror("unable to set SO_KEEPALIVE on socket: %s",
695 static int execute(void)
697 char *line = packet_buffer;
699 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
705 loginfo("Connection from %s:%s", addr, port);
708 alarm(init_timeout ? init_timeout : timeout);
709 pktlen = packet_read(0, NULL, NULL, packet_buffer, sizeof(packet_buffer), 0);
714 loginfo("Extended attributes (%d bytes) exist <%.*s>",
716 (int) pktlen - len, line + len + 1);
717 if (len && line[len-1] == '\n') {
723 parse_host_arg(&hi, line + len + 1, pktlen - len - 1);
725 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
726 struct daemon_service *s = &(daemon_service[i]);
729 if (skip_prefix(line, "git-", &arg) &&
730 skip_prefix(arg, s->name, &arg) &&
733 * Note: The directory here is probably context sensitive,
734 * and might depend on the actual service being performed.
736 int rc = run_service(arg, s, &hi);
743 logerror("Protocol error: '%s'", line);
747 static int addrcmp(const struct sockaddr_storage *s1,
748 const struct sockaddr_storage *s2)
750 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
751 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
753 if (sa1->sa_family != sa2->sa_family)
754 return sa1->sa_family - sa2->sa_family;
755 if (sa1->sa_family == AF_INET)
756 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
757 &((struct sockaddr_in *)s2)->sin_addr,
758 sizeof(struct in_addr));
760 if (sa1->sa_family == AF_INET6)
761 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
762 &((struct sockaddr_in6 *)s2)->sin6_addr,
763 sizeof(struct in6_addr));
768 static int max_connections = 32;
770 static unsigned int live_children;
772 static struct child {
774 struct child_process cld;
775 struct sockaddr_storage address;
778 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
780 struct child *newborn, **cradle;
782 newborn = xcalloc(1, sizeof(*newborn));
784 memcpy(&newborn->cld, cld, sizeof(*cld));
785 memcpy(&newborn->address, addr, addrlen);
786 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
787 if (!addrcmp(&(*cradle)->address, &newborn->address))
789 newborn->next = *cradle;
794 * This gets called if the number of connections grows
795 * past "max_connections".
797 * We kill the newest connection from a duplicate IP.
799 static void kill_some_child(void)
801 const struct child *blanket, *next;
803 if (!(blanket = firstborn))
806 for (; (next = blanket->next); blanket = next)
807 if (!addrcmp(&blanket->address, &next->address)) {
808 kill(blanket->cld.pid, SIGTERM);
813 static void check_dead_children(void)
818 struct child **cradle, *blanket;
819 for (cradle = &firstborn; (blanket = *cradle);)
820 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
821 const char *dead = "";
823 dead = " (with error)";
824 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
826 /* remove the child */
827 *cradle = blanket->next;
829 child_process_clear(&blanket->cld);
832 cradle = &blanket->next;
835 static struct argv_array cld_argv = ARGV_ARRAY_INIT;
836 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
838 struct child_process cld = CHILD_PROCESS_INIT;
840 if (max_connections && live_children >= max_connections) {
842 sleep(1); /* give it some time to die */
843 check_dead_children();
844 if (live_children >= max_connections) {
846 logerror("Too many children, dropping connection");
851 if (addr->sa_family == AF_INET) {
853 struct sockaddr_in *sin_addr = (void *) addr;
854 inet_ntop(addr->sa_family, &sin_addr->sin_addr, buf, sizeof(buf));
855 argv_array_pushf(&cld.env_array, "REMOTE_ADDR=%s", buf);
856 argv_array_pushf(&cld.env_array, "REMOTE_PORT=%d",
857 ntohs(sin_addr->sin_port));
859 } else if (addr->sa_family == AF_INET6) {
861 struct sockaddr_in6 *sin6_addr = (void *) addr;
862 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(buf));
863 argv_array_pushf(&cld.env_array, "REMOTE_ADDR=[%s]", buf);
864 argv_array_pushf(&cld.env_array, "REMOTE_PORT=%d",
865 ntohs(sin6_addr->sin6_port));
869 cld.argv = cld_argv.argv;
871 cld.out = dup(incoming);
873 if (start_command(&cld))
874 logerror("unable to fork");
876 add_child(&cld, addr, addrlen);
879 static void child_handler(int signo)
882 * Otherwise empty handler because systemcalls will get interrupted
883 * upon signal receipt
884 * SysV needs the handler to be rearmed
886 signal(SIGCHLD, child_handler);
889 static int set_reuse_addr(int sockfd)
895 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
905 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
908 static char ip[INET_ADDRSTRLEN];
910 static char ip[INET6_ADDRSTRLEN];
916 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
920 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
923 xsnprintf(ip, sizeof(ip), "<unknown>");
930 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
933 char pbuf[NI_MAXSERV];
934 struct addrinfo hints, *ai0, *ai;
938 xsnprintf(pbuf, sizeof(pbuf), "%d", listen_port);
939 memset(&hints, 0, sizeof(hints));
940 hints.ai_family = AF_UNSPEC;
941 hints.ai_socktype = SOCK_STREAM;
942 hints.ai_protocol = IPPROTO_TCP;
943 hints.ai_flags = AI_PASSIVE;
945 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
947 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
951 for (ai = ai0; ai; ai = ai->ai_next) {
954 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
957 if (sockfd >= FD_SETSIZE) {
958 logerror("Socket descriptor too large");
964 if (ai->ai_family == AF_INET6) {
966 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
968 /* Note: error is not fatal */
972 if (set_reuse_addr(sockfd)) {
973 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
978 set_keep_alive(sockfd);
980 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
981 logerror("Could not bind to %s: %s",
982 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
985 continue; /* not fatal */
987 if (listen(sockfd, 5) < 0) {
988 logerror("Could not listen to %s: %s",
989 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
992 continue; /* not fatal */
995 flags = fcntl(sockfd, F_GETFD, 0);
997 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
999 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1000 socklist->list[socklist->nr++] = sockfd;
1011 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
1013 struct sockaddr_in sin;
1017 memset(&sin, 0, sizeof sin);
1018 sin.sin_family = AF_INET;
1019 sin.sin_port = htons(listen_port);
1022 /* Well, host better be an IP address here. */
1023 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
1026 sin.sin_addr.s_addr = htonl(INADDR_ANY);
1029 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1033 if (set_reuse_addr(sockfd)) {
1034 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1039 set_keep_alive(sockfd);
1041 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
1042 logerror("Could not bind to %s: %s",
1043 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1049 if (listen(sockfd, 5) < 0) {
1050 logerror("Could not listen to %s: %s",
1051 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1057 flags = fcntl(sockfd, F_GETFD, 0);
1059 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1061 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1062 socklist->list[socklist->nr++] = sockfd;
1068 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
1070 if (!listen_addr->nr)
1071 setup_named_sock(NULL, listen_port, socklist);
1074 for (i = 0; i < listen_addr->nr; i++) {
1075 socknum = setup_named_sock(listen_addr->items[i].string,
1076 listen_port, socklist);
1079 logerror("unable to allocate any listen sockets for host %s on port %u",
1080 listen_addr->items[i].string, listen_port);
1085 static int service_loop(struct socketlist *socklist)
1090 pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
1092 for (i = 0; i < socklist->nr; i++) {
1093 pfd[i].fd = socklist->list[i];
1094 pfd[i].events = POLLIN;
1097 signal(SIGCHLD, child_handler);
1102 check_dead_children();
1104 if (poll(pfd, socklist->nr, -1) < 0) {
1105 if (errno != EINTR) {
1106 logerror("Poll failed, resuming: %s",
1113 for (i = 0; i < socklist->nr; i++) {
1114 if (pfd[i].revents & POLLIN) {
1117 struct sockaddr_in sai;
1119 struct sockaddr_in6 sai6;
1122 socklen_t sslen = sizeof(ss);
1123 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1131 die_errno("accept returned");
1134 handle(incoming, &ss.sa, sslen);
1140 #ifdef NO_POSIX_GOODIES
1144 static void drop_privileges(struct credentials *cred)
1149 static struct credentials *prepare_credentials(const char *user_name,
1150 const char *group_name)
1152 die("--user not supported on this platform");
1157 struct credentials {
1158 struct passwd *pass;
1162 static void drop_privileges(struct credentials *cred)
1164 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1165 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1166 die("cannot drop privileges");
1169 static struct credentials *prepare_credentials(const char *user_name,
1170 const char *group_name)
1172 static struct credentials c;
1174 c.pass = getpwnam(user_name);
1176 die("user not found - %s", user_name);
1179 c.gid = c.pass->pw_gid;
1181 struct group *group = getgrnam(group_name);
1183 die("group not found - %s", group_name);
1185 c.gid = group->gr_gid;
1192 static int serve(struct string_list *listen_addr, int listen_port,
1193 struct credentials *cred)
1195 struct socketlist socklist = { NULL, 0, 0 };
1197 socksetup(listen_addr, listen_port, &socklist);
1198 if (socklist.nr == 0)
1199 die("unable to allocate any listen sockets on port %u",
1202 drop_privileges(cred);
1204 loginfo("Ready to rumble");
1206 return service_loop(&socklist);
1209 int cmd_main(int argc, const char **argv)
1211 int listen_port = 0;
1212 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1213 int serve_mode = 0, inetd_mode = 0;
1214 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1216 struct credentials *cred = NULL;
1219 for (i = 1; i < argc; i++) {
1220 const char *arg = argv[i];
1223 if (skip_prefix(arg, "--listen=", &v)) {
1224 string_list_append(&listen_addr, xstrdup_tolower(v));
1227 if (skip_prefix(arg, "--port=", &v)) {
1230 n = strtoul(v, &end, 0);
1236 if (!strcmp(arg, "--serve")) {
1240 if (!strcmp(arg, "--inetd")) {
1245 if (!strcmp(arg, "--verbose")) {
1249 if (!strcmp(arg, "--syslog")) {
1253 if (!strcmp(arg, "--export-all")) {
1254 export_all_trees = 1;
1257 if (skip_prefix(arg, "--access-hook=", &v)) {
1261 if (skip_prefix(arg, "--timeout=", &v)) {
1265 if (skip_prefix(arg, "--init-timeout=", &v)) {
1266 init_timeout = atoi(v);
1269 if (skip_prefix(arg, "--max-connections=", &v)) {
1270 max_connections = atoi(v);
1271 if (max_connections < 0)
1272 max_connections = 0; /* unlimited */
1275 if (!strcmp(arg, "--strict-paths")) {
1279 if (skip_prefix(arg, "--base-path=", &v)) {
1283 if (!strcmp(arg, "--base-path-relaxed")) {
1284 base_path_relaxed = 1;
1287 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1288 interpolated_path = v;
1291 if (!strcmp(arg, "--reuseaddr")) {
1295 if (!strcmp(arg, "--user-path")) {
1299 if (skip_prefix(arg, "--user-path=", &v)) {
1303 if (skip_prefix(arg, "--pid-file=", &v)) {
1307 if (!strcmp(arg, "--detach")) {
1312 if (skip_prefix(arg, "--user=", &v)) {
1316 if (skip_prefix(arg, "--group=", &v)) {
1320 if (skip_prefix(arg, "--enable=", &v)) {
1321 enable_service(v, 1);
1324 if (skip_prefix(arg, "--disable=", &v)) {
1325 enable_service(v, 0);
1328 if (skip_prefix(arg, "--allow-override=", &v)) {
1329 make_service_overridable(v, 1);
1332 if (skip_prefix(arg, "--forbid-override=", &v)) {
1333 make_service_overridable(v, 0);
1336 if (!strcmp(arg, "--informative-errors")) {
1337 informative_errors = 1;
1340 if (!strcmp(arg, "--no-informative-errors")) {
1341 informative_errors = 0;
1344 if (!strcmp(arg, "--")) {
1345 ok_paths = &argv[i+1];
1347 } else if (arg[0] != '-') {
1348 ok_paths = &argv[i];
1352 usage(daemon_usage);
1356 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1357 set_die_routine(daemon_die);
1359 /* avoid splitting a message in the middle */
1360 setvbuf(stderr, NULL, _IOFBF, 4096);
1362 if (inetd_mode && (detach || group_name || user_name))
1363 die("--detach, --user and --group are incompatible with --inetd");
1365 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1366 die("--listen= and --port= are incompatible with --inetd");
1367 else if (listen_port == 0)
1368 listen_port = DEFAULT_GIT_PORT;
1370 if (group_name && !user_name)
1371 die("--group supplied without --user");
1374 cred = prepare_credentials(user_name, group_name);
1376 if (strict_paths && (!ok_paths || !*ok_paths))
1377 die("option --strict-paths requires a whitelist");
1379 if (base_path && !is_directory(base_path))
1380 die("base-path '%s' does not exist or is not a directory",
1384 if (!freopen("/dev/null", "w", stderr))
1385 die_errno("failed to redirect stderr to /dev/null");
1388 if (inetd_mode || serve_mode)
1393 die("--detach not supported on this platform");
1397 write_file(pid_file, "%"PRIuMAX, (uintmax_t) getpid());
1399 /* prepare argv for serving-processes */
1400 argv_array_push(&cld_argv, argv[0]); /* git-daemon */
1401 argv_array_push(&cld_argv, "--serve");
1402 for (i = 1; i < argc; ++i)
1403 argv_array_push(&cld_argv, argv[i]);
1405 return serve(&listen_addr, listen_port, cred);