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 const char *path_ok(const char *directory)
127 static char rpath[PATH_MAX];
128 static char interp_path[PATH_MAX];
134 if (daemon_avoid_alias(dir)) {
135 logerror("'%s': aliased", dir);
141 logerror("'%s': User-path not allowed", dir);
145 /* Got either "~alice" or "~alice/foo";
146 * rewrite them to "~alice/%s" or
149 int namlen, restlen = strlen(dir);
150 const char *slash = strchr(dir, '/');
152 slash = dir + restlen;
153 namlen = slash - dir;
155 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
156 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
157 namlen, dir, user_path, restlen, slash);
161 else if (interpolated_path && saw_extended_args) {
162 struct strbuf expanded_path = STRBUF_INIT;
163 struct strbuf_expand_dict_entry dict[6];
165 dict[0].placeholder = "H"; dict[0].value = hostname;
166 dict[1].placeholder = "CH"; dict[1].value = get_canon_hostname();
167 dict[2].placeholder = "IP"; dict[2].value = get_ip_address();
168 dict[3].placeholder = "P"; dict[3].value = tcp_port;
169 dict[4].placeholder = "D"; dict[4].value = directory;
170 dict[5].placeholder = NULL; dict[5].value = NULL;
172 /* Allow only absolute */
173 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
177 strbuf_expand(&expanded_path, interpolated_path,
178 strbuf_expand_dict_cb, &dict);
179 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
180 strbuf_release(&expanded_path);
181 loginfo("Interpolated dir '%s'", interp_path);
185 else if (base_path) {
187 /* Allow only absolute */
188 logerror("'%s': Non-absolute path denied (base-path active)", dir);
191 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
195 path = enter_repo(dir, strict_paths);
196 if (!path && base_path && base_path_relaxed) {
198 * if we fail and base_path_relaxed is enabled, try without
199 * prefixing the base path
202 path = enter_repo(dir, strict_paths);
206 logerror("'%s' does not appear to be a git repository", dir);
210 if ( ok_paths && *ok_paths ) {
212 int pathlen = strlen(path);
214 /* The validation is done on the paths after enter_repo
215 * appends optional {.git,.git/.git} and friends, but
216 * it does not use getcwd(). So if your /pub is
217 * a symlink to /mnt/pub, you can whitelist /pub and
218 * do not have to say /mnt/pub.
221 for ( pp = ok_paths ; *pp ; pp++ ) {
222 int len = strlen(*pp);
223 if (len <= pathlen &&
224 !memcmp(*pp, path, len) &&
225 (path[len] == '\0' ||
226 (!strict_paths && path[len] == '/')))
231 /* be backwards compatible */
236 logerror("'%s': not in whitelist", path);
237 return NULL; /* Fallthrough. Deny by default */
240 typedef int (*daemon_service_fn)(void);
241 struct daemon_service {
243 const char *config_name;
244 daemon_service_fn fn;
249 static struct daemon_service *service_looking_at;
250 static int service_enabled;
252 static int git_daemon_config(const char *var, const char *value, void *cb)
256 if (skip_prefix(var, "daemon.", &service) &&
257 !strcmp(service, service_looking_at->config_name)) {
258 service_enabled = git_config_bool(var, value);
262 /* we are not interested in parsing any other configuration here */
266 static int daemon_error(const char *dir, const char *msg)
268 if (!informative_errors)
269 msg = "access denied or repository not exported";
270 packet_write(1, "ERR %s: %s", msg, dir);
274 static const char *access_hook;
276 static int run_access_hook(struct daemon_service *service, const char *dir, const char *path)
278 struct child_process child;
279 struct strbuf buf = STRBUF_INIT;
281 const char **arg = argv;
285 #define STRARG(x) ((x) ? (x) : "")
286 *arg++ = access_hook;
287 *arg++ = service->name;
289 *arg++ = STRARG(hostname);
290 *arg++ = STRARG(get_canon_hostname());
291 *arg++ = STRARG(get_ip_address());
292 *arg++ = STRARG(tcp_port);
296 memset(&child, 0, sizeof(child));
302 if (start_command(&child)) {
303 logerror("daemon access hook '%s' failed to start",
307 if (strbuf_read(&buf, child.out, 0) < 0) {
308 logerror("failed to read from pipe to daemon access hook '%s'",
313 if (close(child.out) < 0) {
314 logerror("failed to close pipe to daemon access hook '%s'",
318 if (finish_command(&child))
322 strbuf_release(&buf);
329 strbuf_addstr(&buf, "service rejected");
330 eol = strchr(buf.buf, '\n');
334 daemon_error(dir, buf.buf);
335 strbuf_release(&buf);
339 static int run_service(const char *dir, struct daemon_service *service)
342 int enabled = service->enabled;
344 loginfo("Request %s for '%s'", service->name, dir);
346 if (!enabled && !service->overridable) {
347 logerror("'%s': service not enabled.", service->name);
349 return daemon_error(dir, "service not enabled");
352 if (!(path = path_ok(dir)))
353 return daemon_error(dir, "no such repository");
356 * Security on the cheap.
358 * We want a readable HEAD, usable "objects" directory, and
359 * a "git-daemon-export-ok" flag that says that the other side
360 * is ok with us doing this.
362 * path_ok() uses enter_repo() and does whitelist checking.
363 * We only need to make sure the repository is exported.
366 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
367 logerror("'%s': repository not exported.", path);
369 return daemon_error(dir, "repository not exported");
372 if (service->overridable) {
373 service_looking_at = service;
374 service_enabled = -1;
375 git_config(git_daemon_config, NULL);
376 if (0 <= service_enabled)
377 enabled = service_enabled;
380 logerror("'%s': service not enabled for '%s'",
381 service->name, path);
383 return daemon_error(dir, "service not enabled");
387 * Optionally, a hook can choose to deny access to the
388 * repository depending on the phase of the moon.
390 if (access_hook && run_access_hook(service, dir, path))
394 * We'll ignore SIGTERM from now on, we have a
397 signal(SIGTERM, SIG_IGN);
399 return service->fn();
402 static void copy_to_log(int fd)
404 struct strbuf line = STRBUF_INIT;
407 fp = fdopen(fd, "r");
409 logerror("fdopen of error channel failed");
414 while (strbuf_getline(&line, fp, '\n') != EOF) {
415 logerror("%s", line.buf);
416 strbuf_setlen(&line, 0);
419 strbuf_release(&line);
423 static int run_service_command(const char **argv)
425 struct child_process cld;
427 memset(&cld, 0, sizeof(cld));
431 if (start_command(&cld))
437 copy_to_log(cld.err);
439 return finish_command(&cld);
442 static int upload_pack(void)
444 /* Timeout as string */
445 char timeout_buf[64];
446 const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
448 argv[2] = timeout_buf;
450 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
451 return run_service_command(argv);
454 static int upload_archive(void)
456 static const char *argv[] = { "upload-archive", ".", NULL };
457 return run_service_command(argv);
460 static int receive_pack(void)
462 static const char *argv[] = { "receive-pack", ".", NULL };
463 return run_service_command(argv);
466 static struct daemon_service daemon_service[] = {
467 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
468 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
469 { "receive-pack", "receivepack", receive_pack, 0, 1 },
472 static void enable_service(const char *name, int ena)
475 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
476 if (!strcmp(daemon_service[i].name, name)) {
477 daemon_service[i].enabled = ena;
481 die("No such service %s", name);
484 static void make_service_overridable(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].overridable = ena;
493 die("No such service %s", name);
496 static void parse_host_and_port(char *hostport, char **host,
499 if (*hostport == '[') {
502 end = strchr(hostport, ']');
504 die("Invalid request ('[' without ']')");
506 *host = hostport + 1;
509 else if (end[1] == ':')
512 die("Garbage after end of host part");
515 *port = strrchr(hostport, ':');
524 * Read the host as supplied by the client connection.
526 static void parse_host_arg(char *extra_args, int buflen)
530 char *end = extra_args + buflen;
532 if (extra_args < end && *extra_args) {
533 saw_extended_args = 1;
534 if (strncasecmp("host=", extra_args, 5) == 0) {
535 val = extra_args + 5;
536 vallen = strlen(val) + 1;
538 /* Split <host>:<port> at colon. */
541 parse_host_and_port(val, &host, &port);
544 tcp_port = xstrdup(port);
547 hostname = xstrdup_tolower(host);
548 hostname_lookup_done = 0;
551 /* On to the next one */
552 extra_args = val + vallen;
554 if (extra_args < end && *extra_args)
555 die("Invalid request");
560 * Locate canonical hostname and its IP address.
562 static void lookup_hostname(void)
564 if (!hostname_lookup_done && hostname) {
566 struct addrinfo hints;
569 static char addrbuf[HOST_NAME_MAX + 1];
571 memset(&hints, 0, sizeof(hints));
572 hints.ai_flags = AI_CANONNAME;
574 gai = getaddrinfo(hostname, NULL, &hints, &ai);
576 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
578 inet_ntop(AF_INET, &sin_addr->sin_addr,
579 addrbuf, sizeof(addrbuf));
581 ip_address = xstrdup(addrbuf);
583 free(canon_hostname);
584 canon_hostname = xstrdup(ai->ai_canonname ?
585 ai->ai_canonname : ip_address);
590 struct hostent *hent;
591 struct sockaddr_in sa;
593 static char addrbuf[HOST_NAME_MAX + 1];
595 hent = gethostbyname(hostname);
597 ap = hent->h_addr_list;
598 memset(&sa, 0, sizeof sa);
599 sa.sin_family = hent->h_addrtype;
600 sa.sin_port = htons(0);
601 memcpy(&sa.sin_addr, *ap, hent->h_length);
603 inet_ntop(hent->h_addrtype, &sa.sin_addr,
604 addrbuf, sizeof(addrbuf));
606 free(canon_hostname);
607 canon_hostname = xstrdup(hent->h_name);
609 ip_address = xstrdup(addrbuf);
612 hostname_lookup_done = 1;
617 static int execute(void)
619 char *line = packet_buffer;
621 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
624 loginfo("Connection from %s:%s", addr, port);
626 alarm(init_timeout ? init_timeout : timeout);
627 pktlen = packet_read(0, NULL, NULL, packet_buffer, sizeof(packet_buffer), 0);
632 loginfo("Extended attributes (%d bytes) exist <%.*s>",
634 (int) pktlen - len, line + len + 1);
635 if (len && line[len-1] == '\n') {
641 free(canon_hostname);
644 hostname = canon_hostname = ip_address = tcp_port = NULL;
647 parse_host_arg(line + len + 1, pktlen - len - 1);
649 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
650 struct daemon_service *s = &(daemon_service[i]);
653 if (skip_prefix(line, "git-", &arg) &&
654 skip_prefix(arg, s->name, &arg) &&
657 * Note: The directory here is probably context sensitive,
658 * and might depend on the actual service being performed.
660 return run_service(arg, s);
664 logerror("Protocol error: '%s'", line);
668 static int addrcmp(const struct sockaddr_storage *s1,
669 const struct sockaddr_storage *s2)
671 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
672 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
674 if (sa1->sa_family != sa2->sa_family)
675 return sa1->sa_family - sa2->sa_family;
676 if (sa1->sa_family == AF_INET)
677 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
678 &((struct sockaddr_in *)s2)->sin_addr,
679 sizeof(struct in_addr));
681 if (sa1->sa_family == AF_INET6)
682 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
683 &((struct sockaddr_in6 *)s2)->sin6_addr,
684 sizeof(struct in6_addr));
689 static int max_connections = 32;
691 static unsigned int live_children;
693 static struct child {
695 struct child_process cld;
696 struct sockaddr_storage address;
699 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
701 struct child *newborn, **cradle;
703 newborn = xcalloc(1, sizeof(*newborn));
705 memcpy(&newborn->cld, cld, sizeof(*cld));
706 memcpy(&newborn->address, addr, addrlen);
707 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
708 if (!addrcmp(&(*cradle)->address, &newborn->address))
710 newborn->next = *cradle;
715 * This gets called if the number of connections grows
716 * past "max_connections".
718 * We kill the newest connection from a duplicate IP.
720 static void kill_some_child(void)
722 const struct child *blanket, *next;
724 if (!(blanket = firstborn))
727 for (; (next = blanket->next); blanket = next)
728 if (!addrcmp(&blanket->address, &next->address)) {
729 kill(blanket->cld.pid, SIGTERM);
734 static void check_dead_children(void)
739 struct child **cradle, *blanket;
740 for (cradle = &firstborn; (blanket = *cradle);)
741 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
742 const char *dead = "";
744 dead = " (with error)";
745 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
747 /* remove the child */
748 *cradle = blanket->next;
752 cradle = &blanket->next;
755 static char **cld_argv;
756 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
758 struct child_process cld = { NULL };
759 char addrbuf[300] = "REMOTE_ADDR=", portbuf[300];
760 char *env[] = { addrbuf, portbuf, NULL };
762 if (max_connections && live_children >= max_connections) {
764 sleep(1); /* give it some time to die */
765 check_dead_children();
766 if (live_children >= max_connections) {
768 logerror("Too many children, dropping connection");
773 if (addr->sa_family == AF_INET) {
774 struct sockaddr_in *sin_addr = (void *) addr;
775 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf + 12,
776 sizeof(addrbuf) - 12);
777 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
778 ntohs(sin_addr->sin_port));
780 } else if (addr->sa_family == AF_INET6) {
781 struct sockaddr_in6 *sin6_addr = (void *) addr;
783 char *buf = addrbuf + 12;
784 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
785 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf,
786 sizeof(addrbuf) - 13);
789 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
790 ntohs(sin6_addr->sin6_port));
794 cld.env = (const char **)env;
795 cld.argv = (const char **)cld_argv;
797 cld.out = dup(incoming);
799 if (start_command(&cld))
800 logerror("unable to fork");
802 add_child(&cld, addr, addrlen);
805 static void child_handler(int signo)
808 * Otherwise empty handler because systemcalls will get interrupted
809 * upon signal receipt
810 * SysV needs the handler to be rearmed
812 signal(SIGCHLD, child_handler);
815 static int set_reuse_addr(int sockfd)
821 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
831 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
834 static char ip[INET_ADDRSTRLEN];
836 static char ip[INET6_ADDRSTRLEN];
842 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
846 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
849 strcpy(ip, "<unknown>");
856 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
859 char pbuf[NI_MAXSERV];
860 struct addrinfo hints, *ai0, *ai;
864 sprintf(pbuf, "%d", listen_port);
865 memset(&hints, 0, sizeof(hints));
866 hints.ai_family = AF_UNSPEC;
867 hints.ai_socktype = SOCK_STREAM;
868 hints.ai_protocol = IPPROTO_TCP;
869 hints.ai_flags = AI_PASSIVE;
871 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
873 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
877 for (ai = ai0; ai; ai = ai->ai_next) {
880 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
883 if (sockfd >= FD_SETSIZE) {
884 logerror("Socket descriptor too large");
890 if (ai->ai_family == AF_INET6) {
892 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
894 /* Note: error is not fatal */
898 if (set_reuse_addr(sockfd)) {
899 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
904 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
905 logerror("Could not bind to %s: %s",
906 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
909 continue; /* not fatal */
911 if (listen(sockfd, 5) < 0) {
912 logerror("Could not listen to %s: %s",
913 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
916 continue; /* not fatal */
919 flags = fcntl(sockfd, F_GETFD, 0);
921 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
923 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
924 socklist->list[socklist->nr++] = sockfd;
935 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
937 struct sockaddr_in sin;
941 memset(&sin, 0, sizeof sin);
942 sin.sin_family = AF_INET;
943 sin.sin_port = htons(listen_port);
946 /* Well, host better be an IP address here. */
947 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
950 sin.sin_addr.s_addr = htonl(INADDR_ANY);
953 sockfd = socket(AF_INET, SOCK_STREAM, 0);
957 if (set_reuse_addr(sockfd)) {
958 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
963 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
964 logerror("Could not bind to %s: %s",
965 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
971 if (listen(sockfd, 5) < 0) {
972 logerror("Could not listen to %s: %s",
973 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
979 flags = fcntl(sockfd, F_GETFD, 0);
981 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
983 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
984 socklist->list[socklist->nr++] = sockfd;
990 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
992 if (!listen_addr->nr)
993 setup_named_sock(NULL, listen_port, socklist);
996 for (i = 0; i < listen_addr->nr; i++) {
997 socknum = setup_named_sock(listen_addr->items[i].string,
998 listen_port, socklist);
1001 logerror("unable to allocate any listen sockets for host %s on port %u",
1002 listen_addr->items[i].string, listen_port);
1007 static int service_loop(struct socketlist *socklist)
1012 pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
1014 for (i = 0; i < socklist->nr; i++) {
1015 pfd[i].fd = socklist->list[i];
1016 pfd[i].events = POLLIN;
1019 signal(SIGCHLD, child_handler);
1024 check_dead_children();
1026 if (poll(pfd, socklist->nr, -1) < 0) {
1027 if (errno != EINTR) {
1028 logerror("Poll failed, resuming: %s",
1035 for (i = 0; i < socklist->nr; i++) {
1036 if (pfd[i].revents & POLLIN) {
1039 struct sockaddr_in sai;
1041 struct sockaddr_in6 sai6;
1044 socklen_t sslen = sizeof(ss);
1045 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1053 die_errno("accept returned");
1056 handle(incoming, &ss.sa, sslen);
1062 #ifdef NO_POSIX_GOODIES
1066 static void drop_privileges(struct credentials *cred)
1071 static struct credentials *prepare_credentials(const char *user_name,
1072 const char *group_name)
1074 die("--user not supported on this platform");
1079 struct credentials {
1080 struct passwd *pass;
1084 static void drop_privileges(struct credentials *cred)
1086 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1087 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1088 die("cannot drop privileges");
1091 static struct credentials *prepare_credentials(const char *user_name,
1092 const char *group_name)
1094 static struct credentials c;
1096 c.pass = getpwnam(user_name);
1098 die("user not found - %s", user_name);
1101 c.gid = c.pass->pw_gid;
1103 struct group *group = getgrnam(group_name);
1105 die("group not found - %s", group_name);
1107 c.gid = group->gr_gid;
1114 static void store_pid(const char *path)
1116 FILE *f = fopen(path, "w");
1118 die_errno("cannot open pid file '%s'", path);
1119 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
1120 die_errno("failed to write pid file '%s'", path);
1123 static int serve(struct string_list *listen_addr, int listen_port,
1124 struct credentials *cred)
1126 struct socketlist socklist = { NULL, 0, 0 };
1128 socksetup(listen_addr, listen_port, &socklist);
1129 if (socklist.nr == 0)
1130 die("unable to allocate any listen sockets on port %u",
1133 drop_privileges(cred);
1135 loginfo("Ready to rumble");
1137 return service_loop(&socklist);
1140 int main(int argc, char **argv)
1142 int listen_port = 0;
1143 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1144 int serve_mode = 0, inetd_mode = 0;
1145 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1147 struct credentials *cred = NULL;
1150 git_setup_gettext();
1152 git_extract_argv0_path(argv[0]);
1154 for (i = 1; i < argc; i++) {
1155 char *arg = argv[i];
1158 if (skip_prefix(arg, "--listen=", &v)) {
1159 string_list_append(&listen_addr, xstrdup_tolower(v));
1162 if (skip_prefix(arg, "--port=", &v)) {
1165 n = strtoul(v, &end, 0);
1171 if (!strcmp(arg, "--serve")) {
1175 if (!strcmp(arg, "--inetd")) {
1180 if (!strcmp(arg, "--verbose")) {
1184 if (!strcmp(arg, "--syslog")) {
1188 if (!strcmp(arg, "--export-all")) {
1189 export_all_trees = 1;
1192 if (skip_prefix(arg, "--access-hook=", &v)) {
1196 if (skip_prefix(arg, "--timeout=", &v)) {
1200 if (skip_prefix(arg, "--init-timeout=", &v)) {
1201 init_timeout = atoi(v);
1204 if (skip_prefix(arg, "--max-connections=", &v)) {
1205 max_connections = atoi(v);
1206 if (max_connections < 0)
1207 max_connections = 0; /* unlimited */
1210 if (!strcmp(arg, "--strict-paths")) {
1214 if (skip_prefix(arg, "--base-path=", &v)) {
1218 if (!strcmp(arg, "--base-path-relaxed")) {
1219 base_path_relaxed = 1;
1222 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1223 interpolated_path = v;
1226 if (!strcmp(arg, "--reuseaddr")) {
1230 if (!strcmp(arg, "--user-path")) {
1234 if (skip_prefix(arg, "--user-path=", &v)) {
1238 if (skip_prefix(arg, "--pid-file=", &v)) {
1242 if (!strcmp(arg, "--detach")) {
1247 if (skip_prefix(arg, "--user=", &v)) {
1251 if (skip_prefix(arg, "--group=", &v)) {
1255 if (skip_prefix(arg, "--enable=", &v)) {
1256 enable_service(v, 1);
1259 if (skip_prefix(arg, "--disable=", &v)) {
1260 enable_service(v, 0);
1263 if (skip_prefix(arg, "--allow-override=", &v)) {
1264 make_service_overridable(v, 1);
1267 if (skip_prefix(arg, "--forbid-override=", &v)) {
1268 make_service_overridable(v, 0);
1271 if (!strcmp(arg, "--informative-errors")) {
1272 informative_errors = 1;
1275 if (!strcmp(arg, "--no-informative-errors")) {
1276 informative_errors = 0;
1279 if (!strcmp(arg, "--")) {
1280 ok_paths = &argv[i+1];
1282 } else if (arg[0] != '-') {
1283 ok_paths = &argv[i];
1287 usage(daemon_usage);
1291 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1292 set_die_routine(daemon_die);
1294 /* avoid splitting a message in the middle */
1295 setvbuf(stderr, NULL, _IOFBF, 4096);
1297 if (inetd_mode && (detach || group_name || user_name))
1298 die("--detach, --user and --group are incompatible with --inetd");
1300 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1301 die("--listen= and --port= are incompatible with --inetd");
1302 else if (listen_port == 0)
1303 listen_port = DEFAULT_GIT_PORT;
1305 if (group_name && !user_name)
1306 die("--group supplied without --user");
1309 cred = prepare_credentials(user_name, group_name);
1311 if (strict_paths && (!ok_paths || !*ok_paths))
1312 die("option --strict-paths requires a whitelist");
1314 if (base_path && !is_directory(base_path))
1315 die("base-path '%s' does not exist or is not a directory",
1319 if (!freopen("/dev/null", "w", stderr))
1320 die_errno("failed to redirect stderr to /dev/null");
1323 if (inetd_mode || serve_mode)
1328 die("--detach not supported on this platform");
1333 store_pid(pid_file);
1335 /* prepare argv for serving-processes */
1336 cld_argv = xmalloc(sizeof (char *) * (argc + 2));
1337 cld_argv[0] = argv[0]; /* git-daemon */
1338 cld_argv[1] = "--serve";
1339 for (i = 1; i < argc; ++i)
1340 cld_argv[i+1] = argv[i];
1341 cld_argv[argc+1] = NULL;
1343 return serve(&listen_addr, listen_port, cred);