8 #define HOST_NAME_MAX 256
15 static int log_syslog;
19 static const char daemon_usage[] =
20 "git daemon [--verbose] [--syslog] [--export-all]\n"
21 " [--timeout=n] [--init-timeout=n] [--max-connections=n]\n"
22 " [--strict-paths] [--base-path=path] [--base-path-relaxed]\n"
23 " [--user-path | --user-path=path]\n"
24 " [--interpolated-path=path]\n"
25 " [--reuseaddr] [--detach] [--pid-file=file]\n"
26 " [--[enable|disable|allow-override|forbid-override]=service]\n"
27 " [--inetd | [--listen=host_or_ipaddr] [--port=n]\n"
28 " [--user=user [--group=group]]\n"
31 /* List of acceptable pathname prefixes */
32 static char **ok_paths;
33 static int strict_paths;
35 /* If this is set, git-daemon-export-ok is not required */
36 static int export_all_trees;
38 /* Take all paths relative to this one if non-NULL */
39 static char *base_path;
40 static char *interpolated_path;
41 static int base_path_relaxed;
43 /* Flag indicating client sent extra args. */
44 static int saw_extended_args;
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;
56 static char *hostname;
57 static char *canon_hostname;
58 static char *ip_address;
59 static char *tcp_port;
61 static void logreport(int priority, const char *err, va_list params)
65 vsnprintf(buf, sizeof(buf), err, params);
66 syslog(priority, "%s", buf);
69 * Since stderr is set to linebuffered mode, the
70 * logging of different processes will not overlap
72 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
73 vfprintf(stderr, err, params);
78 static void logerror(const char *err, ...)
81 va_start(params, err);
82 logreport(LOG_ERR, err, params);
86 static void loginfo(const char *err, ...)
91 va_start(params, err);
92 logreport(LOG_INFO, err, params);
96 static void NORETURN daemon_die(const char *err, va_list params)
98 logreport(LOG_ERR, err, params);
102 static int avoid_alias(char *p)
107 * This resurrects the belts and suspenders paranoia check by HPA
108 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
109 * does not do getcwd() based path canonicalizations.
111 * sl becomes true immediately after seeing '/' and continues to
112 * be true as long as dots continue after that without intervening
115 if (!p || (*p != '/' && *p != '~'))
125 else if (ch == '/') {
127 /* reject //, /./ and /../ */
132 if (0 < ndot && ndot < 3)
133 /* reject /.$ and /..$ */
142 else if (ch == '/') {
149 static char *path_ok(char *directory)
151 static char rpath[PATH_MAX];
152 static char interp_path[PATH_MAX];
153 int retried_path = 0;
159 if (avoid_alias(dir)) {
160 logerror("'%s': aliased", dir);
166 logerror("'%s': User-path not allowed", dir);
170 /* Got either "~alice" or "~alice/foo";
171 * rewrite them to "~alice/%s" or
174 int namlen, restlen = strlen(dir);
175 char *slash = strchr(dir, '/');
177 slash = dir + restlen;
178 namlen = slash - dir;
180 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
181 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
182 namlen, dir, user_path, restlen, slash);
186 else if (interpolated_path && saw_extended_args) {
187 struct strbuf expanded_path = STRBUF_INIT;
188 struct strbuf_expand_dict_entry dict[] = {
190 { "CH", canon_hostname },
191 { "IP", ip_address },
199 /* Allow only absolute */
200 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
204 strbuf_expand(&expanded_path, interpolated_path,
205 strbuf_expand_dict_cb, &dict);
206 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
207 strbuf_release(&expanded_path);
208 loginfo("Interpolated dir '%s'", interp_path);
212 else if (base_path) {
214 /* Allow only absolute */
215 logerror("'%s': Non-absolute path denied (base-path active)", dir);
218 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
223 path = enter_repo(dir, strict_paths);
228 * if we fail and base_path_relaxed is enabled, try without
229 * prefixing the base path
231 if (base_path && base_path_relaxed && !retried_path) {
240 logerror("'%s': unable to chdir or not a git archive", dir);
244 if ( ok_paths && *ok_paths ) {
246 int pathlen = strlen(path);
248 /* The validation is done on the paths after enter_repo
249 * appends optional {.git,.git/.git} and friends, but
250 * it does not use getcwd(). So if your /pub is
251 * a symlink to /mnt/pub, you can whitelist /pub and
252 * do not have to say /mnt/pub.
255 for ( pp = ok_paths ; *pp ; pp++ ) {
256 int len = strlen(*pp);
257 if (len <= pathlen &&
258 !memcmp(*pp, path, len) &&
259 (path[len] == '\0' ||
260 (!strict_paths && path[len] == '/')))
265 /* be backwards compatible */
270 logerror("'%s': not in whitelist", path);
271 return NULL; /* Fallthrough. Deny by default */
274 typedef int (*daemon_service_fn)(void);
275 struct daemon_service {
277 const char *config_name;
278 daemon_service_fn fn;
283 static struct daemon_service *service_looking_at;
284 static int service_enabled;
286 static int git_daemon_config(const char *var, const char *value, void *cb)
288 if (!prefixcmp(var, "daemon.") &&
289 !strcmp(var + 7, service_looking_at->config_name)) {
290 service_enabled = git_config_bool(var, value);
294 /* we are not interested in parsing any other configuration here */
298 static int run_service(char *dir, struct daemon_service *service)
301 int enabled = service->enabled;
303 loginfo("Request %s for '%s'", service->name, dir);
305 if (!enabled && !service->overridable) {
306 logerror("'%s': service not enabled.", service->name);
311 if (!(path = path_ok(dir)))
315 * Security on the cheap.
317 * We want a readable HEAD, usable "objects" directory, and
318 * a "git-daemon-export-ok" flag that says that the other side
319 * is ok with us doing this.
321 * path_ok() uses enter_repo() and does whitelist checking.
322 * We only need to make sure the repository is exported.
325 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
326 logerror("'%s': repository not exported.", path);
331 if (service->overridable) {
332 service_looking_at = service;
333 service_enabled = -1;
334 git_config(git_daemon_config, NULL);
335 if (0 <= service_enabled)
336 enabled = service_enabled;
339 logerror("'%s': service not enabled for '%s'",
340 service->name, path);
346 * We'll ignore SIGTERM from now on, we have a
349 signal(SIGTERM, SIG_IGN);
351 return service->fn();
354 static int upload_pack(void)
356 /* Timeout as string */
357 char timeout_buf[64];
359 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
361 /* git-upload-pack only ever reads stuff, so this is safe */
362 execl_git_cmd("upload-pack", "--strict", timeout_buf, ".", NULL);
366 static int upload_archive(void)
368 execl_git_cmd("upload-archive", ".", NULL);
372 static int receive_pack(void)
374 execl_git_cmd("receive-pack", ".", NULL);
378 static struct daemon_service daemon_service[] = {
379 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
380 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
381 { "receive-pack", "receivepack", receive_pack, 0, 1 },
384 static void enable_service(const char *name, int ena)
387 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
388 if (!strcmp(daemon_service[i].name, name)) {
389 daemon_service[i].enabled = ena;
393 die("No such service %s", name);
396 static void make_service_overridable(const char *name, int ena)
399 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
400 if (!strcmp(daemon_service[i].name, name)) {
401 daemon_service[i].overridable = ena;
405 die("No such service %s", name);
409 * Separate the "extra args" information as supplied by the client connection.
411 static void parse_extra_args(char *extra_args, int buflen)
415 char *end = extra_args + buflen;
418 while (extra_args < end && *extra_args) {
419 saw_extended_args = 1;
420 if (strncasecmp("host=", extra_args, 5) == 0) {
421 val = extra_args + 5;
422 vallen = strlen(val) + 1;
424 /* Split <host>:<port> at colon. */
426 char *port = strrchr(host, ':');
431 tcp_port = xstrdup(port);
434 hostname = xstrdup(host);
437 /* On to the next one */
438 extra_args = val + vallen;
443 * Replace literal host with lowercase-ized hostname.
452 * Locate canonical hostname and its IP address.
456 struct addrinfo hints;
457 struct addrinfo *ai, *ai0;
459 static char addrbuf[HOST_NAME_MAX + 1];
461 memset(&hints, 0, sizeof(hints));
462 hints.ai_flags = AI_CANONNAME;
464 gai = getaddrinfo(hostname, 0, &hints, &ai0);
466 for (ai = ai0; ai; ai = ai->ai_next) {
467 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
469 inet_ntop(AF_INET, &sin_addr->sin_addr,
470 addrbuf, sizeof(addrbuf));
471 free(canon_hostname);
472 canon_hostname = xstrdup(ai->ai_canonname);
474 ip_address = xstrdup(addrbuf);
482 struct hostent *hent;
483 struct sockaddr_in sa;
485 static char addrbuf[HOST_NAME_MAX + 1];
487 hent = gethostbyname(hostname);
489 ap = hent->h_addr_list;
490 memset(&sa, 0, sizeof sa);
491 sa.sin_family = hent->h_addrtype;
492 sa.sin_port = htons(0);
493 memcpy(&sa.sin_addr, *ap, hent->h_length);
495 inet_ntop(hent->h_addrtype, &sa.sin_addr,
496 addrbuf, sizeof(addrbuf));
498 free(canon_hostname);
499 canon_hostname = xstrdup(hent->h_name);
501 ip_address = xstrdup(addrbuf);
507 static int execute(struct sockaddr *addr)
509 static char line[1000];
513 char addrbuf[256] = "";
516 if (addr->sa_family == AF_INET) {
517 struct sockaddr_in *sin_addr = (void *) addr;
518 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
519 port = ntohs(sin_addr->sin_port);
521 } else if (addr && addr->sa_family == AF_INET6) {
522 struct sockaddr_in6 *sin6_addr = (void *) addr;
525 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
526 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
529 port = ntohs(sin6_addr->sin6_port);
532 loginfo("Connection from %s:%d", addrbuf, port);
533 setenv("REMOTE_ADDR", addrbuf, 1);
536 unsetenv("REMOTE_ADDR");
539 alarm(init_timeout ? init_timeout : timeout);
540 pktlen = packet_read_line(0, line, sizeof(line));
545 loginfo("Extended attributes (%d bytes) exist <%.*s>",
547 (int) pktlen - len, line + len + 1);
548 if (len && line[len-1] == '\n') {
554 free(canon_hostname);
557 hostname = canon_hostname = ip_address = tcp_port = NULL;
560 parse_extra_args(line + len + 1, pktlen - len - 1);
562 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
563 struct daemon_service *s = &(daemon_service[i]);
564 int namelen = strlen(s->name);
565 if (!prefixcmp(line, "git-") &&
566 !strncmp(s->name, line + 4, namelen) &&
567 line[namelen + 4] == ' ') {
569 * Note: The directory here is probably context sensitive,
570 * and might depend on the actual service being performed.
572 return run_service(line + namelen + 5, s);
576 logerror("Protocol error: '%s'", line);
580 static int max_connections = 32;
582 static unsigned int live_children;
584 static struct child {
587 struct sockaddr_storage address;
590 static void add_child(pid_t pid, struct sockaddr *addr, int addrlen)
592 struct child *newborn, **cradle;
595 * This must be xcalloc() -- we'll compare the whole sockaddr_storage
596 * but individual address may be shorter.
598 newborn = xcalloc(1, sizeof(*newborn));
601 memcpy(&newborn->address, addr, addrlen);
602 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
603 if (!memcmp(&(*cradle)->address, &newborn->address,
604 sizeof(newborn->address)))
606 newborn->next = *cradle;
610 static void remove_child(pid_t pid)
612 struct child **cradle, *blanket;
614 for (cradle = &firstborn; (blanket = *cradle); cradle = &blanket->next)
615 if (blanket->pid == pid) {
616 *cradle = blanket->next;
624 * This gets called if the number of connections grows
625 * past "max_connections".
627 * We kill the newest connection from a duplicate IP.
629 static void kill_some_child(void)
631 const struct child *blanket, *next;
633 if (!(blanket = firstborn))
636 for (; (next = blanket->next); blanket = next)
637 if (!memcmp(&blanket->address, &next->address,
638 sizeof(next->address))) {
639 kill(blanket->pid, SIGTERM);
644 static void check_dead_children(void)
649 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
650 const char *dead = "";
652 if (!WIFEXITED(status) || (WEXITSTATUS(status) > 0))
653 dead = " (with error)";
654 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
658 static void handle(int incoming, struct sockaddr *addr, int addrlen)
662 if (max_connections && live_children >= max_connections) {
664 sleep(1); /* give it some time to die */
665 check_dead_children();
666 if (live_children >= max_connections) {
668 logerror("Too many children, dropping connection");
673 if ((pid = fork())) {
676 logerror("Couldn't fork %s", strerror(errno));
680 add_child(pid, addr, addrlen);
691 static void child_handler(int signo)
694 * Otherwise empty handler because systemcalls will get interrupted
695 * upon signal receipt
696 * SysV needs the handler to be rearmed
698 signal(SIGCHLD, child_handler);
701 static int set_reuse_addr(int sockfd)
707 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
713 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
715 int socknum = 0, *socklist = NULL;
717 char pbuf[NI_MAXSERV];
718 struct addrinfo hints, *ai0, *ai;
722 sprintf(pbuf, "%d", listen_port);
723 memset(&hints, 0, sizeof(hints));
724 hints.ai_family = AF_UNSPEC;
725 hints.ai_socktype = SOCK_STREAM;
726 hints.ai_protocol = IPPROTO_TCP;
727 hints.ai_flags = AI_PASSIVE;
729 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
731 die("getaddrinfo() failed: %s\n", gai_strerror(gai));
733 for (ai = ai0; ai; ai = ai->ai_next) {
736 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
739 if (sockfd >= FD_SETSIZE) {
740 logerror("Socket descriptor too large");
746 if (ai->ai_family == AF_INET6) {
748 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
750 /* Note: error is not fatal */
754 if (set_reuse_addr(sockfd)) {
759 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
761 continue; /* not fatal */
763 if (listen(sockfd, 5) < 0) {
765 continue; /* not fatal */
768 flags = fcntl(sockfd, F_GETFD, 0);
770 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
772 socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
773 socklist[socknum++] = sockfd;
781 *socklist_p = socklist;
787 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
789 struct sockaddr_in sin;
793 memset(&sin, 0, sizeof sin);
794 sin.sin_family = AF_INET;
795 sin.sin_port = htons(listen_port);
798 /* Well, host better be an IP address here. */
799 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
802 sin.sin_addr.s_addr = htonl(INADDR_ANY);
805 sockfd = socket(AF_INET, SOCK_STREAM, 0);
809 if (set_reuse_addr(sockfd)) {
814 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
819 if (listen(sockfd, 5) < 0) {
824 flags = fcntl(sockfd, F_GETFD, 0);
826 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
828 *socklist_p = xmalloc(sizeof(int));
829 **socklist_p = sockfd;
835 static int service_loop(int socknum, int *socklist)
840 pfd = xcalloc(socknum, sizeof(struct pollfd));
842 for (i = 0; i < socknum; i++) {
843 pfd[i].fd = socklist[i];
844 pfd[i].events = POLLIN;
847 signal(SIGCHLD, child_handler);
852 check_dead_children();
854 if (poll(pfd, socknum, -1) < 0) {
855 if (errno != EINTR) {
856 logerror("Poll failed, resuming: %s",
863 for (i = 0; i < socknum; i++) {
864 if (pfd[i].revents & POLLIN) {
865 struct sockaddr_storage ss;
866 unsigned int sslen = sizeof(ss);
867 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
875 die("accept returned %s", strerror(errno));
878 handle(incoming, (struct sockaddr *)&ss, sslen);
884 /* if any standard file descriptor is missing open it to /dev/null */
885 static void sanitize_stdfds(void)
887 int fd = open("/dev/null", O_RDWR, 0);
888 while (fd != -1 && fd < 2)
891 die("open /dev/null or dup failed: %s", strerror(errno));
896 static void daemonize(void)
902 die("fork failed: %s", strerror(errno));
907 die("setsid failed: %s", strerror(errno));
914 static void store_pid(const char *path)
916 FILE *f = fopen(path, "w");
918 die("cannot open pid file %s: %s", path, strerror(errno));
919 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
920 die("failed to write pid file %s: %s", path, strerror(errno));
923 static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
925 int socknum, *socklist;
927 socknum = socksetup(listen_addr, listen_port, &socklist);
929 die("unable to allocate any listen sockets on host %s port %u",
930 listen_addr, listen_port);
933 (initgroups(pass->pw_name, gid) || setgid (gid) ||
934 setuid(pass->pw_uid)))
935 die("cannot drop privileges");
937 return service_loop(socknum, socklist);
940 int main(int argc, char **argv)
943 char *listen_addr = NULL;
945 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
947 struct passwd *pass = NULL;
952 for (i = 1; i < argc; i++) {
955 if (!prefixcmp(arg, "--listen=")) {
957 char *ph = listen_addr = xmalloc(strlen(arg + 9) + 1);
959 *ph++ = tolower(*p++);
963 if (!prefixcmp(arg, "--port=")) {
966 n = strtoul(arg+7, &end, 0);
967 if (arg[7] && !*end) {
972 if (!strcmp(arg, "--inetd")) {
977 if (!strcmp(arg, "--verbose")) {
981 if (!strcmp(arg, "--syslog")) {
985 if (!strcmp(arg, "--export-all")) {
986 export_all_trees = 1;
989 if (!prefixcmp(arg, "--timeout=")) {
990 timeout = atoi(arg+10);
993 if (!prefixcmp(arg, "--init-timeout=")) {
994 init_timeout = atoi(arg+15);
997 if (!prefixcmp(arg, "--max-connections=")) {
998 max_connections = atoi(arg+18);
999 if (max_connections < 0)
1000 max_connections = 0; /* unlimited */
1003 if (!strcmp(arg, "--strict-paths")) {
1007 if (!prefixcmp(arg, "--base-path=")) {
1011 if (!strcmp(arg, "--base-path-relaxed")) {
1012 base_path_relaxed = 1;
1015 if (!prefixcmp(arg, "--interpolated-path=")) {
1016 interpolated_path = arg+20;
1019 if (!strcmp(arg, "--reuseaddr")) {
1023 if (!strcmp(arg, "--user-path")) {
1027 if (!prefixcmp(arg, "--user-path=")) {
1028 user_path = arg + 12;
1031 if (!prefixcmp(arg, "--pid-file=")) {
1032 pid_file = arg + 11;
1035 if (!strcmp(arg, "--detach")) {
1040 if (!prefixcmp(arg, "--user=")) {
1041 user_name = arg + 7;
1044 if (!prefixcmp(arg, "--group=")) {
1045 group_name = arg + 8;
1048 if (!prefixcmp(arg, "--enable=")) {
1049 enable_service(arg + 9, 1);
1052 if (!prefixcmp(arg, "--disable=")) {
1053 enable_service(arg + 10, 0);
1056 if (!prefixcmp(arg, "--allow-override=")) {
1057 make_service_overridable(arg + 17, 1);
1060 if (!prefixcmp(arg, "--forbid-override=")) {
1061 make_service_overridable(arg + 18, 0);
1064 if (!strcmp(arg, "--")) {
1065 ok_paths = &argv[i+1];
1067 } else if (arg[0] != '-') {
1068 ok_paths = &argv[i];
1072 usage(daemon_usage);
1076 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1077 set_die_routine(daemon_die);
1079 /* avoid splitting a message in the middle */
1080 setvbuf(stderr, NULL, _IOLBF, 0);
1082 if (inetd_mode && (group_name || user_name))
1083 die("--user and --group are incompatible with --inetd");
1085 if (inetd_mode && (listen_port || listen_addr))
1086 die("--listen= and --port= are incompatible with --inetd");
1087 else if (listen_port == 0)
1088 listen_port = DEFAULT_GIT_PORT;
1090 if (group_name && !user_name)
1091 die("--group supplied without --user");
1094 pass = getpwnam(user_name);
1096 die("user not found - %s", user_name);
1101 group = getgrnam(group_name);
1103 die("group not found - %s", group_name);
1105 gid = group->gr_gid;
1109 if (strict_paths && (!ok_paths || !*ok_paths))
1110 die("option --strict-paths requires a whitelist");
1112 if (base_path && !is_directory(base_path))
1113 die("base-path '%s' does not exist or is not a directory",
1117 struct sockaddr_storage ss;
1118 struct sockaddr *peer = (struct sockaddr *)&ss;
1119 socklen_t slen = sizeof(ss);
1121 freopen("/dev/null", "w", stderr);
1123 if (getpeername(0, peer, &slen))
1126 return execute(peer);
1131 loginfo("Ready to rumble");
1137 store_pid(pid_file);
1139 return serve(listen_addr, listen_port, pass, gid);