4 #include "run-command.h"
10 #define HOST_NAME_MAX 256
17 static int log_syslog;
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] [--detach] [--pid-file=file]\n"
28 " [--[enable|disable|allow-override|forbid-override]=service]\n"
29 " [--inetd | [--listen=host_or_ipaddr] [--port=n]\n"
30 " [--user=user [--group=group]]\n"
33 /* List of acceptable pathname prefixes */
34 static char **ok_paths;
35 static int strict_paths;
37 /* If this is set, git-daemon-export-ok is not required */
38 static int export_all_trees;
40 /* Take all paths relative to this one if non-NULL */
41 static char *base_path;
42 static char *interpolated_path;
43 static int base_path_relaxed;
45 /* Flag indicating client sent extra args. */
46 static int saw_extended_args;
48 /* If defined, ~user notation is allowed and the string is inserted
49 * after ~user/. E.g. a request to git://host/~alice/frotz would
50 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
52 static const char *user_path;
54 /* Timeout, and initial timeout */
55 static unsigned int timeout;
56 static unsigned int init_timeout;
58 static char *hostname;
59 static char *canon_hostname;
60 static char *ip_address;
61 static char *tcp_port;
63 static void logreport(int priority, const char *err, va_list params)
67 vsnprintf(buf, sizeof(buf), err, params);
68 syslog(priority, "%s", buf);
71 * Since stderr is set to linebuffered mode, the
72 * logging of different processes will not overlap
74 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
75 vfprintf(stderr, err, params);
80 __attribute__((format (printf, 1, 2)))
81 static void logerror(const char *err, ...)
84 va_start(params, err);
85 logreport(LOG_ERR, err, params);
89 __attribute__((format (printf, 1, 2)))
90 static void loginfo(const char *err, ...)
95 va_start(params, err);
96 logreport(LOG_INFO, err, params);
100 static void NORETURN daemon_die(const char *err, va_list params)
102 logreport(LOG_ERR, err, params);
106 static int avoid_alias(char *p)
111 * This resurrects the belts and suspenders paranoia check by HPA
112 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
113 * does not do getcwd() based path canonicalizations.
115 * sl becomes true immediately after seeing '/' and continues to
116 * be true as long as dots continue after that without intervening
119 if (!p || (*p != '/' && *p != '~'))
129 else if (ch == '/') {
131 /* reject //, /./ and /../ */
136 if (0 < ndot && ndot < 3)
137 /* reject /.$ and /..$ */
146 else if (ch == '/') {
153 static char *path_ok(char *directory)
155 static char rpath[PATH_MAX];
156 static char interp_path[PATH_MAX];
162 if (avoid_alias(dir)) {
163 logerror("'%s': aliased", dir);
169 logerror("'%s': User-path not allowed", dir);
173 /* Got either "~alice" or "~alice/foo";
174 * rewrite them to "~alice/%s" or
177 int namlen, restlen = strlen(dir);
178 char *slash = strchr(dir, '/');
180 slash = dir + restlen;
181 namlen = slash - dir;
183 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
184 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
185 namlen, dir, user_path, restlen, slash);
189 else if (interpolated_path && saw_extended_args) {
190 struct strbuf expanded_path = STRBUF_INIT;
191 struct strbuf_expand_dict_entry dict[] = {
193 { "CH", canon_hostname },
194 { "IP", ip_address },
202 /* Allow only absolute */
203 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
207 strbuf_expand(&expanded_path, interpolated_path,
208 strbuf_expand_dict_cb, &dict);
209 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
210 strbuf_release(&expanded_path);
211 loginfo("Interpolated dir '%s'", interp_path);
215 else if (base_path) {
217 /* Allow only absolute */
218 logerror("'%s': Non-absolute path denied (base-path active)", dir);
221 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
225 path = enter_repo(dir, strict_paths);
226 if (!path && base_path && base_path_relaxed) {
228 * if we fail and base_path_relaxed is enabled, try without
229 * prefixing the base path
232 path = enter_repo(dir, strict_paths);
236 logerror("'%s' does not appear to be a git repository", dir);
240 if ( ok_paths && *ok_paths ) {
242 int pathlen = strlen(path);
244 /* The validation is done on the paths after enter_repo
245 * appends optional {.git,.git/.git} and friends, but
246 * it does not use getcwd(). So if your /pub is
247 * a symlink to /mnt/pub, you can whitelist /pub and
248 * do not have to say /mnt/pub.
251 for ( pp = ok_paths ; *pp ; pp++ ) {
252 int len = strlen(*pp);
253 if (len <= pathlen &&
254 !memcmp(*pp, path, len) &&
255 (path[len] == '\0' ||
256 (!strict_paths && path[len] == '/')))
261 /* be backwards compatible */
266 logerror("'%s': not in whitelist", path);
267 return NULL; /* Fallthrough. Deny by default */
270 typedef int (*daemon_service_fn)(void);
271 struct daemon_service {
273 const char *config_name;
274 daemon_service_fn fn;
279 static struct daemon_service *service_looking_at;
280 static int service_enabled;
282 static int git_daemon_config(const char *var, const char *value, void *cb)
284 if (!prefixcmp(var, "daemon.") &&
285 !strcmp(var + 7, service_looking_at->config_name)) {
286 service_enabled = git_config_bool(var, value);
290 /* we are not interested in parsing any other configuration here */
294 static int run_service(char *dir, struct daemon_service *service)
297 int enabled = service->enabled;
299 loginfo("Request %s for '%s'", service->name, dir);
301 if (!enabled && !service->overridable) {
302 logerror("'%s': service not enabled.", service->name);
307 if (!(path = path_ok(dir)))
311 * Security on the cheap.
313 * We want a readable HEAD, usable "objects" directory, and
314 * a "git-daemon-export-ok" flag that says that the other side
315 * is ok with us doing this.
317 * path_ok() uses enter_repo() and does whitelist checking.
318 * We only need to make sure the repository is exported.
321 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
322 logerror("'%s': repository not exported.", path);
327 if (service->overridable) {
328 service_looking_at = service;
329 service_enabled = -1;
330 git_config(git_daemon_config, NULL);
331 if (0 <= service_enabled)
332 enabled = service_enabled;
335 logerror("'%s': service not enabled for '%s'",
336 service->name, path);
342 * We'll ignore SIGTERM from now on, we have a
345 signal(SIGTERM, SIG_IGN);
347 return service->fn();
350 static void copy_to_log(int fd)
352 struct strbuf line = STRBUF_INIT;
355 fp = fdopen(fd, "r");
357 logerror("fdopen of error channel failed");
362 while (strbuf_getline(&line, fp, '\n') != EOF) {
363 logerror("%s", line.buf);
364 strbuf_setlen(&line, 0);
367 strbuf_release(&line);
371 static int run_service_command(const char **argv)
373 struct child_process cld;
375 memset(&cld, 0, sizeof(cld));
379 if (start_command(&cld))
385 copy_to_log(cld.err);
387 return finish_command(&cld);
390 static int upload_pack(void)
392 /* Timeout as string */
393 char timeout_buf[64];
394 const char *argv[] = { "upload-pack", "--strict", timeout_buf, ".", NULL };
396 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
397 return run_service_command(argv);
400 static int upload_archive(void)
402 static const char *argv[] = { "upload-archive", ".", NULL };
403 return run_service_command(argv);
406 static int receive_pack(void)
408 static const char *argv[] = { "receive-pack", ".", NULL };
409 return run_service_command(argv);
412 static struct daemon_service daemon_service[] = {
413 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
414 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
415 { "receive-pack", "receivepack", receive_pack, 0, 1 },
418 static void enable_service(const char *name, int ena)
421 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
422 if (!strcmp(daemon_service[i].name, name)) {
423 daemon_service[i].enabled = ena;
427 die("No such service %s", name);
430 static void make_service_overridable(const char *name, int ena)
433 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
434 if (!strcmp(daemon_service[i].name, name)) {
435 daemon_service[i].overridable = ena;
439 die("No such service %s", name);
442 static char *xstrdup_tolower(const char *str)
444 char *p, *dup = xstrdup(str);
445 for (p = dup; *p; p++)
451 * Read the host as supplied by the client connection.
453 static void parse_host_arg(char *extra_args, int buflen)
457 char *end = extra_args + buflen;
459 if (extra_args < end && *extra_args) {
460 saw_extended_args = 1;
461 if (strncasecmp("host=", extra_args, 5) == 0) {
462 val = extra_args + 5;
463 vallen = strlen(val) + 1;
465 /* Split <host>:<port> at colon. */
467 char *port = strrchr(host, ':');
472 tcp_port = xstrdup(port);
475 hostname = xstrdup_tolower(host);
478 /* On to the next one */
479 extra_args = val + vallen;
481 if (extra_args < end && *extra_args)
482 die("Invalid request");
486 * Locate canonical hostname and its IP address.
490 struct addrinfo hints;
493 static char addrbuf[HOST_NAME_MAX + 1];
495 memset(&hints, 0, sizeof(hints));
496 hints.ai_flags = AI_CANONNAME;
498 gai = getaddrinfo(hostname, NULL, &hints, &ai);
500 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
502 inet_ntop(AF_INET, &sin_addr->sin_addr,
503 addrbuf, sizeof(addrbuf));
505 ip_address = xstrdup(addrbuf);
507 free(canon_hostname);
508 canon_hostname = xstrdup(ai->ai_canonname ?
509 ai->ai_canonname : ip_address);
514 struct hostent *hent;
515 struct sockaddr_in sa;
517 static char addrbuf[HOST_NAME_MAX + 1];
519 hent = gethostbyname(hostname);
521 ap = hent->h_addr_list;
522 memset(&sa, 0, sizeof sa);
523 sa.sin_family = hent->h_addrtype;
524 sa.sin_port = htons(0);
525 memcpy(&sa.sin_addr, *ap, hent->h_length);
527 inet_ntop(hent->h_addrtype, &sa.sin_addr,
528 addrbuf, sizeof(addrbuf));
530 free(canon_hostname);
531 canon_hostname = xstrdup(hent->h_name);
533 ip_address = xstrdup(addrbuf);
539 static int execute(struct sockaddr *addr)
541 static char line[1000];
545 char addrbuf[256] = "";
548 if (addr->sa_family == AF_INET) {
549 struct sockaddr_in *sin_addr = (void *) addr;
550 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
551 port = ntohs(sin_addr->sin_port);
553 } else if (addr && addr->sa_family == AF_INET6) {
554 struct sockaddr_in6 *sin6_addr = (void *) addr;
557 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
558 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
561 port = ntohs(sin6_addr->sin6_port);
564 loginfo("Connection from %s:%d", addrbuf, port);
565 setenv("REMOTE_ADDR", addrbuf, 1);
568 unsetenv("REMOTE_ADDR");
571 alarm(init_timeout ? init_timeout : timeout);
572 pktlen = packet_read_line(0, line, sizeof(line));
577 loginfo("Extended attributes (%d bytes) exist <%.*s>",
579 (int) pktlen - len, line + len + 1);
580 if (len && line[len-1] == '\n') {
586 free(canon_hostname);
589 hostname = canon_hostname = ip_address = tcp_port = NULL;
592 parse_host_arg(line + len + 1, pktlen - len - 1);
594 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
595 struct daemon_service *s = &(daemon_service[i]);
596 int namelen = strlen(s->name);
597 if (!prefixcmp(line, "git-") &&
598 !strncmp(s->name, line + 4, namelen) &&
599 line[namelen + 4] == ' ') {
601 * Note: The directory here is probably context sensitive,
602 * and might depend on the actual service being performed.
604 return run_service(line + namelen + 5, s);
608 logerror("Protocol error: '%s'", line);
612 static int max_connections = 32;
614 static unsigned int live_children;
616 static struct child {
619 struct sockaddr_storage address;
622 static void add_child(pid_t pid, struct sockaddr *addr, int addrlen)
624 struct child *newborn, **cradle;
627 * This must be xcalloc() -- we'll compare the whole sockaddr_storage
628 * but individual address may be shorter.
630 newborn = xcalloc(1, sizeof(*newborn));
633 memcpy(&newborn->address, addr, addrlen);
634 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
635 if (!memcmp(&(*cradle)->address, &newborn->address,
636 sizeof(newborn->address)))
638 newborn->next = *cradle;
642 static void remove_child(pid_t pid)
644 struct child **cradle, *blanket;
646 for (cradle = &firstborn; (blanket = *cradle); cradle = &blanket->next)
647 if (blanket->pid == pid) {
648 *cradle = blanket->next;
656 * This gets called if the number of connections grows
657 * past "max_connections".
659 * We kill the newest connection from a duplicate IP.
661 static void kill_some_child(void)
663 const struct child *blanket, *next;
665 if (!(blanket = firstborn))
668 for (; (next = blanket->next); blanket = next)
669 if (!memcmp(&blanket->address, &next->address,
670 sizeof(next->address))) {
671 kill(blanket->pid, SIGTERM);
676 static void check_dead_children(void)
681 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
682 const char *dead = "";
684 if (!WIFEXITED(status) || (WEXITSTATUS(status) > 0))
685 dead = " (with error)";
686 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
690 static void handle(int incoming, struct sockaddr *addr, int addrlen)
694 if (max_connections && live_children >= max_connections) {
696 sleep(1); /* give it some time to die */
697 check_dead_children();
698 if (live_children >= max_connections) {
700 logerror("Too many children, dropping connection");
705 if ((pid = fork())) {
708 logerror("Couldn't fork %s", strerror(errno));
712 add_child(pid, addr, addrlen);
723 static void child_handler(int signo)
726 * Otherwise empty handler because systemcalls will get interrupted
727 * upon signal receipt
728 * SysV needs the handler to be rearmed
730 signal(SIGCHLD, child_handler);
733 static int set_reuse_addr(int sockfd)
739 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
745 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
747 int socknum = 0, *socklist = NULL;
749 char pbuf[NI_MAXSERV];
750 struct addrinfo hints, *ai0, *ai;
754 sprintf(pbuf, "%d", listen_port);
755 memset(&hints, 0, sizeof(hints));
756 hints.ai_family = AF_UNSPEC;
757 hints.ai_socktype = SOCK_STREAM;
758 hints.ai_protocol = IPPROTO_TCP;
759 hints.ai_flags = AI_PASSIVE;
761 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
763 die("getaddrinfo() failed: %s", gai_strerror(gai));
765 for (ai = ai0; ai; ai = ai->ai_next) {
768 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
771 if (sockfd >= FD_SETSIZE) {
772 logerror("Socket descriptor too large");
778 if (ai->ai_family == AF_INET6) {
780 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
782 /* Note: error is not fatal */
786 if (set_reuse_addr(sockfd)) {
791 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
793 continue; /* not fatal */
795 if (listen(sockfd, 5) < 0) {
797 continue; /* not fatal */
800 flags = fcntl(sockfd, F_GETFD, 0);
802 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
804 socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
805 socklist[socknum++] = sockfd;
813 *socklist_p = socklist;
819 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
821 struct sockaddr_in sin;
825 memset(&sin, 0, sizeof sin);
826 sin.sin_family = AF_INET;
827 sin.sin_port = htons(listen_port);
830 /* Well, host better be an IP address here. */
831 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
834 sin.sin_addr.s_addr = htonl(INADDR_ANY);
837 sockfd = socket(AF_INET, SOCK_STREAM, 0);
841 if (set_reuse_addr(sockfd)) {
846 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
851 if (listen(sockfd, 5) < 0) {
856 flags = fcntl(sockfd, F_GETFD, 0);
858 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
860 *socklist_p = xmalloc(sizeof(int));
861 **socklist_p = sockfd;
867 static int service_loop(int socknum, int *socklist)
872 pfd = xcalloc(socknum, sizeof(struct pollfd));
874 for (i = 0; i < socknum; i++) {
875 pfd[i].fd = socklist[i];
876 pfd[i].events = POLLIN;
879 signal(SIGCHLD, child_handler);
884 check_dead_children();
886 if (poll(pfd, socknum, -1) < 0) {
887 if (errno != EINTR) {
888 logerror("Poll failed, resuming: %s",
895 for (i = 0; i < socknum; i++) {
896 if (pfd[i].revents & POLLIN) {
897 struct sockaddr_storage ss;
898 unsigned int sslen = sizeof(ss);
899 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
907 die_errno("accept returned");
910 handle(incoming, (struct sockaddr *)&ss, sslen);
916 /* if any standard file descriptor is missing open it to /dev/null */
917 static void sanitize_stdfds(void)
919 int fd = open("/dev/null", O_RDWR, 0);
920 while (fd != -1 && fd < 2)
923 die_errno("open /dev/null or dup failed");
928 static void daemonize(void)
934 die_errno("fork failed");
939 die_errno("setsid failed");
946 static void store_pid(const char *path)
948 FILE *f = fopen(path, "w");
950 die_errno("cannot open pid file '%s'", path);
951 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
952 die_errno("failed to write pid file '%s'", path);
955 static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
957 int socknum, *socklist;
959 socknum = socksetup(listen_addr, listen_port, &socklist);
961 die("unable to allocate any listen sockets on host %s port %u",
962 listen_addr, listen_port);
965 (initgroups(pass->pw_name, gid) || setgid (gid) ||
966 setuid(pass->pw_uid)))
967 die("cannot drop privileges");
969 return service_loop(socknum, socklist);
972 int main(int argc, char **argv)
975 char *listen_addr = NULL;
977 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
979 struct passwd *pass = NULL;
984 git_extract_argv0_path(argv[0]);
986 for (i = 1; i < argc; i++) {
989 if (!prefixcmp(arg, "--listen=")) {
990 listen_addr = xstrdup_tolower(arg + 9);
993 if (!prefixcmp(arg, "--port=")) {
996 n = strtoul(arg+7, &end, 0);
997 if (arg[7] && !*end) {
1002 if (!strcmp(arg, "--inetd")) {
1007 if (!strcmp(arg, "--verbose")) {
1011 if (!strcmp(arg, "--syslog")) {
1015 if (!strcmp(arg, "--export-all")) {
1016 export_all_trees = 1;
1019 if (!prefixcmp(arg, "--timeout=")) {
1020 timeout = atoi(arg+10);
1023 if (!prefixcmp(arg, "--init-timeout=")) {
1024 init_timeout = atoi(arg+15);
1027 if (!prefixcmp(arg, "--max-connections=")) {
1028 max_connections = atoi(arg+18);
1029 if (max_connections < 0)
1030 max_connections = 0; /* unlimited */
1033 if (!strcmp(arg, "--strict-paths")) {
1037 if (!prefixcmp(arg, "--base-path=")) {
1041 if (!strcmp(arg, "--base-path-relaxed")) {
1042 base_path_relaxed = 1;
1045 if (!prefixcmp(arg, "--interpolated-path=")) {
1046 interpolated_path = arg+20;
1049 if (!strcmp(arg, "--reuseaddr")) {
1053 if (!strcmp(arg, "--user-path")) {
1057 if (!prefixcmp(arg, "--user-path=")) {
1058 user_path = arg + 12;
1061 if (!prefixcmp(arg, "--pid-file=")) {
1062 pid_file = arg + 11;
1065 if (!strcmp(arg, "--detach")) {
1070 if (!prefixcmp(arg, "--user=")) {
1071 user_name = arg + 7;
1074 if (!prefixcmp(arg, "--group=")) {
1075 group_name = arg + 8;
1078 if (!prefixcmp(arg, "--enable=")) {
1079 enable_service(arg + 9, 1);
1082 if (!prefixcmp(arg, "--disable=")) {
1083 enable_service(arg + 10, 0);
1086 if (!prefixcmp(arg, "--allow-override=")) {
1087 make_service_overridable(arg + 17, 1);
1090 if (!prefixcmp(arg, "--forbid-override=")) {
1091 make_service_overridable(arg + 18, 0);
1094 if (!strcmp(arg, "--")) {
1095 ok_paths = &argv[i+1];
1097 } else if (arg[0] != '-') {
1098 ok_paths = &argv[i];
1102 usage(daemon_usage);
1106 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1107 set_die_routine(daemon_die);
1109 /* avoid splitting a message in the middle */
1110 setvbuf(stderr, NULL, _IOLBF, 0);
1112 if (inetd_mode && (group_name || user_name))
1113 die("--user and --group are incompatible with --inetd");
1115 if (inetd_mode && (listen_port || listen_addr))
1116 die("--listen= and --port= are incompatible with --inetd");
1117 else if (listen_port == 0)
1118 listen_port = DEFAULT_GIT_PORT;
1120 if (group_name && !user_name)
1121 die("--group supplied without --user");
1124 pass = getpwnam(user_name);
1126 die("user not found - %s", user_name);
1131 group = getgrnam(group_name);
1133 die("group not found - %s", group_name);
1135 gid = group->gr_gid;
1139 if (strict_paths && (!ok_paths || !*ok_paths))
1140 die("option --strict-paths requires a whitelist");
1142 if (base_path && !is_directory(base_path))
1143 die("base-path '%s' does not exist or is not a directory",
1147 struct sockaddr_storage ss;
1148 struct sockaddr *peer = (struct sockaddr *)&ss;
1149 socklen_t slen = sizeof(ss);
1151 if (!freopen("/dev/null", "w", stderr))
1152 die_errno("failed to redirect stderr to /dev/null");
1154 if (getpeername(0, peer, &slen))
1157 return execute(peer);
1162 loginfo("Ready to rumble");
1168 store_pid(pid_file);
1170 return serve(listen_addr, listen_port, pass, gid);