4 #include "run-command.h"
6 #include "string-list.h"
10 static DNSServiceRef sdRef;
13 static void dnssd_register(struct string_list *listen_addr, int listen_port);
14 static void dnssd_unregister(void);
17 #define HOST_NAME_MAX 256
21 #define initgroups(x, y) (0) /* nothing */
24 static int log_syslog;
27 static int informative_errors;
29 static const char daemon_usage[] =
30 "git daemon [--verbose] [--syslog] [--export-all]\n"
31 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
32 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
33 " [--user-path | --user-path=<path>]\n"
34 " [--interpolated-path=<path>]\n"
35 " [--reuseaddr] [--pid-file=<file>]\n"
36 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
37 " [--access-hook=<path>]\n"
38 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
39 " [--detach] [--user=<user> [--group=<group>]]\n"
42 /* List of acceptable pathname prefixes */
43 static char **ok_paths;
44 static int strict_paths;
46 /* If this is set, git-daemon-export-ok is not required */
47 static int export_all_trees;
49 /* Take all paths relative to this one if non-NULL */
50 static const char *base_path;
51 static const char *interpolated_path;
52 static int base_path_relaxed;
54 /* Flag indicating client sent extra args. */
55 static int saw_extended_args;
57 /* If defined, ~user notation is allowed and the string is inserted
58 * after ~user/. E.g. a request to git://host/~alice/frotz would
59 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
61 static const char *user_path;
63 /* Timeout, and initial timeout */
64 static unsigned int timeout;
65 static unsigned int init_timeout;
67 static char *hostname;
68 static char *canon_hostname;
69 static char *ip_address;
70 static char *tcp_port;
72 static void logreport(int priority, const char *err, va_list params)
76 vsnprintf(buf, sizeof(buf), err, params);
77 syslog(priority, "%s", buf);
80 * Since stderr is set to buffered mode, the
81 * logging of different processes will not overlap
82 * unless they overflow the (rather big) buffers.
84 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
85 vfprintf(stderr, err, params);
91 __attribute__((format (printf, 1, 2)))
92 static void logerror(const char *err, ...)
95 va_start(params, err);
96 logreport(LOG_ERR, err, params);
100 __attribute__((format (printf, 1, 2)))
101 static void loginfo(const char *err, ...)
106 va_start(params, err);
107 logreport(LOG_INFO, err, params);
111 static void NORETURN daemon_die(const char *err, va_list params)
113 logreport(LOG_ERR, err, params);
118 static const char *path_ok(const char *directory)
120 static char rpath[PATH_MAX];
121 static char interp_path[PATH_MAX];
127 if (daemon_avoid_alias(dir)) {
128 logerror("'%s': aliased", dir);
134 logerror("'%s': User-path not allowed", dir);
138 /* Got either "~alice" or "~alice/foo";
139 * rewrite them to "~alice/%s" or
142 int namlen, restlen = strlen(dir);
143 const char *slash = strchr(dir, '/');
145 slash = dir + restlen;
146 namlen = slash - dir;
148 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
149 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
150 namlen, dir, user_path, restlen, slash);
154 else if (interpolated_path && saw_extended_args) {
155 struct strbuf expanded_path = STRBUF_INIT;
156 struct strbuf_expand_dict_entry dict[6];
158 dict[0].placeholder = "H"; dict[0].value = hostname;
159 dict[1].placeholder = "CH"; dict[1].value = canon_hostname;
160 dict[2].placeholder = "IP"; dict[2].value = ip_address;
161 dict[3].placeholder = "P"; dict[3].value = tcp_port;
162 dict[4].placeholder = "D"; dict[4].value = directory;
163 dict[5].placeholder = NULL; dict[5].value = NULL;
165 /* Allow only absolute */
166 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
170 strbuf_expand(&expanded_path, interpolated_path,
171 strbuf_expand_dict_cb, &dict);
172 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
173 strbuf_release(&expanded_path);
174 loginfo("Interpolated dir '%s'", interp_path);
178 else if (base_path) {
180 /* Allow only absolute */
181 logerror("'%s': Non-absolute path denied (base-path active)", dir);
184 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
188 path = enter_repo(dir, strict_paths);
189 if (!path && base_path && base_path_relaxed) {
191 * if we fail and base_path_relaxed is enabled, try without
192 * prefixing the base path
195 path = enter_repo(dir, strict_paths);
199 logerror("'%s' does not appear to be a git repository", dir);
203 if ( ok_paths && *ok_paths ) {
205 int pathlen = strlen(path);
207 /* The validation is done on the paths after enter_repo
208 * appends optional {.git,.git/.git} and friends, but
209 * it does not use getcwd(). So if your /pub is
210 * a symlink to /mnt/pub, you can whitelist /pub and
211 * do not have to say /mnt/pub.
214 for ( pp = ok_paths ; *pp ; pp++ ) {
215 int len = strlen(*pp);
216 if (len <= pathlen &&
217 !memcmp(*pp, path, len) &&
218 (path[len] == '\0' ||
219 (!strict_paths && path[len] == '/')))
224 /* be backwards compatible */
229 logerror("'%s': not in whitelist", path);
230 return NULL; /* Fallthrough. Deny by default */
233 typedef int (*daemon_service_fn)(void);
234 struct daemon_service {
236 const char *config_name;
237 daemon_service_fn fn;
242 static struct daemon_service *service_looking_at;
243 static int service_enabled;
245 static int git_daemon_config(const char *var, const char *value, void *cb)
249 if (skip_prefix(var, "daemon.", &service) &&
250 !strcmp(service, service_looking_at->config_name)) {
251 service_enabled = git_config_bool(var, value);
255 /* we are not interested in parsing any other configuration here */
259 static int daemon_error(const char *dir, const char *msg)
261 if (!informative_errors)
262 msg = "access denied or repository not exported";
263 packet_write(1, "ERR %s: %s", msg, dir);
267 static const char *access_hook;
269 static int run_access_hook(struct daemon_service *service, const char *dir, const char *path)
271 struct child_process child;
272 struct strbuf buf = STRBUF_INIT;
274 const char **arg = argv;
278 #define STRARG(x) ((x) ? (x) : "")
279 *arg++ = access_hook;
280 *arg++ = service->name;
282 *arg++ = STRARG(hostname);
283 *arg++ = STRARG(canon_hostname);
284 *arg++ = STRARG(ip_address);
285 *arg++ = STRARG(tcp_port);
289 memset(&child, 0, sizeof(child));
295 if (start_command(&child)) {
296 logerror("daemon access hook '%s' failed to start",
300 if (strbuf_read(&buf, child.out, 0) < 0) {
301 logerror("failed to read from pipe to daemon access hook '%s'",
306 if (close(child.out) < 0) {
307 logerror("failed to close pipe to daemon access hook '%s'",
311 if (finish_command(&child))
315 strbuf_release(&buf);
322 strbuf_addstr(&buf, "service rejected");
323 eol = strchr(buf.buf, '\n');
327 daemon_error(dir, buf.buf);
328 strbuf_release(&buf);
332 static int run_service(const char *dir, struct daemon_service *service)
335 int enabled = service->enabled;
337 loginfo("Request %s for '%s'", service->name, dir);
339 if (!enabled && !service->overridable) {
340 logerror("'%s': service not enabled.", service->name);
342 return daemon_error(dir, "service not enabled");
345 if (!(path = path_ok(dir)))
346 return daemon_error(dir, "no such repository");
349 * Security on the cheap.
351 * We want a readable HEAD, usable "objects" directory, and
352 * a "git-daemon-export-ok" flag that says that the other side
353 * is ok with us doing this.
355 * path_ok() uses enter_repo() and does whitelist checking.
356 * We only need to make sure the repository is exported.
359 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
360 logerror("'%s': repository not exported.", path);
362 return daemon_error(dir, "repository not exported");
365 if (service->overridable) {
366 service_looking_at = service;
367 service_enabled = -1;
368 git_config(git_daemon_config, NULL);
369 if (0 <= service_enabled)
370 enabled = service_enabled;
373 logerror("'%s': service not enabled for '%s'",
374 service->name, path);
376 return daemon_error(dir, "service not enabled");
380 * Optionally, a hook can choose to deny access to the
381 * repository depending on the phase of the moon.
383 if (access_hook && run_access_hook(service, dir, path))
387 * We'll ignore SIGTERM from now on, we have a
390 signal(SIGTERM, SIG_IGN);
392 return service->fn();
395 static void copy_to_log(int fd)
397 struct strbuf line = STRBUF_INIT;
400 fp = fdopen(fd, "r");
402 logerror("fdopen of error channel failed");
407 while (strbuf_getline(&line, fp, '\n') != EOF) {
408 logerror("%s", line.buf);
409 strbuf_setlen(&line, 0);
412 strbuf_release(&line);
416 static int run_service_command(const char **argv)
418 struct child_process cld;
420 memset(&cld, 0, sizeof(cld));
424 if (start_command(&cld))
430 copy_to_log(cld.err);
432 return finish_command(&cld);
435 static int upload_pack(void)
437 /* Timeout as string */
438 char timeout_buf[64];
439 const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
441 argv[2] = timeout_buf;
443 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
444 return run_service_command(argv);
447 static int upload_archive(void)
449 static const char *argv[] = { "upload-archive", ".", NULL };
450 return run_service_command(argv);
453 static int receive_pack(void)
455 static const char *argv[] = { "receive-pack", ".", NULL };
456 return run_service_command(argv);
459 static struct daemon_service daemon_service[] = {
460 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
461 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
462 { "receive-pack", "receivepack", receive_pack, 0, 1 },
465 static void enable_service(const char *name, int ena)
468 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
469 if (!strcmp(daemon_service[i].name, name)) {
470 daemon_service[i].enabled = ena;
474 die("No such service %s", name);
477 static void make_service_overridable(const char *name, int ena)
480 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
481 if (!strcmp(daemon_service[i].name, name)) {
482 daemon_service[i].overridable = ena;
486 die("No such service %s", name);
489 static void parse_host_and_port(char *hostport, char **host,
492 if (*hostport == '[') {
495 end = strchr(hostport, ']');
497 die("Invalid request ('[' without ']')");
499 *host = hostport + 1;
502 else if (end[1] == ':')
505 die("Garbage after end of host part");
508 *port = strrchr(hostport, ':');
517 * Read the host as supplied by the client connection.
519 static void parse_host_arg(char *extra_args, int buflen)
523 char *end = extra_args + buflen;
525 if (extra_args < end && *extra_args) {
526 saw_extended_args = 1;
527 if (strncasecmp("host=", extra_args, 5) == 0) {
528 val = extra_args + 5;
529 vallen = strlen(val) + 1;
531 /* Split <host>:<port> at colon. */
534 parse_host_and_port(val, &host, &port);
537 tcp_port = xstrdup(port);
540 hostname = xstrdup_tolower(host);
543 /* On to the next one */
544 extra_args = val + vallen;
546 if (extra_args < end && *extra_args)
547 die("Invalid request");
551 * Locate canonical hostname and its IP address.
555 struct addrinfo hints;
558 static char addrbuf[HOST_NAME_MAX + 1];
560 memset(&hints, 0, sizeof(hints));
561 hints.ai_flags = AI_CANONNAME;
563 gai = getaddrinfo(hostname, NULL, &hints, &ai);
565 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
567 inet_ntop(AF_INET, &sin_addr->sin_addr,
568 addrbuf, sizeof(addrbuf));
570 ip_address = xstrdup(addrbuf);
572 free(canon_hostname);
573 canon_hostname = xstrdup(ai->ai_canonname ?
574 ai->ai_canonname : ip_address);
579 struct hostent *hent;
580 struct sockaddr_in sa;
582 static char addrbuf[HOST_NAME_MAX + 1];
584 hent = gethostbyname(hostname);
586 ap = hent->h_addr_list;
587 memset(&sa, 0, sizeof sa);
588 sa.sin_family = hent->h_addrtype;
589 sa.sin_port = htons(0);
590 memcpy(&sa.sin_addr, *ap, hent->h_length);
592 inet_ntop(hent->h_addrtype, &sa.sin_addr,
593 addrbuf, sizeof(addrbuf));
595 free(canon_hostname);
596 canon_hostname = xstrdup(hent->h_name);
598 ip_address = xstrdup(addrbuf);
604 static int execute(void)
606 char *line = packet_buffer;
608 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
611 loginfo("Connection from %s:%s", addr, port);
613 alarm(init_timeout ? init_timeout : timeout);
614 pktlen = packet_read(0, NULL, NULL, packet_buffer, sizeof(packet_buffer), 0);
619 loginfo("Extended attributes (%d bytes) exist <%.*s>",
621 (int) pktlen - len, line + len + 1);
622 if (len && line[len-1] == '\n') {
628 free(canon_hostname);
631 hostname = canon_hostname = ip_address = tcp_port = NULL;
634 parse_host_arg(line + len + 1, pktlen - len - 1);
636 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
637 struct daemon_service *s = &(daemon_service[i]);
640 if (skip_prefix(line, "git-", &arg) &&
641 skip_prefix(arg, s->name, &arg) &&
644 * Note: The directory here is probably context sensitive,
645 * and might depend on the actual service being performed.
647 return run_service(arg, s);
651 logerror("Protocol error: '%s'", line);
655 static int addrcmp(const struct sockaddr_storage *s1,
656 const struct sockaddr_storage *s2)
658 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
659 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
661 if (sa1->sa_family != sa2->sa_family)
662 return sa1->sa_family - sa2->sa_family;
663 if (sa1->sa_family == AF_INET)
664 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
665 &((struct sockaddr_in *)s2)->sin_addr,
666 sizeof(struct in_addr));
668 if (sa1->sa_family == AF_INET6)
669 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
670 &((struct sockaddr_in6 *)s2)->sin6_addr,
671 sizeof(struct in6_addr));
676 static int max_connections = 32;
678 static unsigned int live_children;
680 static struct child {
682 struct child_process cld;
683 struct sockaddr_storage address;
686 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
688 struct child *newborn, **cradle;
690 newborn = xcalloc(1, sizeof(*newborn));
692 memcpy(&newborn->cld, cld, sizeof(*cld));
693 memcpy(&newborn->address, addr, addrlen);
694 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
695 if (!addrcmp(&(*cradle)->address, &newborn->address))
697 newborn->next = *cradle;
702 * This gets called if the number of connections grows
703 * past "max_connections".
705 * We kill the newest connection from a duplicate IP.
707 static void kill_some_child(void)
709 const struct child *blanket, *next;
711 if (!(blanket = firstborn))
714 for (; (next = blanket->next); blanket = next)
715 if (!addrcmp(&blanket->address, &next->address)) {
716 kill(blanket->cld.pid, SIGTERM);
721 static void check_dead_children(void)
726 struct child **cradle, *blanket;
727 for (cradle = &firstborn; (blanket = *cradle);)
728 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
729 const char *dead = "";
731 dead = " (with error)";
732 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
734 /* remove the child */
735 *cradle = blanket->next;
739 cradle = &blanket->next;
742 static char **cld_argv;
743 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
745 struct child_process cld = { NULL };
746 char addrbuf[300] = "REMOTE_ADDR=", portbuf[300];
747 char *env[] = { addrbuf, portbuf, NULL };
749 if (max_connections && live_children >= max_connections) {
751 sleep(1); /* give it some time to die */
752 check_dead_children();
753 if (live_children >= max_connections) {
755 logerror("Too many children, dropping connection");
760 if (addr->sa_family == AF_INET) {
761 struct sockaddr_in *sin_addr = (void *) addr;
762 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf + 12,
763 sizeof(addrbuf) - 12);
764 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
765 ntohs(sin_addr->sin_port));
767 } else if (addr->sa_family == AF_INET6) {
768 struct sockaddr_in6 *sin6_addr = (void *) addr;
770 char *buf = addrbuf + 12;
771 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
772 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf,
773 sizeof(addrbuf) - 13);
776 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
777 ntohs(sin6_addr->sin6_port));
781 cld.env = (const char **)env;
782 cld.argv = (const char **)cld_argv;
784 cld.out = dup(incoming);
786 if (start_command(&cld))
787 logerror("unable to fork");
789 add_child(&cld, addr, addrlen);
793 static void child_handler(int signo)
796 * Otherwise empty handler because systemcalls will get interrupted
797 * upon signal receipt
798 * SysV needs the handler to be rearmed
800 signal(SIGCHLD, child_handler);
803 static int set_reuse_addr(int sockfd)
809 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
819 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
822 static char ip[INET_ADDRSTRLEN];
824 static char ip[INET6_ADDRSTRLEN];
830 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
834 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
837 strcpy(ip, "<unknown>");
844 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
848 char pbuf[NI_MAXSERV];
849 struct addrinfo hints, *ai0, *ai;
853 sprintf(pbuf, "%d", listen_port);
854 memset(&hints, 0, sizeof(hints));
855 hints.ai_family = AF_UNSPEC;
856 hints.ai_socktype = SOCK_STREAM;
857 hints.ai_protocol = IPPROTO_TCP;
858 hints.ai_flags = AI_PASSIVE;
860 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
862 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
866 for (ai = ai0; ai; ai = ai->ai_next) {
869 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
872 if (sockfd >= FD_SETSIZE) {
873 logerror("Socket descriptor too large");
879 if (ai->ai_family == AF_INET6) {
881 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
883 /* Note: error is not fatal */
887 if (set_reuse_addr(sockfd)) {
888 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
893 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
894 logerror("Could not bind to %s: %s",
895 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
898 continue; /* not fatal */
900 if (listen(sockfd, 5) < 0) {
901 logerror("Could not listen to %s: %s",
902 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
905 continue; /* not fatal */
908 flags = fcntl(sockfd, F_GETFD, 0);
910 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
912 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
913 socklist->list[socklist->nr++] = sockfd;
927 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
929 struct sockaddr_in sin;
933 memset(&sin, 0, sizeof sin);
934 sin.sin_family = AF_INET;
935 sin.sin_port = htons(listen_port);
938 /* Well, host better be an IP address here. */
939 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
942 sin.sin_addr.s_addr = htonl(INADDR_ANY);
945 sockfd = socket(AF_INET, SOCK_STREAM, 0);
949 if (set_reuse_addr(sockfd)) {
950 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
955 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
956 logerror("Could not listen to %s: %s",
957 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
963 if (listen(sockfd, 5) < 0) {
964 logerror("Could not listen to %s: %s",
965 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
971 flags = fcntl(sockfd, F_GETFD, 0);
973 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
975 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
976 socklist->list[socklist->nr++] = sockfd;
982 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
984 if (!listen_addr->nr)
985 setup_named_sock(NULL, listen_port, socklist);
988 for (i = 0; i < listen_addr->nr; i++) {
989 socknum = setup_named_sock(listen_addr->items[i].string,
990 listen_port, socklist);
993 logerror("unable to allocate any listen sockets for host %s on port %u",
994 listen_addr->items[i].string, listen_port);
999 static int service_loop(struct socketlist *socklist)
1004 pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
1006 for (i = 0; i < socklist->nr; i++) {
1007 pfd[i].fd = socklist->list[i];
1008 pfd[i].events = POLLIN;
1011 signal(SIGCHLD, child_handler);
1016 check_dead_children();
1018 if (poll(pfd, socklist->nr, -1) < 0) {
1019 if (errno != EINTR) {
1020 logerror("Poll failed, resuming: %s",
1027 for (i = 0; i < socklist->nr; i++) {
1028 if (pfd[i].revents & POLLIN) {
1031 struct sockaddr_in sai;
1033 struct sockaddr_in6 sai6;
1036 socklen_t sslen = sizeof(ss);
1037 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1045 die_errno("accept returned");
1048 handle(incoming, &ss.sa, sslen);
1054 #ifdef NO_POSIX_GOODIES
1058 static void drop_privileges(struct credentials *cred)
1063 static struct credentials *prepare_credentials(const char *user_name,
1064 const char *group_name)
1066 die("--user not supported on this platform");
1071 struct credentials {
1072 struct passwd *pass;
1076 static void drop_privileges(struct credentials *cred)
1078 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1079 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1080 die("cannot drop privileges");
1083 static struct credentials *prepare_credentials(const char *user_name,
1084 const char *group_name)
1086 static struct credentials c;
1088 c.pass = getpwnam(user_name);
1090 die("user not found - %s", user_name);
1093 c.gid = c.pass->pw_gid;
1095 struct group *group = getgrnam(group_name);
1097 die("group not found - %s", group_name);
1099 c.gid = group->gr_gid;
1107 static void register_dnssd_addr(const char *listen_addr, int listen_port)
1109 /* We can use if_nametoindex() to turn an interface name
1110 into an index, but how do we turn a listen_addr into
1111 an interface name? */
1112 unsigned if_idx = 0;
1113 DNSServiceErrorType err = DNSServiceRegister(&sdRef,
1114 0, /* Default flags */
1116 "git daemon", /* TODO customize */
1121 0, NULL, /* TODO customize TXT */
1123 if (err != kDNSServiceErr_NoError)
1124 logerror("failed to register service on DNS-SD (%d)\n", err);
1126 loginfo("registered git service for port %d on DNS-SD\n",
1130 static void dnssd_register(struct string_list *listen_addr, int listen_port)
1132 if (!listen_addr->nr)
1133 register_dnssd_addr("", listen_port);
1136 for (i = 0; i < listen_addr->nr; ++i) {
1137 register_dnssd_addr(listen_addr->items[i].string,
1143 static void dnssd_unregister(void)
1145 DNSServiceRefDeallocate(sdRef);
1149 static void dnssd_register(struct string_list *listen_addr, int listen_port)
1151 static void dnssd_unregister(void)
1155 static void store_pid(const char *path)
1157 FILE *f = fopen(path, "w");
1159 die_errno("cannot open pid file '%s'", path);
1160 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
1161 die_errno("failed to write pid file '%s'", path);
1164 static int serve(struct string_list *listen_addr, int listen_port,
1165 struct credentials *cred)
1167 struct socketlist socklist = { NULL, 0, 0 };
1169 socksetup(listen_addr, listen_port, &socklist);
1170 if (socklist.nr == 0)
1171 die("unable to allocate any listen sockets on port %u",
1174 drop_privileges(cred);
1176 dnssd_register(listen_addr, listen_port);
1178 loginfo("Ready to rumble");
1180 return service_loop(&socklist);
1183 int main(int argc, char **argv)
1185 int listen_port = 0;
1186 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1187 int serve_mode = 0, inetd_mode = 0;
1188 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1190 struct credentials *cred = NULL;
1193 git_setup_gettext();
1195 git_extract_argv0_path(argv[0]);
1197 for (i = 1; i < argc; i++) {
1198 char *arg = argv[i];
1201 if (skip_prefix(arg, "--listen=", &v)) {
1202 string_list_append(&listen_addr, xstrdup_tolower(v));
1205 if (skip_prefix(arg, "--port=", &v)) {
1208 n = strtoul(v, &end, 0);
1214 if (!strcmp(arg, "--serve")) {
1218 if (!strcmp(arg, "--inetd")) {
1223 if (!strcmp(arg, "--verbose")) {
1227 if (!strcmp(arg, "--syslog")) {
1231 if (!strcmp(arg, "--export-all")) {
1232 export_all_trees = 1;
1235 if (skip_prefix(arg, "--access-hook=", &v)) {
1239 if (skip_prefix(arg, "--timeout=", &v)) {
1243 if (skip_prefix(arg, "--init-timeout=", &v)) {
1244 init_timeout = atoi(v);
1247 if (skip_prefix(arg, "--max-connections=", &v)) {
1248 max_connections = atoi(v);
1249 if (max_connections < 0)
1250 max_connections = 0; /* unlimited */
1253 if (!strcmp(arg, "--strict-paths")) {
1257 if (skip_prefix(arg, "--base-path=", &v)) {
1261 if (!strcmp(arg, "--base-path-relaxed")) {
1262 base_path_relaxed = 1;
1265 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1266 interpolated_path = v;
1269 if (!strcmp(arg, "--reuseaddr")) {
1273 if (!strcmp(arg, "--user-path")) {
1277 if (skip_prefix(arg, "--user-path=", &v)) {
1281 if (skip_prefix(arg, "--pid-file=", &v)) {
1285 if (!strcmp(arg, "--detach")) {
1290 if (skip_prefix(arg, "--user=", &v)) {
1294 if (skip_prefix(arg, "--group=", &v)) {
1298 if (skip_prefix(arg, "--enable=", &v)) {
1299 enable_service(v, 1);
1302 if (skip_prefix(arg, "--disable=", &v)) {
1303 enable_service(v, 0);
1306 if (skip_prefix(arg, "--allow-override=", &v)) {
1307 make_service_overridable(v, 1);
1310 if (skip_prefix(arg, "--forbid-override=", &v)) {
1311 make_service_overridable(v, 0);
1314 if (!strcmp(arg, "--informative-errors")) {
1315 informative_errors = 1;
1318 if (!strcmp(arg, "--no-informative-errors")) {
1319 informative_errors = 0;
1322 if (!strcmp(arg, "--")) {
1323 ok_paths = &argv[i+1];
1325 } else if (arg[0] != '-') {
1326 ok_paths = &argv[i];
1330 usage(daemon_usage);
1334 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1335 set_die_routine(daemon_die);
1337 /* avoid splitting a message in the middle */
1338 setvbuf(stderr, NULL, _IOFBF, 4096);
1340 if (inetd_mode && (detach || group_name || user_name))
1341 die("--detach, --user and --group are incompatible with --inetd");
1343 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1344 die("--listen= and --port= are incompatible with --inetd");
1345 else if (listen_port == 0)
1346 listen_port = DEFAULT_GIT_PORT;
1348 if (group_name && !user_name)
1349 die("--group supplied without --user");
1352 cred = prepare_credentials(user_name, group_name);
1354 if (strict_paths && (!ok_paths || !*ok_paths))
1355 die("option --strict-paths requires a whitelist");
1357 if (base_path && !is_directory(base_path))
1358 die("base-path '%s' does not exist or is not a directory",
1362 if (!freopen("/dev/null", "w", stderr))
1363 die_errno("failed to redirect stderr to /dev/null");
1366 if (inetd_mode || serve_mode)
1371 die("--detach not supported on this platform");
1376 store_pid(pid_file);
1378 /* prepare argv for serving-processes */
1379 cld_argv = xmalloc(sizeof (char *) * (argc + 2));
1380 cld_argv[0] = argv[0]; /* git-daemon */
1381 cld_argv[1] = "--serve";
1382 for (i = 1; i < argc; ++i)
1383 cld_argv[i+1] = argv[i];
1384 cld_argv[argc+1] = NULL;
1386 return serve(&listen_addr, listen_port, cred);