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 /* If defined, ~user notation is allowed and the string is inserted
47 * after ~user/. E.g. a request to git://host/~alice/frotz would
48 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
50 static const char *user_path;
52 /* Timeout, and initial timeout */
53 static unsigned int timeout;
54 static unsigned int init_timeout;
57 struct strbuf hostname;
58 struct strbuf canon_hostname;
59 struct strbuf ip_address;
60 struct strbuf tcp_port;
61 unsigned int hostname_lookup_done:1;
62 unsigned int saw_extended_args:1;
65 static void lookup_hostname(struct hostinfo *hi);
67 static const char *get_canon_hostname(struct hostinfo *hi)
70 return hi->canon_hostname.buf;
73 static const char *get_ip_address(struct hostinfo *hi)
76 return hi->ip_address.buf;
79 static void logreport(int priority, const char *err, va_list params)
83 vsnprintf(buf, sizeof(buf), err, params);
84 syslog(priority, "%s", buf);
87 * Since stderr is set to buffered mode, the
88 * logging of different processes will not overlap
89 * unless they overflow the (rather big) buffers.
91 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
92 vfprintf(stderr, err, params);
98 __attribute__((format (printf, 1, 2)))
99 static void logerror(const char *err, ...)
102 va_start(params, err);
103 logreport(LOG_ERR, err, params);
107 __attribute__((format (printf, 1, 2)))
108 static void loginfo(const char *err, ...)
113 va_start(params, err);
114 logreport(LOG_INFO, err, params);
118 static void NORETURN daemon_die(const char *err, va_list params)
120 logreport(LOG_ERR, err, params);
124 struct expand_path_context {
125 const char *directory;
126 struct hostinfo *hostinfo;
129 static size_t expand_path(struct strbuf *sb, const char *placeholder, void *ctx)
131 struct expand_path_context *context = ctx;
132 struct hostinfo *hi = context->hostinfo;
134 switch (placeholder[0]) {
136 strbuf_addbuf(sb, &hi->hostname);
139 if (placeholder[1] == 'H') {
140 strbuf_addstr(sb, get_canon_hostname(hi));
145 if (placeholder[1] == 'P') {
146 strbuf_addstr(sb, get_ip_address(hi));
151 strbuf_addbuf(sb, &hi->tcp_port);
154 strbuf_addstr(sb, context->directory);
160 static const char *path_ok(const char *directory, struct hostinfo *hi)
162 static char rpath[PATH_MAX];
163 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 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
192 namlen, dir, user_path, restlen, slash);
196 else if (interpolated_path && hi->saw_extended_args) {
197 struct strbuf expanded_path = STRBUF_INIT;
198 struct expand_path_context context;
200 context.directory = directory;
201 context.hostinfo = hi;
204 /* Allow only absolute */
205 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
209 strbuf_expand(&expanded_path, interpolated_path,
210 expand_path, &context);
211 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
212 strbuf_release(&expanded_path);
213 loginfo("Interpolated dir '%s'", interp_path);
217 else if (base_path) {
219 /* Allow only absolute */
220 logerror("'%s': Non-absolute path denied (base-path active)", dir);
223 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
227 path = enter_repo(dir, strict_paths);
228 if (!path && base_path && base_path_relaxed) {
230 * if we fail and base_path_relaxed is enabled, try without
231 * prefixing the base path
234 path = enter_repo(dir, strict_paths);
238 logerror("'%s' does not appear to be a git repository", dir);
242 if ( ok_paths && *ok_paths ) {
244 int pathlen = strlen(path);
246 /* The validation is done on the paths after enter_repo
247 * appends optional {.git,.git/.git} and friends, but
248 * it does not use getcwd(). So if your /pub is
249 * a symlink to /mnt/pub, you can whitelist /pub and
250 * do not have to say /mnt/pub.
253 for ( pp = ok_paths ; *pp ; pp++ ) {
254 int len = strlen(*pp);
255 if (len <= pathlen &&
256 !memcmp(*pp, path, len) &&
257 (path[len] == '\0' ||
258 (!strict_paths && path[len] == '/')))
263 /* be backwards compatible */
268 logerror("'%s': not in whitelist", path);
269 return NULL; /* Fallthrough. Deny by default */
272 typedef int (*daemon_service_fn)(void);
273 struct daemon_service {
275 const char *config_name;
276 daemon_service_fn fn;
281 static int daemon_error(const char *dir, const char *msg)
283 if (!informative_errors)
284 msg = "access denied or repository not exported";
285 packet_write(1, "ERR %s: %s", msg, dir);
289 static const char *access_hook;
291 static int run_access_hook(struct daemon_service *service, const char *dir,
292 const char *path, struct hostinfo *hi)
294 struct child_process child = CHILD_PROCESS_INIT;
295 struct strbuf buf = STRBUF_INIT;
297 const char **arg = argv;
301 *arg++ = access_hook;
302 *arg++ = service->name;
304 *arg++ = hi->hostname.buf;
305 *arg++ = get_canon_hostname(hi);
306 *arg++ = get_ip_address(hi);
307 *arg++ = hi->tcp_port.buf;
315 if (start_command(&child)) {
316 logerror("daemon access hook '%s' failed to start",
320 if (strbuf_read(&buf, child.out, 0) < 0) {
321 logerror("failed to read from pipe to daemon access hook '%s'",
326 if (close(child.out) < 0) {
327 logerror("failed to close pipe to daemon access hook '%s'",
331 if (finish_command(&child))
335 strbuf_release(&buf);
342 strbuf_addstr(&buf, "service rejected");
343 eol = strchr(buf.buf, '\n');
347 daemon_error(dir, buf.buf);
348 strbuf_release(&buf);
352 static int run_service(const char *dir, struct daemon_service *service,
356 int enabled = service->enabled;
357 struct strbuf var = STRBUF_INIT;
359 loginfo("Request %s for '%s'", service->name, dir);
361 if (!enabled && !service->overridable) {
362 logerror("'%s': service not enabled.", service->name);
364 return daemon_error(dir, "service not enabled");
367 if (!(path = path_ok(dir, hi)))
368 return daemon_error(dir, "no such repository");
371 * Security on the cheap.
373 * We want a readable HEAD, usable "objects" directory, and
374 * a "git-daemon-export-ok" flag that says that the other side
375 * is ok with us doing this.
377 * path_ok() uses enter_repo() and does whitelist checking.
378 * We only need to make sure the repository is exported.
381 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
382 logerror("'%s': repository not exported.", path);
384 return daemon_error(dir, "repository not exported");
387 if (service->overridable) {
388 strbuf_addf(&var, "daemon.%s", service->config_name);
389 git_config_get_bool(var.buf, &enabled);
390 strbuf_release(&var);
393 logerror("'%s': service not enabled for '%s'",
394 service->name, path);
396 return daemon_error(dir, "service not enabled");
400 * Optionally, a hook can choose to deny access to the
401 * repository depending on the phase of the moon.
403 if (access_hook && run_access_hook(service, dir, path, hi))
407 * We'll ignore SIGTERM from now on, we have a
410 signal(SIGTERM, SIG_IGN);
412 return service->fn();
415 static void copy_to_log(int fd)
417 struct strbuf line = STRBUF_INIT;
420 fp = fdopen(fd, "r");
422 logerror("fdopen of error channel failed");
427 while (strbuf_getline_lf(&line, fp) != EOF) {
428 logerror("%s", line.buf);
429 strbuf_setlen(&line, 0);
432 strbuf_release(&line);
436 static int run_service_command(const char **argv)
438 struct child_process cld = CHILD_PROCESS_INIT;
443 if (start_command(&cld))
449 copy_to_log(cld.err);
451 return finish_command(&cld);
454 static int upload_pack(void)
456 /* Timeout as string */
457 char timeout_buf[64];
458 const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
460 argv[2] = timeout_buf;
462 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
463 return run_service_command(argv);
466 static int upload_archive(void)
468 static const char *argv[] = { "upload-archive", ".", NULL };
469 return run_service_command(argv);
472 static int receive_pack(void)
474 static const char *argv[] = { "receive-pack", ".", NULL };
475 return run_service_command(argv);
478 static struct daemon_service daemon_service[] = {
479 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
480 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
481 { "receive-pack", "receivepack", receive_pack, 0, 1 },
484 static void enable_service(const char *name, int ena)
487 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
488 if (!strcmp(daemon_service[i].name, name)) {
489 daemon_service[i].enabled = ena;
493 die("No such service %s", name);
496 static void make_service_overridable(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].overridable = ena;
505 die("No such service %s", name);
508 static void parse_host_and_port(char *hostport, char **host,
511 if (*hostport == '[') {
514 end = strchr(hostport, ']');
516 die("Invalid request ('[' without ']')");
518 *host = hostport + 1;
521 else if (end[1] == ':')
524 die("Garbage after end of host part");
527 *port = strrchr(hostport, ':');
536 * Sanitize a string from the client so that it's OK to be inserted into a
537 * filesystem path. Specifically, we disallow slashes, runs of "..", and
538 * trailing and leading dots, which means that the client cannot escape
539 * our base path via ".." traversal.
541 static void sanitize_client(struct strbuf *out, const char *in)
546 if (*in == '.' && (!out->len || out->buf[out->len - 1] == '.'))
548 strbuf_addch(out, *in);
551 while (out->len && out->buf[out->len - 1] == '.')
552 strbuf_setlen(out, out->len - 1);
556 * Like sanitize_client, but we also perform any canonicalization
557 * to make life easier on the admin.
559 static void canonicalize_client(struct strbuf *out, const char *in)
561 sanitize_client(out, in);
566 * Read the host as supplied by the client connection.
568 static void parse_host_arg(struct hostinfo *hi, char *extra_args, int buflen)
572 char *end = extra_args + buflen;
574 if (extra_args < end && *extra_args) {
575 hi->saw_extended_args = 1;
576 if (strncasecmp("host=", extra_args, 5) == 0) {
577 val = extra_args + 5;
578 vallen = strlen(val) + 1;
580 /* Split <host>:<port> at colon. */
583 parse_host_and_port(val, &host, &port);
585 sanitize_client(&hi->tcp_port, port);
586 canonicalize_client(&hi->hostname, host);
587 hi->hostname_lookup_done = 0;
590 /* On to the next one */
591 extra_args = val + vallen;
593 if (extra_args < end && *extra_args)
594 die("Invalid request");
599 * Locate canonical hostname and its IP address.
601 static void lookup_hostname(struct hostinfo *hi)
603 if (!hi->hostname_lookup_done && hi->hostname.len) {
605 struct addrinfo hints;
608 static char addrbuf[HOST_NAME_MAX + 1];
610 memset(&hints, 0, sizeof(hints));
611 hints.ai_flags = AI_CANONNAME;
613 gai = getaddrinfo(hi->hostname.buf, NULL, &hints, &ai);
615 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
617 inet_ntop(AF_INET, &sin_addr->sin_addr,
618 addrbuf, sizeof(addrbuf));
619 strbuf_addstr(&hi->ip_address, addrbuf);
621 if (ai->ai_canonname)
622 sanitize_client(&hi->canon_hostname,
625 strbuf_addbuf(&hi->canon_hostname,
631 struct hostent *hent;
632 struct sockaddr_in sa;
634 static char addrbuf[HOST_NAME_MAX + 1];
636 hent = gethostbyname(hi->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 sanitize_client(&hi->canon_hostname, hent->h_name);
648 strbuf_addstr(&hi->ip_address, addrbuf);
651 hi->hostname_lookup_done = 1;
655 static void hostinfo_init(struct hostinfo *hi)
657 memset(hi, 0, sizeof(*hi));
658 strbuf_init(&hi->hostname, 0);
659 strbuf_init(&hi->canon_hostname, 0);
660 strbuf_init(&hi->ip_address, 0);
661 strbuf_init(&hi->tcp_port, 0);
664 static void hostinfo_clear(struct hostinfo *hi)
666 strbuf_release(&hi->hostname);
667 strbuf_release(&hi->canon_hostname);
668 strbuf_release(&hi->ip_address);
669 strbuf_release(&hi->tcp_port);
672 static void set_keep_alive(int sockfd)
676 if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0) {
677 if (errno != ENOTSOCK)
678 logerror("unable to set SO_KEEPALIVE on socket: %s",
683 static int execute(void)
685 char *line = packet_buffer;
687 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
693 loginfo("Connection from %s:%s", addr, port);
696 alarm(init_timeout ? init_timeout : timeout);
697 pktlen = packet_read(0, NULL, NULL, packet_buffer, sizeof(packet_buffer), 0);
702 loginfo("Extended attributes (%d bytes) exist <%.*s>",
704 (int) pktlen - len, line + len + 1);
705 if (len && line[len-1] == '\n') {
711 parse_host_arg(&hi, line + len + 1, pktlen - len - 1);
713 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
714 struct daemon_service *s = &(daemon_service[i]);
717 if (skip_prefix(line, "git-", &arg) &&
718 skip_prefix(arg, s->name, &arg) &&
721 * Note: The directory here is probably context sensitive,
722 * and might depend on the actual service being performed.
724 int rc = run_service(arg, s, &hi);
731 logerror("Protocol error: '%s'", line);
735 static int addrcmp(const struct sockaddr_storage *s1,
736 const struct sockaddr_storage *s2)
738 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
739 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
741 if (sa1->sa_family != sa2->sa_family)
742 return sa1->sa_family - sa2->sa_family;
743 if (sa1->sa_family == AF_INET)
744 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
745 &((struct sockaddr_in *)s2)->sin_addr,
746 sizeof(struct in_addr));
748 if (sa1->sa_family == AF_INET6)
749 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
750 &((struct sockaddr_in6 *)s2)->sin6_addr,
751 sizeof(struct in6_addr));
756 static int max_connections = 32;
758 static unsigned int live_children;
760 static struct child {
762 struct child_process cld;
763 struct sockaddr_storage address;
766 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
768 struct child *newborn, **cradle;
770 newborn = xcalloc(1, sizeof(*newborn));
772 memcpy(&newborn->cld, cld, sizeof(*cld));
773 memcpy(&newborn->address, addr, addrlen);
774 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
775 if (!addrcmp(&(*cradle)->address, &newborn->address))
777 newborn->next = *cradle;
782 * This gets called if the number of connections grows
783 * past "max_connections".
785 * We kill the newest connection from a duplicate IP.
787 static void kill_some_child(void)
789 const struct child *blanket, *next;
791 if (!(blanket = firstborn))
794 for (; (next = blanket->next); blanket = next)
795 if (!addrcmp(&blanket->address, &next->address)) {
796 kill(blanket->cld.pid, SIGTERM);
801 static void check_dead_children(void)
806 struct child **cradle, *blanket;
807 for (cradle = &firstborn; (blanket = *cradle);)
808 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
809 const char *dead = "";
811 dead = " (with error)";
812 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
814 /* remove the child */
815 *cradle = blanket->next;
817 child_process_clear(&blanket->cld);
820 cradle = &blanket->next;
823 static struct argv_array cld_argv = ARGV_ARRAY_INIT;
824 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
826 struct child_process cld = CHILD_PROCESS_INIT;
828 if (max_connections && live_children >= max_connections) {
830 sleep(1); /* give it some time to die */
831 check_dead_children();
832 if (live_children >= max_connections) {
834 logerror("Too many children, dropping connection");
839 if (addr->sa_family == AF_INET) {
841 struct sockaddr_in *sin_addr = (void *) addr;
842 inet_ntop(addr->sa_family, &sin_addr->sin_addr, buf, sizeof(buf));
843 argv_array_pushf(&cld.env_array, "REMOTE_ADDR=%s", buf);
844 argv_array_pushf(&cld.env_array, "REMOTE_PORT=%d",
845 ntohs(sin_addr->sin_port));
847 } else if (addr->sa_family == AF_INET6) {
849 struct sockaddr_in6 *sin6_addr = (void *) addr;
850 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(buf));
851 argv_array_pushf(&cld.env_array, "REMOTE_ADDR=[%s]", buf);
852 argv_array_pushf(&cld.env_array, "REMOTE_PORT=%d",
853 ntohs(sin6_addr->sin6_port));
857 cld.argv = cld_argv.argv;
859 cld.out = dup(incoming);
861 if (start_command(&cld))
862 logerror("unable to fork");
864 add_child(&cld, addr, addrlen);
867 static void child_handler(int signo)
870 * Otherwise empty handler because systemcalls will get interrupted
871 * upon signal receipt
872 * SysV needs the handler to be rearmed
874 signal(SIGCHLD, child_handler);
877 static int set_reuse_addr(int sockfd)
883 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
893 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
896 static char ip[INET_ADDRSTRLEN];
898 static char ip[INET6_ADDRSTRLEN];
904 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
908 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
911 xsnprintf(ip, sizeof(ip), "<unknown>");
918 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
921 char pbuf[NI_MAXSERV];
922 struct addrinfo hints, *ai0, *ai;
926 xsnprintf(pbuf, sizeof(pbuf), "%d", listen_port);
927 memset(&hints, 0, sizeof(hints));
928 hints.ai_family = AF_UNSPEC;
929 hints.ai_socktype = SOCK_STREAM;
930 hints.ai_protocol = IPPROTO_TCP;
931 hints.ai_flags = AI_PASSIVE;
933 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
935 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
939 for (ai = ai0; ai; ai = ai->ai_next) {
942 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
945 if (sockfd >= FD_SETSIZE) {
946 logerror("Socket descriptor too large");
952 if (ai->ai_family == AF_INET6) {
954 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
956 /* Note: error is not fatal */
960 if (set_reuse_addr(sockfd)) {
961 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
966 set_keep_alive(sockfd);
968 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
969 logerror("Could not bind to %s: %s",
970 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
973 continue; /* not fatal */
975 if (listen(sockfd, 5) < 0) {
976 logerror("Could not listen to %s: %s",
977 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
980 continue; /* not fatal */
983 flags = fcntl(sockfd, F_GETFD, 0);
985 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
987 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
988 socklist->list[socklist->nr++] = sockfd;
999 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
1001 struct sockaddr_in sin;
1005 memset(&sin, 0, sizeof sin);
1006 sin.sin_family = AF_INET;
1007 sin.sin_port = htons(listen_port);
1010 /* Well, host better be an IP address here. */
1011 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
1014 sin.sin_addr.s_addr = htonl(INADDR_ANY);
1017 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1021 if (set_reuse_addr(sockfd)) {
1022 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1027 set_keep_alive(sockfd);
1029 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
1030 logerror("Could not bind to %s: %s",
1031 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1037 if (listen(sockfd, 5) < 0) {
1038 logerror("Could not listen to %s: %s",
1039 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1045 flags = fcntl(sockfd, F_GETFD, 0);
1047 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1049 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1050 socklist->list[socklist->nr++] = sockfd;
1056 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
1058 if (!listen_addr->nr)
1059 setup_named_sock(NULL, listen_port, socklist);
1062 for (i = 0; i < listen_addr->nr; i++) {
1063 socknum = setup_named_sock(listen_addr->items[i].string,
1064 listen_port, socklist);
1067 logerror("unable to allocate any listen sockets for host %s on port %u",
1068 listen_addr->items[i].string, listen_port);
1073 static int service_loop(struct socketlist *socklist)
1078 pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
1080 for (i = 0; i < socklist->nr; i++) {
1081 pfd[i].fd = socklist->list[i];
1082 pfd[i].events = POLLIN;
1085 signal(SIGCHLD, child_handler);
1090 check_dead_children();
1092 if (poll(pfd, socklist->nr, -1) < 0) {
1093 if (errno != EINTR) {
1094 logerror("Poll failed, resuming: %s",
1101 for (i = 0; i < socklist->nr; i++) {
1102 if (pfd[i].revents & POLLIN) {
1105 struct sockaddr_in sai;
1107 struct sockaddr_in6 sai6;
1110 socklen_t sslen = sizeof(ss);
1111 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1119 die_errno("accept returned");
1122 handle(incoming, &ss.sa, sslen);
1128 #ifdef NO_POSIX_GOODIES
1132 static void drop_privileges(struct credentials *cred)
1137 static struct credentials *prepare_credentials(const char *user_name,
1138 const char *group_name)
1140 die("--user not supported on this platform");
1145 struct credentials {
1146 struct passwd *pass;
1150 static void drop_privileges(struct credentials *cred)
1152 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1153 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1154 die("cannot drop privileges");
1157 static struct credentials *prepare_credentials(const char *user_name,
1158 const char *group_name)
1160 static struct credentials c;
1162 c.pass = getpwnam(user_name);
1164 die("user not found - %s", user_name);
1167 c.gid = c.pass->pw_gid;
1169 struct group *group = getgrnam(group_name);
1171 die("group not found - %s", group_name);
1173 c.gid = group->gr_gid;
1180 static int serve(struct string_list *listen_addr, int listen_port,
1181 struct credentials *cred)
1183 struct socketlist socklist = { NULL, 0, 0 };
1185 socksetup(listen_addr, listen_port, &socklist);
1186 if (socklist.nr == 0)
1187 die("unable to allocate any listen sockets on port %u",
1190 drop_privileges(cred);
1192 loginfo("Ready to rumble");
1194 return service_loop(&socklist);
1197 int main(int argc, char **argv)
1199 int listen_port = 0;
1200 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1201 int serve_mode = 0, inetd_mode = 0;
1202 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1204 struct credentials *cred = NULL;
1207 git_setup_gettext();
1209 git_extract_argv0_path(argv[0]);
1211 for (i = 1; i < argc; i++) {
1212 char *arg = argv[i];
1215 if (skip_prefix(arg, "--listen=", &v)) {
1216 string_list_append(&listen_addr, xstrdup_tolower(v));
1219 if (skip_prefix(arg, "--port=", &v)) {
1222 n = strtoul(v, &end, 0);
1228 if (!strcmp(arg, "--serve")) {
1232 if (!strcmp(arg, "--inetd")) {
1237 if (!strcmp(arg, "--verbose")) {
1241 if (!strcmp(arg, "--syslog")) {
1245 if (!strcmp(arg, "--export-all")) {
1246 export_all_trees = 1;
1249 if (skip_prefix(arg, "--access-hook=", &v)) {
1253 if (skip_prefix(arg, "--timeout=", &v)) {
1257 if (skip_prefix(arg, "--init-timeout=", &v)) {
1258 init_timeout = atoi(v);
1261 if (skip_prefix(arg, "--max-connections=", &v)) {
1262 max_connections = atoi(v);
1263 if (max_connections < 0)
1264 max_connections = 0; /* unlimited */
1267 if (!strcmp(arg, "--strict-paths")) {
1271 if (skip_prefix(arg, "--base-path=", &v)) {
1275 if (!strcmp(arg, "--base-path-relaxed")) {
1276 base_path_relaxed = 1;
1279 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1280 interpolated_path = v;
1283 if (!strcmp(arg, "--reuseaddr")) {
1287 if (!strcmp(arg, "--user-path")) {
1291 if (skip_prefix(arg, "--user-path=", &v)) {
1295 if (skip_prefix(arg, "--pid-file=", &v)) {
1299 if (!strcmp(arg, "--detach")) {
1304 if (skip_prefix(arg, "--user=", &v)) {
1308 if (skip_prefix(arg, "--group=", &v)) {
1312 if (skip_prefix(arg, "--enable=", &v)) {
1313 enable_service(v, 1);
1316 if (skip_prefix(arg, "--disable=", &v)) {
1317 enable_service(v, 0);
1320 if (skip_prefix(arg, "--allow-override=", &v)) {
1321 make_service_overridable(v, 1);
1324 if (skip_prefix(arg, "--forbid-override=", &v)) {
1325 make_service_overridable(v, 0);
1328 if (!strcmp(arg, "--informative-errors")) {
1329 informative_errors = 1;
1332 if (!strcmp(arg, "--no-informative-errors")) {
1333 informative_errors = 0;
1336 if (!strcmp(arg, "--")) {
1337 ok_paths = &argv[i+1];
1339 } else if (arg[0] != '-') {
1340 ok_paths = &argv[i];
1344 usage(daemon_usage);
1348 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1349 set_die_routine(daemon_die);
1351 /* avoid splitting a message in the middle */
1352 setvbuf(stderr, NULL, _IOFBF, 4096);
1354 if (inetd_mode && (detach || group_name || user_name))
1355 die("--detach, --user and --group are incompatible with --inetd");
1357 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1358 die("--listen= and --port= are incompatible with --inetd");
1359 else if (listen_port == 0)
1360 listen_port = DEFAULT_GIT_PORT;
1362 if (group_name && !user_name)
1363 die("--group supplied without --user");
1366 cred = prepare_credentials(user_name, group_name);
1368 if (strict_paths && (!ok_paths || !*ok_paths))
1369 die("option --strict-paths requires a whitelist");
1371 if (base_path && !is_directory(base_path))
1372 die("base-path '%s' does not exist or is not a directory",
1376 if (!freopen("/dev/null", "w", stderr))
1377 die_errno("failed to redirect stderr to /dev/null");
1380 if (inetd_mode || serve_mode)
1385 die("--detach not supported on this platform");
1390 write_file(pid_file, "%"PRIuMAX, (uintmax_t) getpid());
1392 /* prepare argv for serving-processes */
1393 argv_array_push(&cld_argv, argv[0]); /* git-daemon */
1394 argv_array_push(&cld_argv, "--serve");
1395 for (i = 1; i < argc; ++i)
1396 argv_array_push(&cld_argv, argv[i]);
1398 return serve(&listen_addr, listen_port, cred);