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 char *path_ok(char *directory)
108 static char rpath[PATH_MAX];
109 static char interp_path[PATH_MAX];
115 if (daemon_avoid_alias(dir)) {
116 logerror("'%s': aliased", dir);
122 logerror("'%s': User-path not allowed", dir);
126 /* Got either "~alice" or "~alice/foo";
127 * rewrite them to "~alice/%s" or
130 int namlen, restlen = strlen(dir);
131 char *slash = strchr(dir, '/');
133 slash = dir + restlen;
134 namlen = slash - dir;
136 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
137 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
138 namlen, dir, user_path, restlen, slash);
142 else if (interpolated_path && saw_extended_args) {
143 struct strbuf expanded_path = STRBUF_INIT;
144 struct strbuf_expand_dict_entry dict[] = {
146 { "CH", canon_hostname },
147 { "IP", ip_address },
155 /* Allow only absolute */
156 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
160 strbuf_expand(&expanded_path, interpolated_path,
161 strbuf_expand_dict_cb, &dict);
162 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
163 strbuf_release(&expanded_path);
164 loginfo("Interpolated dir '%s'", interp_path);
168 else if (base_path) {
170 /* Allow only absolute */
171 logerror("'%s': Non-absolute path denied (base-path active)", dir);
174 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
178 path = enter_repo(dir, strict_paths);
179 if (!path && base_path && base_path_relaxed) {
181 * if we fail and base_path_relaxed is enabled, try without
182 * prefixing the base path
185 path = enter_repo(dir, strict_paths);
189 logerror("'%s' does not appear to be a git repository", dir);
193 if ( ok_paths && *ok_paths ) {
195 int pathlen = strlen(path);
197 /* The validation is done on the paths after enter_repo
198 * appends optional {.git,.git/.git} and friends, but
199 * it does not use getcwd(). So if your /pub is
200 * a symlink to /mnt/pub, you can whitelist /pub and
201 * do not have to say /mnt/pub.
204 for ( pp = ok_paths ; *pp ; pp++ ) {
205 int len = strlen(*pp);
206 if (len <= pathlen &&
207 !memcmp(*pp, path, len) &&
208 (path[len] == '\0' ||
209 (!strict_paths && path[len] == '/')))
214 /* be backwards compatible */
219 logerror("'%s': not in whitelist", path);
220 return NULL; /* Fallthrough. Deny by default */
223 typedef int (*daemon_service_fn)(void);
224 struct daemon_service {
226 const char *config_name;
227 daemon_service_fn fn;
232 static struct daemon_service *service_looking_at;
233 static int service_enabled;
235 static int git_daemon_config(const char *var, const char *value, void *cb)
237 if (!prefixcmp(var, "daemon.") &&
238 !strcmp(var + 7, service_looking_at->config_name)) {
239 service_enabled = git_config_bool(var, value);
243 /* we are not interested in parsing any other configuration here */
247 static int run_service(char *dir, struct daemon_service *service)
250 int enabled = service->enabled;
252 loginfo("Request %s for '%s'", service->name, dir);
254 if (!enabled && !service->overridable) {
255 logerror("'%s': service not enabled.", service->name);
260 if (!(path = path_ok(dir)))
264 * Security on the cheap.
266 * We want a readable HEAD, usable "objects" directory, and
267 * a "git-daemon-export-ok" flag that says that the other side
268 * is ok with us doing this.
270 * path_ok() uses enter_repo() and does whitelist checking.
271 * We only need to make sure the repository is exported.
274 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
275 logerror("'%s': repository not exported.", path);
280 if (service->overridable) {
281 service_looking_at = service;
282 service_enabled = -1;
283 git_config(git_daemon_config, NULL);
284 if (0 <= service_enabled)
285 enabled = service_enabled;
288 logerror("'%s': service not enabled for '%s'",
289 service->name, path);
295 * We'll ignore SIGTERM from now on, we have a
298 signal(SIGTERM, SIG_IGN);
300 return service->fn();
303 static void copy_to_log(int fd)
305 struct strbuf line = STRBUF_INIT;
308 fp = fdopen(fd, "r");
310 logerror("fdopen of error channel failed");
315 while (strbuf_getline(&line, fp, '\n') != EOF) {
316 logerror("%s", line.buf);
317 strbuf_setlen(&line, 0);
320 strbuf_release(&line);
324 static int run_service_command(const char **argv)
326 struct child_process cld;
328 memset(&cld, 0, sizeof(cld));
332 if (start_command(&cld))
338 copy_to_log(cld.err);
340 return finish_command(&cld);
343 static int upload_pack(void)
345 /* Timeout as string */
346 char timeout_buf[64];
347 const char *argv[] = { "upload-pack", "--strict", timeout_buf, ".", NULL };
349 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
350 return run_service_command(argv);
353 static int upload_archive(void)
355 static const char *argv[] = { "upload-archive", ".", NULL };
356 return run_service_command(argv);
359 static int receive_pack(void)
361 static const char *argv[] = { "receive-pack", ".", NULL };
362 return run_service_command(argv);
365 static struct daemon_service daemon_service[] = {
366 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
367 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
368 { "receive-pack", "receivepack", receive_pack, 0, 1 },
371 static void enable_service(const char *name, int ena)
374 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
375 if (!strcmp(daemon_service[i].name, name)) {
376 daemon_service[i].enabled = ena;
380 die("No such service %s", name);
383 static void make_service_overridable(const char *name, int ena)
386 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
387 if (!strcmp(daemon_service[i].name, name)) {
388 daemon_service[i].overridable = ena;
392 die("No such service %s", name);
395 static char *xstrdup_tolower(const char *str)
397 char *p, *dup = xstrdup(str);
398 for (p = dup; *p; p++)
404 * Read the host as supplied by the client connection.
406 static void parse_host_arg(char *extra_args, int buflen)
410 char *end = extra_args + buflen;
412 if (extra_args < end && *extra_args) {
413 saw_extended_args = 1;
414 if (strncasecmp("host=", extra_args, 5) == 0) {
415 val = extra_args + 5;
416 vallen = strlen(val) + 1;
418 /* Split <host>:<port> at colon. */
420 char *port = strrchr(host, ':');
425 tcp_port = xstrdup(port);
428 hostname = xstrdup_tolower(host);
431 /* On to the next one */
432 extra_args = val + vallen;
434 if (extra_args < end && *extra_args)
435 die("Invalid request");
439 * Locate canonical hostname and its IP address.
443 struct addrinfo hints;
446 static char addrbuf[HOST_NAME_MAX + 1];
448 memset(&hints, 0, sizeof(hints));
449 hints.ai_flags = AI_CANONNAME;
451 gai = getaddrinfo(hostname, NULL, &hints, &ai);
453 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
455 inet_ntop(AF_INET, &sin_addr->sin_addr,
456 addrbuf, sizeof(addrbuf));
458 ip_address = xstrdup(addrbuf);
460 free(canon_hostname);
461 canon_hostname = xstrdup(ai->ai_canonname ?
462 ai->ai_canonname : ip_address);
467 struct hostent *hent;
468 struct sockaddr_in sa;
470 static char addrbuf[HOST_NAME_MAX + 1];
472 hent = gethostbyname(hostname);
474 ap = hent->h_addr_list;
475 memset(&sa, 0, sizeof sa);
476 sa.sin_family = hent->h_addrtype;
477 sa.sin_port = htons(0);
478 memcpy(&sa.sin_addr, *ap, hent->h_length);
480 inet_ntop(hent->h_addrtype, &sa.sin_addr,
481 addrbuf, sizeof(addrbuf));
483 free(canon_hostname);
484 canon_hostname = xstrdup(hent->h_name);
486 ip_address = xstrdup(addrbuf);
492 static int execute(struct sockaddr *addr)
494 static char line[1000];
498 char addrbuf[256] = "";
501 if (addr->sa_family == AF_INET) {
502 struct sockaddr_in *sin_addr = (void *) addr;
503 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
504 port = ntohs(sin_addr->sin_port);
506 } else if (addr && addr->sa_family == AF_INET6) {
507 struct sockaddr_in6 *sin6_addr = (void *) addr;
510 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
511 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
514 port = ntohs(sin6_addr->sin6_port);
517 loginfo("Connection from %s:%d", addrbuf, port);
518 setenv("REMOTE_ADDR", addrbuf, 1);
521 unsetenv("REMOTE_ADDR");
524 alarm(init_timeout ? init_timeout : timeout);
525 pktlen = packet_read_line(0, line, sizeof(line));
530 loginfo("Extended attributes (%d bytes) exist <%.*s>",
532 (int) pktlen - len, line + len + 1);
533 if (len && line[len-1] == '\n') {
539 free(canon_hostname);
542 hostname = canon_hostname = ip_address = tcp_port = NULL;
545 parse_host_arg(line + len + 1, pktlen - len - 1);
547 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
548 struct daemon_service *s = &(daemon_service[i]);
549 int namelen = strlen(s->name);
550 if (!prefixcmp(line, "git-") &&
551 !strncmp(s->name, line + 4, namelen) &&
552 line[namelen + 4] == ' ') {
554 * Note: The directory here is probably context sensitive,
555 * and might depend on the actual service being performed.
557 return run_service(line + namelen + 5, s);
561 logerror("Protocol error: '%s'", line);
565 static int max_connections = 32;
567 static unsigned int live_children;
569 static struct child {
572 struct sockaddr_storage address;
575 static void add_child(pid_t pid, struct sockaddr *addr, int addrlen)
577 struct child *newborn, **cradle;
580 * This must be xcalloc() -- we'll compare the whole sockaddr_storage
581 * but individual address may be shorter.
583 newborn = xcalloc(1, sizeof(*newborn));
586 memcpy(&newborn->address, addr, addrlen);
587 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
588 if (!memcmp(&(*cradle)->address, &newborn->address,
589 sizeof(newborn->address)))
591 newborn->next = *cradle;
595 static void remove_child(pid_t pid)
597 struct child **cradle, *blanket;
599 for (cradle = &firstborn; (blanket = *cradle); cradle = &blanket->next)
600 if (blanket->pid == pid) {
601 *cradle = blanket->next;
609 * This gets called if the number of connections grows
610 * past "max_connections".
612 * We kill the newest connection from a duplicate IP.
614 static void kill_some_child(void)
616 const struct child *blanket, *next;
618 if (!(blanket = firstborn))
621 for (; (next = blanket->next); blanket = next)
622 if (!memcmp(&blanket->address, &next->address,
623 sizeof(next->address))) {
624 kill(blanket->pid, SIGTERM);
629 static void check_dead_children(void)
634 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
635 const char *dead = "";
637 if (!WIFEXITED(status) || (WEXITSTATUS(status) > 0))
638 dead = " (with error)";
639 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
643 static void handle(int incoming, struct sockaddr *addr, int addrlen)
647 if (max_connections && live_children >= max_connections) {
649 sleep(1); /* give it some time to die */
650 check_dead_children();
651 if (live_children >= max_connections) {
653 logerror("Too many children, dropping connection");
658 if ((pid = fork())) {
661 logerror("Couldn't fork %s", strerror(errno));
665 add_child(pid, addr, addrlen);
676 static void child_handler(int signo)
679 * Otherwise empty handler because systemcalls will get interrupted
680 * upon signal receipt
681 * SysV needs the handler to be rearmed
683 signal(SIGCHLD, child_handler);
686 static int set_reuse_addr(int sockfd)
692 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
698 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
700 int socknum = 0, *socklist = NULL;
702 char pbuf[NI_MAXSERV];
703 struct addrinfo hints, *ai0, *ai;
707 sprintf(pbuf, "%d", listen_port);
708 memset(&hints, 0, sizeof(hints));
709 hints.ai_family = AF_UNSPEC;
710 hints.ai_socktype = SOCK_STREAM;
711 hints.ai_protocol = IPPROTO_TCP;
712 hints.ai_flags = AI_PASSIVE;
714 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
716 die("getaddrinfo() failed: %s", gai_strerror(gai));
718 for (ai = ai0; ai; ai = ai->ai_next) {
721 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
724 if (sockfd >= FD_SETSIZE) {
725 logerror("Socket descriptor too large");
731 if (ai->ai_family == AF_INET6) {
733 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
735 /* Note: error is not fatal */
739 if (set_reuse_addr(sockfd)) {
744 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
746 continue; /* not fatal */
748 if (listen(sockfd, 5) < 0) {
750 continue; /* not fatal */
753 flags = fcntl(sockfd, F_GETFD, 0);
755 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
757 socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
758 socklist[socknum++] = sockfd;
766 *socklist_p = socklist;
772 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
774 struct sockaddr_in sin;
778 memset(&sin, 0, sizeof sin);
779 sin.sin_family = AF_INET;
780 sin.sin_port = htons(listen_port);
783 /* Well, host better be an IP address here. */
784 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
787 sin.sin_addr.s_addr = htonl(INADDR_ANY);
790 sockfd = socket(AF_INET, SOCK_STREAM, 0);
794 if (set_reuse_addr(sockfd)) {
799 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
804 if (listen(sockfd, 5) < 0) {
809 flags = fcntl(sockfd, F_GETFD, 0);
811 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
813 *socklist_p = xmalloc(sizeof(int));
814 **socklist_p = sockfd;
820 static int service_loop(int socknum, int *socklist)
825 pfd = xcalloc(socknum, sizeof(struct pollfd));
827 for (i = 0; i < socknum; i++) {
828 pfd[i].fd = socklist[i];
829 pfd[i].events = POLLIN;
832 signal(SIGCHLD, child_handler);
837 check_dead_children();
839 if (poll(pfd, socknum, -1) < 0) {
840 if (errno != EINTR) {
841 logerror("Poll failed, resuming: %s",
848 for (i = 0; i < socknum; i++) {
849 if (pfd[i].revents & POLLIN) {
850 struct sockaddr_storage ss;
851 unsigned int sslen = sizeof(ss);
852 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
860 die_errno("accept returned");
863 handle(incoming, (struct sockaddr *)&ss, sslen);
869 /* if any standard file descriptor is missing open it to /dev/null */
870 static void sanitize_stdfds(void)
872 int fd = open("/dev/null", O_RDWR, 0);
873 while (fd != -1 && fd < 2)
876 die_errno("open /dev/null or dup failed");
881 static void daemonize(void)
887 die_errno("fork failed");
892 die_errno("setsid failed");
899 static void store_pid(const char *path)
901 FILE *f = fopen(path, "w");
903 die_errno("cannot open pid file '%s'", path);
904 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
905 die_errno("failed to write pid file '%s'", path);
908 static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
910 int socknum, *socklist;
912 socknum = socksetup(listen_addr, listen_port, &socklist);
914 die("unable to allocate any listen sockets on host %s port %u",
915 listen_addr, listen_port);
918 (initgroups(pass->pw_name, gid) || setgid (gid) ||
919 setuid(pass->pw_uid)))
920 die("cannot drop privileges");
922 return service_loop(socknum, socklist);
925 int main(int argc, char **argv)
928 char *listen_addr = NULL;
930 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
932 struct passwd *pass = NULL;
937 git_extract_argv0_path(argv[0]);
939 for (i = 1; i < argc; i++) {
942 if (!prefixcmp(arg, "--listen=")) {
943 listen_addr = xstrdup_tolower(arg + 9);
946 if (!prefixcmp(arg, "--port=")) {
949 n = strtoul(arg+7, &end, 0);
950 if (arg[7] && !*end) {
955 if (!strcmp(arg, "--inetd")) {
960 if (!strcmp(arg, "--verbose")) {
964 if (!strcmp(arg, "--syslog")) {
968 if (!strcmp(arg, "--export-all")) {
969 export_all_trees = 1;
972 if (!prefixcmp(arg, "--timeout=")) {
973 timeout = atoi(arg+10);
976 if (!prefixcmp(arg, "--init-timeout=")) {
977 init_timeout = atoi(arg+15);
980 if (!prefixcmp(arg, "--max-connections=")) {
981 max_connections = atoi(arg+18);
982 if (max_connections < 0)
983 max_connections = 0; /* unlimited */
986 if (!strcmp(arg, "--strict-paths")) {
990 if (!prefixcmp(arg, "--base-path=")) {
994 if (!strcmp(arg, "--base-path-relaxed")) {
995 base_path_relaxed = 1;
998 if (!prefixcmp(arg, "--interpolated-path=")) {
999 interpolated_path = arg+20;
1002 if (!strcmp(arg, "--reuseaddr")) {
1006 if (!strcmp(arg, "--user-path")) {
1010 if (!prefixcmp(arg, "--user-path=")) {
1011 user_path = arg + 12;
1014 if (!prefixcmp(arg, "--pid-file=")) {
1015 pid_file = arg + 11;
1018 if (!strcmp(arg, "--detach")) {
1023 if (!prefixcmp(arg, "--user=")) {
1024 user_name = arg + 7;
1027 if (!prefixcmp(arg, "--group=")) {
1028 group_name = arg + 8;
1031 if (!prefixcmp(arg, "--enable=")) {
1032 enable_service(arg + 9, 1);
1035 if (!prefixcmp(arg, "--disable=")) {
1036 enable_service(arg + 10, 0);
1039 if (!prefixcmp(arg, "--allow-override=")) {
1040 make_service_overridable(arg + 17, 1);
1043 if (!prefixcmp(arg, "--forbid-override=")) {
1044 make_service_overridable(arg + 18, 0);
1047 if (!strcmp(arg, "--")) {
1048 ok_paths = &argv[i+1];
1050 } else if (arg[0] != '-') {
1051 ok_paths = &argv[i];
1055 usage(daemon_usage);
1059 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1060 set_die_routine(daemon_die);
1062 /* avoid splitting a message in the middle */
1063 setvbuf(stderr, NULL, _IOLBF, 0);
1065 if (inetd_mode && (group_name || user_name))
1066 die("--user and --group are incompatible with --inetd");
1068 if (inetd_mode && (listen_port || listen_addr))
1069 die("--listen= and --port= are incompatible with --inetd");
1070 else if (listen_port == 0)
1071 listen_port = DEFAULT_GIT_PORT;
1073 if (group_name && !user_name)
1074 die("--group supplied without --user");
1077 pass = getpwnam(user_name);
1079 die("user not found - %s", user_name);
1084 group = getgrnam(group_name);
1086 die("group not found - %s", group_name);
1088 gid = group->gr_gid;
1092 if (strict_paths && (!ok_paths || !*ok_paths))
1093 die("option --strict-paths requires a whitelist");
1095 if (base_path && !is_directory(base_path))
1096 die("base-path '%s' does not exist or is not a directory",
1100 struct sockaddr_storage ss;
1101 struct sockaddr *peer = (struct sockaddr *)&ss;
1102 socklen_t slen = sizeof(ss);
1104 if (!freopen("/dev/null", "w", stderr))
1105 die_errno("failed to redirect stderr to /dev/null");
1107 if (getpeername(0, peer, &slen))
1110 return execute(peer);
1115 loginfo("Ready to rumble");
1121 store_pid(pid_file);
1123 return serve(listen_addr, listen_port, pass, gid);