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 void logreport(int priority, const char *err, va_list params)
68 vsnprintf(buf, sizeof(buf), err, params);
69 syslog(priority, "%s", buf);
72 * Since stderr is set to buffered mode, the
73 * logging of different processes will not overlap
74 * unless they overflow the (rather big) buffers.
76 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
77 vfprintf(stderr, err, params);
83 __attribute__((format (printf, 1, 2)))
84 static void logerror(const char *err, ...)
87 va_start(params, err);
88 logreport(LOG_ERR, err, params);
92 __attribute__((format (printf, 1, 2)))
93 static void loginfo(const char *err, ...)
98 va_start(params, err);
99 logreport(LOG_INFO, err, params);
103 static void NORETURN daemon_die(const char *err, va_list params)
105 logreport(LOG_ERR, err, params);
109 static const char *path_ok(const char *directory)
111 static char rpath[PATH_MAX];
112 static char interp_path[PATH_MAX];
118 if (daemon_avoid_alias(dir)) {
119 logerror("'%s': aliased", dir);
125 logerror("'%s': User-path not allowed", dir);
129 /* Got either "~alice" or "~alice/foo";
130 * rewrite them to "~alice/%s" or
133 int namlen, restlen = strlen(dir);
134 const char *slash = strchr(dir, '/');
136 slash = dir + restlen;
137 namlen = slash - dir;
139 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
140 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
141 namlen, dir, user_path, restlen, slash);
145 else if (interpolated_path && saw_extended_args) {
146 struct strbuf expanded_path = STRBUF_INIT;
147 struct strbuf_expand_dict_entry dict[6];
149 dict[0].placeholder = "H"; dict[0].value = hostname;
150 dict[1].placeholder = "CH"; dict[1].value = canon_hostname;
151 dict[2].placeholder = "IP"; dict[2].value = ip_address;
152 dict[3].placeholder = "P"; dict[3].value = tcp_port;
153 dict[4].placeholder = "D"; dict[4].value = directory;
154 dict[5].placeholder = NULL; dict[5].value = NULL;
156 /* Allow only absolute */
157 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
161 strbuf_expand(&expanded_path, interpolated_path,
162 strbuf_expand_dict_cb, &dict);
163 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
164 strbuf_release(&expanded_path);
165 loginfo("Interpolated dir '%s'", interp_path);
169 else if (base_path) {
171 /* Allow only absolute */
172 logerror("'%s': Non-absolute path denied (base-path active)", dir);
175 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
179 path = enter_repo(dir, strict_paths);
180 if (!path && base_path && base_path_relaxed) {
182 * if we fail and base_path_relaxed is enabled, try without
183 * prefixing the base path
186 path = enter_repo(dir, strict_paths);
190 logerror("'%s' does not appear to be a git repository", dir);
194 if ( ok_paths && *ok_paths ) {
196 int pathlen = strlen(path);
198 /* The validation is done on the paths after enter_repo
199 * appends optional {.git,.git/.git} and friends, but
200 * it does not use getcwd(). So if your /pub is
201 * a symlink to /mnt/pub, you can whitelist /pub and
202 * do not have to say /mnt/pub.
205 for ( pp = ok_paths ; *pp ; pp++ ) {
206 int len = strlen(*pp);
207 if (len <= pathlen &&
208 !memcmp(*pp, path, len) &&
209 (path[len] == '\0' ||
210 (!strict_paths && path[len] == '/')))
215 /* be backwards compatible */
220 logerror("'%s': not in whitelist", path);
221 return NULL; /* Fallthrough. Deny by default */
224 typedef int (*daemon_service_fn)(void);
225 struct daemon_service {
227 const char *config_name;
228 daemon_service_fn fn;
233 static struct daemon_service *service_looking_at;
234 static int service_enabled;
236 static int git_daemon_config(const char *var, const char *value, void *cb)
240 if (skip_prefix(var, "daemon.", &service) &&
241 !strcmp(service, service_looking_at->config_name)) {
242 service_enabled = git_config_bool(var, value);
246 /* we are not interested in parsing any other configuration here */
250 static int daemon_error(const char *dir, const char *msg)
252 if (!informative_errors)
253 msg = "access denied or repository not exported";
254 packet_write(1, "ERR %s: %s", msg, dir);
258 static const char *access_hook;
260 static int run_access_hook(struct daemon_service *service, const char *dir, const char *path)
262 struct child_process child;
263 struct strbuf buf = STRBUF_INIT;
265 const char **arg = argv;
269 #define STRARG(x) ((x) ? (x) : "")
270 *arg++ = access_hook;
271 *arg++ = service->name;
273 *arg++ = STRARG(hostname);
274 *arg++ = STRARG(canon_hostname);
275 *arg++ = STRARG(ip_address);
276 *arg++ = STRARG(tcp_port);
280 memset(&child, 0, sizeof(child));
286 if (start_command(&child)) {
287 logerror("daemon access hook '%s' failed to start",
291 if (strbuf_read(&buf, child.out, 0) < 0) {
292 logerror("failed to read from pipe to daemon access hook '%s'",
297 if (close(child.out) < 0) {
298 logerror("failed to close pipe to daemon access hook '%s'",
302 if (finish_command(&child))
306 strbuf_release(&buf);
313 strbuf_addstr(&buf, "service rejected");
314 eol = strchr(buf.buf, '\n');
318 daemon_error(dir, buf.buf);
319 strbuf_release(&buf);
323 static int run_service(const char *dir, struct daemon_service *service)
326 int enabled = service->enabled;
328 loginfo("Request %s for '%s'", service->name, dir);
330 if (!enabled && !service->overridable) {
331 logerror("'%s': service not enabled.", service->name);
333 return daemon_error(dir, "service not enabled");
336 if (!(path = path_ok(dir)))
337 return daemon_error(dir, "no such repository");
340 * Security on the cheap.
342 * We want a readable HEAD, usable "objects" directory, and
343 * a "git-daemon-export-ok" flag that says that the other side
344 * is ok with us doing this.
346 * path_ok() uses enter_repo() and does whitelist checking.
347 * We only need to make sure the repository is exported.
350 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
351 logerror("'%s': repository not exported.", path);
353 return daemon_error(dir, "repository not exported");
356 if (service->overridable) {
357 service_looking_at = service;
358 service_enabled = -1;
359 git_config(git_daemon_config, NULL);
360 if (0 <= service_enabled)
361 enabled = service_enabled;
364 logerror("'%s': service not enabled for '%s'",
365 service->name, path);
367 return daemon_error(dir, "service not enabled");
371 * Optionally, a hook can choose to deny access to the
372 * repository depending on the phase of the moon.
374 if (access_hook && run_access_hook(service, dir, path))
378 * We'll ignore SIGTERM from now on, we have a
381 signal(SIGTERM, SIG_IGN);
383 return service->fn();
386 static void copy_to_log(int fd)
388 struct strbuf line = STRBUF_INIT;
391 fp = fdopen(fd, "r");
393 logerror("fdopen of error channel failed");
398 while (strbuf_getline(&line, fp, '\n') != EOF) {
399 logerror("%s", line.buf);
400 strbuf_setlen(&line, 0);
403 strbuf_release(&line);
407 static int run_service_command(const char **argv)
409 struct child_process cld;
411 memset(&cld, 0, sizeof(cld));
415 if (start_command(&cld))
421 copy_to_log(cld.err);
423 return finish_command(&cld);
426 static int upload_pack(void)
428 /* Timeout as string */
429 char timeout_buf[64];
430 const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
432 argv[2] = timeout_buf;
434 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
435 return run_service_command(argv);
438 static int upload_archive(void)
440 static const char *argv[] = { "upload-archive", ".", NULL };
441 return run_service_command(argv);
444 static int receive_pack(void)
446 static const char *argv[] = { "receive-pack", ".", NULL };
447 return run_service_command(argv);
450 static struct daemon_service daemon_service[] = {
451 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
452 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
453 { "receive-pack", "receivepack", receive_pack, 0, 1 },
456 static void enable_service(const char *name, int ena)
459 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
460 if (!strcmp(daemon_service[i].name, name)) {
461 daemon_service[i].enabled = ena;
465 die("No such service %s", name);
468 static void make_service_overridable(const char *name, int ena)
471 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
472 if (!strcmp(daemon_service[i].name, name)) {
473 daemon_service[i].overridable = ena;
477 die("No such service %s", name);
480 static void parse_host_and_port(char *hostport, char **host,
483 if (*hostport == '[') {
486 end = strchr(hostport, ']');
488 die("Invalid request ('[' without ']')");
490 *host = hostport + 1;
493 else if (end[1] == ':')
496 die("Garbage after end of host part");
499 *port = strrchr(hostport, ':');
508 * Read the host as supplied by the client connection.
510 static void parse_host_arg(char *extra_args, int buflen)
514 char *end = extra_args + buflen;
516 if (extra_args < end && *extra_args) {
517 saw_extended_args = 1;
518 if (strncasecmp("host=", extra_args, 5) == 0) {
519 val = extra_args + 5;
520 vallen = strlen(val) + 1;
522 /* Split <host>:<port> at colon. */
525 parse_host_and_port(val, &host, &port);
528 tcp_port = xstrdup(port);
531 hostname = xstrdup_tolower(host);
534 /* On to the next one */
535 extra_args = val + vallen;
537 if (extra_args < end && *extra_args)
538 die("Invalid request");
542 * Locate canonical hostname and its IP address.
546 struct addrinfo hints;
549 static char addrbuf[HOST_NAME_MAX + 1];
551 memset(&hints, 0, sizeof(hints));
552 hints.ai_flags = AI_CANONNAME;
554 gai = getaddrinfo(hostname, NULL, &hints, &ai);
556 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
558 inet_ntop(AF_INET, &sin_addr->sin_addr,
559 addrbuf, sizeof(addrbuf));
561 ip_address = xstrdup(addrbuf);
563 free(canon_hostname);
564 canon_hostname = xstrdup(ai->ai_canonname ?
565 ai->ai_canonname : ip_address);
570 struct hostent *hent;
571 struct sockaddr_in sa;
573 static char addrbuf[HOST_NAME_MAX + 1];
575 hent = gethostbyname(hostname);
577 ap = hent->h_addr_list;
578 memset(&sa, 0, sizeof sa);
579 sa.sin_family = hent->h_addrtype;
580 sa.sin_port = htons(0);
581 memcpy(&sa.sin_addr, *ap, hent->h_length);
583 inet_ntop(hent->h_addrtype, &sa.sin_addr,
584 addrbuf, sizeof(addrbuf));
586 free(canon_hostname);
587 canon_hostname = xstrdup(hent->h_name);
589 ip_address = xstrdup(addrbuf);
596 static int execute(void)
598 char *line = packet_buffer;
600 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
603 loginfo("Connection from %s:%s", addr, port);
605 alarm(init_timeout ? init_timeout : timeout);
606 pktlen = packet_read(0, NULL, NULL, packet_buffer, sizeof(packet_buffer), 0);
611 loginfo("Extended attributes (%d bytes) exist <%.*s>",
613 (int) pktlen - len, line + len + 1);
614 if (len && line[len-1] == '\n') {
620 free(canon_hostname);
623 hostname = canon_hostname = ip_address = tcp_port = NULL;
626 parse_host_arg(line + len + 1, pktlen - len - 1);
628 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
629 struct daemon_service *s = &(daemon_service[i]);
632 if (skip_prefix(line, "git-", &arg) &&
633 skip_prefix(arg, s->name, &arg) &&
636 * Note: The directory here is probably context sensitive,
637 * and might depend on the actual service being performed.
639 return run_service(arg, s);
643 logerror("Protocol error: '%s'", line);
647 static int addrcmp(const struct sockaddr_storage *s1,
648 const struct sockaddr_storage *s2)
650 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
651 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
653 if (sa1->sa_family != sa2->sa_family)
654 return sa1->sa_family - sa2->sa_family;
655 if (sa1->sa_family == AF_INET)
656 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
657 &((struct sockaddr_in *)s2)->sin_addr,
658 sizeof(struct in_addr));
660 if (sa1->sa_family == AF_INET6)
661 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
662 &((struct sockaddr_in6 *)s2)->sin6_addr,
663 sizeof(struct in6_addr));
668 static int max_connections = 32;
670 static unsigned int live_children;
672 static struct child {
674 struct child_process cld;
675 struct sockaddr_storage address;
678 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
680 struct child *newborn, **cradle;
682 newborn = xcalloc(1, sizeof(*newborn));
684 memcpy(&newborn->cld, cld, sizeof(*cld));
685 memcpy(&newborn->address, addr, addrlen);
686 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
687 if (!addrcmp(&(*cradle)->address, &newborn->address))
689 newborn->next = *cradle;
694 * This gets called if the number of connections grows
695 * past "max_connections".
697 * We kill the newest connection from a duplicate IP.
699 static void kill_some_child(void)
701 const struct child *blanket, *next;
703 if (!(blanket = firstborn))
706 for (; (next = blanket->next); blanket = next)
707 if (!addrcmp(&blanket->address, &next->address)) {
708 kill(blanket->cld.pid, SIGTERM);
713 static void check_dead_children(void)
718 struct child **cradle, *blanket;
719 for (cradle = &firstborn; (blanket = *cradle);)
720 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
721 const char *dead = "";
723 dead = " (with error)";
724 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
726 /* remove the child */
727 *cradle = blanket->next;
731 cradle = &blanket->next;
734 static char **cld_argv;
735 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
737 struct child_process cld = { NULL };
738 char addrbuf[300] = "REMOTE_ADDR=", portbuf[300];
739 char *env[] = { addrbuf, portbuf, NULL };
741 if (max_connections && live_children >= max_connections) {
743 sleep(1); /* give it some time to die */
744 check_dead_children();
745 if (live_children >= max_connections) {
747 logerror("Too many children, dropping connection");
752 if (addr->sa_family == AF_INET) {
753 struct sockaddr_in *sin_addr = (void *) addr;
754 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf + 12,
755 sizeof(addrbuf) - 12);
756 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
757 ntohs(sin_addr->sin_port));
759 } else if (addr->sa_family == AF_INET6) {
760 struct sockaddr_in6 *sin6_addr = (void *) addr;
762 char *buf = addrbuf + 12;
763 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
764 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf,
765 sizeof(addrbuf) - 13);
768 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
769 ntohs(sin6_addr->sin6_port));
773 cld.env = (const char **)env;
774 cld.argv = (const char **)cld_argv;
776 cld.out = dup(incoming);
778 if (start_command(&cld))
779 logerror("unable to fork");
781 add_child(&cld, addr, addrlen);
784 static void child_handler(int signo)
787 * Otherwise empty handler because systemcalls will get interrupted
788 * upon signal receipt
789 * SysV needs the handler to be rearmed
791 signal(SIGCHLD, child_handler);
794 static int set_reuse_addr(int sockfd)
800 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
810 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
813 static char ip[INET_ADDRSTRLEN];
815 static char ip[INET6_ADDRSTRLEN];
821 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
825 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
828 strcpy(ip, "<unknown>");
835 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
838 char pbuf[NI_MAXSERV];
839 struct addrinfo hints, *ai0, *ai;
843 sprintf(pbuf, "%d", listen_port);
844 memset(&hints, 0, sizeof(hints));
845 hints.ai_family = AF_UNSPEC;
846 hints.ai_socktype = SOCK_STREAM;
847 hints.ai_protocol = IPPROTO_TCP;
848 hints.ai_flags = AI_PASSIVE;
850 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
852 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
856 for (ai = ai0; ai; ai = ai->ai_next) {
859 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
862 if (sockfd >= FD_SETSIZE) {
863 logerror("Socket descriptor too large");
869 if (ai->ai_family == AF_INET6) {
871 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
873 /* Note: error is not fatal */
877 if (set_reuse_addr(sockfd)) {
878 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
883 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
884 logerror("Could not bind to %s: %s",
885 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
888 continue; /* not fatal */
890 if (listen(sockfd, 5) < 0) {
891 logerror("Could not listen to %s: %s",
892 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
895 continue; /* not fatal */
898 flags = fcntl(sockfd, F_GETFD, 0);
900 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
902 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
903 socklist->list[socklist->nr++] = sockfd;
914 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
916 struct sockaddr_in sin;
920 memset(&sin, 0, sizeof sin);
921 sin.sin_family = AF_INET;
922 sin.sin_port = htons(listen_port);
925 /* Well, host better be an IP address here. */
926 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
929 sin.sin_addr.s_addr = htonl(INADDR_ANY);
932 sockfd = socket(AF_INET, SOCK_STREAM, 0);
936 if (set_reuse_addr(sockfd)) {
937 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
942 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
943 logerror("Could not bind to %s: %s",
944 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
950 if (listen(sockfd, 5) < 0) {
951 logerror("Could not listen to %s: %s",
952 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
958 flags = fcntl(sockfd, F_GETFD, 0);
960 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
962 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
963 socklist->list[socklist->nr++] = sockfd;
969 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
971 if (!listen_addr->nr)
972 setup_named_sock(NULL, listen_port, socklist);
975 for (i = 0; i < listen_addr->nr; i++) {
976 socknum = setup_named_sock(listen_addr->items[i].string,
977 listen_port, socklist);
980 logerror("unable to allocate any listen sockets for host %s on port %u",
981 listen_addr->items[i].string, listen_port);
986 static int service_loop(struct socketlist *socklist)
991 pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
993 for (i = 0; i < socklist->nr; i++) {
994 pfd[i].fd = socklist->list[i];
995 pfd[i].events = POLLIN;
998 signal(SIGCHLD, child_handler);
1003 check_dead_children();
1005 if (poll(pfd, socklist->nr, -1) < 0) {
1006 if (errno != EINTR) {
1007 logerror("Poll failed, resuming: %s",
1014 for (i = 0; i < socklist->nr; i++) {
1015 if (pfd[i].revents & POLLIN) {
1018 struct sockaddr_in sai;
1020 struct sockaddr_in6 sai6;
1023 socklen_t sslen = sizeof(ss);
1024 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1032 die_errno("accept returned");
1035 handle(incoming, &ss.sa, sslen);
1041 #ifdef NO_POSIX_GOODIES
1045 static void drop_privileges(struct credentials *cred)
1050 static struct credentials *prepare_credentials(const char *user_name,
1051 const char *group_name)
1053 die("--user not supported on this platform");
1058 struct credentials {
1059 struct passwd *pass;
1063 static void drop_privileges(struct credentials *cred)
1065 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1066 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1067 die("cannot drop privileges");
1070 static struct credentials *prepare_credentials(const char *user_name,
1071 const char *group_name)
1073 static struct credentials c;
1075 c.pass = getpwnam(user_name);
1077 die("user not found - %s", user_name);
1080 c.gid = c.pass->pw_gid;
1082 struct group *group = getgrnam(group_name);
1084 die("group not found - %s", group_name);
1086 c.gid = group->gr_gid;
1093 static void store_pid(const char *path)
1095 FILE *f = fopen(path, "w");
1097 die_errno("cannot open pid file '%s'", path);
1098 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
1099 die_errno("failed to write pid file '%s'", path);
1102 static int serve(struct string_list *listen_addr, int listen_port,
1103 struct credentials *cred)
1105 struct socketlist socklist = { NULL, 0, 0 };
1107 socksetup(listen_addr, listen_port, &socklist);
1108 if (socklist.nr == 0)
1109 die("unable to allocate any listen sockets on port %u",
1112 drop_privileges(cred);
1114 loginfo("Ready to rumble");
1116 return service_loop(&socklist);
1119 int main(int argc, char **argv)
1121 int listen_port = 0;
1122 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1123 int serve_mode = 0, inetd_mode = 0;
1124 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1126 struct credentials *cred = NULL;
1129 git_setup_gettext();
1131 git_extract_argv0_path(argv[0]);
1133 for (i = 1; i < argc; i++) {
1134 char *arg = argv[i];
1137 if (skip_prefix(arg, "--listen=", &v)) {
1138 string_list_append(&listen_addr, xstrdup_tolower(v));
1141 if (skip_prefix(arg, "--port=", &v)) {
1144 n = strtoul(v, &end, 0);
1150 if (!strcmp(arg, "--serve")) {
1154 if (!strcmp(arg, "--inetd")) {
1159 if (!strcmp(arg, "--verbose")) {
1163 if (!strcmp(arg, "--syslog")) {
1167 if (!strcmp(arg, "--export-all")) {
1168 export_all_trees = 1;
1171 if (skip_prefix(arg, "--access-hook=", &v)) {
1175 if (skip_prefix(arg, "--timeout=", &v)) {
1179 if (skip_prefix(arg, "--init-timeout=", &v)) {
1180 init_timeout = atoi(v);
1183 if (skip_prefix(arg, "--max-connections=", &v)) {
1184 max_connections = atoi(v);
1185 if (max_connections < 0)
1186 max_connections = 0; /* unlimited */
1189 if (!strcmp(arg, "--strict-paths")) {
1193 if (skip_prefix(arg, "--base-path=", &v)) {
1197 if (!strcmp(arg, "--base-path-relaxed")) {
1198 base_path_relaxed = 1;
1201 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1202 interpolated_path = v;
1205 if (!strcmp(arg, "--reuseaddr")) {
1209 if (!strcmp(arg, "--user-path")) {
1213 if (skip_prefix(arg, "--user-path=", &v)) {
1217 if (skip_prefix(arg, "--pid-file=", &v)) {
1221 if (!strcmp(arg, "--detach")) {
1226 if (skip_prefix(arg, "--user=", &v)) {
1230 if (skip_prefix(arg, "--group=", &v)) {
1234 if (skip_prefix(arg, "--enable=", &v)) {
1235 enable_service(v, 1);
1238 if (skip_prefix(arg, "--disable=", &v)) {
1239 enable_service(v, 0);
1242 if (skip_prefix(arg, "--allow-override=", &v)) {
1243 make_service_overridable(v, 1);
1246 if (skip_prefix(arg, "--forbid-override=", &v)) {
1247 make_service_overridable(v, 0);
1250 if (!strcmp(arg, "--informative-errors")) {
1251 informative_errors = 1;
1254 if (!strcmp(arg, "--no-informative-errors")) {
1255 informative_errors = 0;
1258 if (!strcmp(arg, "--")) {
1259 ok_paths = &argv[i+1];
1261 } else if (arg[0] != '-') {
1262 ok_paths = &argv[i];
1266 usage(daemon_usage);
1270 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1271 set_die_routine(daemon_die);
1273 /* avoid splitting a message in the middle */
1274 setvbuf(stderr, NULL, _IOFBF, 4096);
1276 if (inetd_mode && (detach || group_name || user_name))
1277 die("--detach, --user and --group are incompatible with --inetd");
1279 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1280 die("--listen= and --port= are incompatible with --inetd");
1281 else if (listen_port == 0)
1282 listen_port = DEFAULT_GIT_PORT;
1284 if (group_name && !user_name)
1285 die("--group supplied without --user");
1288 cred = prepare_credentials(user_name, group_name);
1290 if (strict_paths && (!ok_paths || !*ok_paths))
1291 die("option --strict-paths requires a whitelist");
1293 if (base_path && !is_directory(base_path))
1294 die("base-path '%s' does not exist or is not a directory",
1298 if (!freopen("/dev/null", "w", stderr))
1299 die_errno("failed to redirect stderr to /dev/null");
1302 if (inetd_mode || serve_mode)
1307 die("--detach not supported on this platform");
1312 store_pid(pid_file);
1314 /* prepare argv for serving-processes */
1315 cld_argv = xmalloc(sizeof (char *) * (argc + 2));
1316 cld_argv[0] = argv[0]; /* git-daemon */
1317 cld_argv[1] = "--serve";
1318 for (i = 1; i < argc; ++i)
1319 cld_argv[i+1] = argv[i];
1320 cld_argv[argc+1] = NULL;
1322 return serve(&listen_addr, listen_port, cred);