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;
60 static char *directory;
62 static void logreport(int priority, const char *err, va_list params)
66 vsnprintf(buf, sizeof(buf), err, params);
67 syslog(priority, "%s", buf);
70 * Since stderr is set to linebuffered mode, the
71 * logging of different processes will not overlap
73 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
74 vfprintf(stderr, err, params);
79 static void logerror(const char *err, ...)
82 va_start(params, err);
83 logreport(LOG_ERR, err, params);
87 static void loginfo(const char *err, ...)
92 va_start(params, err);
93 logreport(LOG_INFO, err, params);
97 static void NORETURN daemon_die(const char *err, va_list params)
99 logreport(LOG_ERR, err, params);
103 static int avoid_alias(char *p)
108 * This resurrects the belts and suspenders paranoia check by HPA
109 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
110 * does not do getcwd() based path canonicalizations.
112 * sl becomes true immediately after seeing '/' and continues to
113 * be true as long as dots continue after that without intervening
116 if (!p || (*p != '/' && *p != '~'))
126 else if (ch == '/') {
128 /* reject //, /./ and /../ */
133 if (0 < ndot && ndot < 3)
134 /* reject /.$ and /..$ */
143 else if (ch == '/') {
150 static char *path_ok(void)
152 static char rpath[PATH_MAX];
153 static char interp_path[PATH_MAX];
154 int retried_path = 0;
160 if (avoid_alias(dir)) {
161 logerror("'%s': aliased", dir);
167 logerror("'%s': User-path not allowed", dir);
171 /* Got either "~alice" or "~alice/foo";
172 * rewrite them to "~alice/%s" or
175 int namlen, restlen = strlen(dir);
176 char *slash = strchr(dir, '/');
178 slash = dir + restlen;
179 namlen = slash - dir;
181 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
182 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
183 namlen, dir, user_path, restlen, slash);
187 else if (interpolated_path && saw_extended_args) {
188 struct strbuf expanded_path = STRBUF_INIT;
189 struct strbuf_expand_dict_entry dict[] = {
191 { "CH", canon_hostname },
192 { "IP", ip_address },
200 /* Allow only absolute */
201 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
205 strbuf_expand(&expanded_path, interpolated_path,
206 strbuf_expand_dict_cb, &dict);
207 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
208 strbuf_release(&expanded_path);
209 loginfo("Interpolated dir '%s'", interp_path);
213 else if (base_path) {
215 /* Allow only absolute */
216 logerror("'%s': Non-absolute path denied (base-path active)", dir);
219 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
224 path = enter_repo(dir, strict_paths);
229 * if we fail and base_path_relaxed is enabled, try without
230 * prefixing the base path
232 if (base_path && base_path_relaxed && !retried_path) {
241 logerror("'%s': unable to chdir or not a git archive", dir);
245 if ( ok_paths && *ok_paths ) {
247 int pathlen = strlen(path);
249 /* The validation is done on the paths after enter_repo
250 * appends optional {.git,.git/.git} and friends, but
251 * it does not use getcwd(). So if your /pub is
252 * a symlink to /mnt/pub, you can whitelist /pub and
253 * do not have to say /mnt/pub.
256 for ( pp = ok_paths ; *pp ; pp++ ) {
257 int len = strlen(*pp);
258 if (len <= pathlen &&
259 !memcmp(*pp, path, len) &&
260 (path[len] == '\0' ||
261 (!strict_paths && path[len] == '/')))
266 /* be backwards compatible */
271 logerror("'%s': not in whitelist", path);
272 return NULL; /* Fallthrough. Deny by default */
275 typedef int (*daemon_service_fn)(void);
276 struct daemon_service {
278 const char *config_name;
279 daemon_service_fn fn;
284 static struct daemon_service *service_looking_at;
285 static int service_enabled;
287 static int git_daemon_config(const char *var, const char *value, void *cb)
289 if (!prefixcmp(var, "daemon.") &&
290 !strcmp(var + 7, service_looking_at->config_name)) {
291 service_enabled = git_config_bool(var, value);
295 /* we are not interested in parsing any other configuration here */
299 static int run_service(struct daemon_service *service)
302 int enabled = service->enabled;
304 loginfo("Request %s for '%s'", service->name, directory);
306 if (!enabled && !service->overridable) {
307 logerror("'%s': service not enabled.", service->name);
312 if (!(path = path_ok()))
316 * Security on the cheap.
318 * We want a readable HEAD, usable "objects" directory, and
319 * a "git-daemon-export-ok" flag that says that the other side
320 * is ok with us doing this.
322 * path_ok() uses enter_repo() and does whitelist checking.
323 * We only need to make sure the repository is exported.
326 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
327 logerror("'%s': repository not exported.", path);
332 if (service->overridable) {
333 service_looking_at = service;
334 service_enabled = -1;
335 git_config(git_daemon_config, NULL);
336 if (0 <= service_enabled)
337 enabled = service_enabled;
340 logerror("'%s': service not enabled for '%s'",
341 service->name, path);
347 * We'll ignore SIGTERM from now on, we have a
350 signal(SIGTERM, SIG_IGN);
352 return service->fn();
355 static int upload_pack(void)
357 /* Timeout as string */
358 char timeout_buf[64];
360 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
362 /* git-upload-pack only ever reads stuff, so this is safe */
363 execl_git_cmd("upload-pack", "--strict", timeout_buf, ".", NULL);
367 static int upload_archive(void)
369 execl_git_cmd("upload-archive", ".", NULL);
373 static int receive_pack(void)
375 execl_git_cmd("receive-pack", ".", NULL);
379 static struct daemon_service daemon_service[] = {
380 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
381 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
382 { "receive-pack", "receivepack", receive_pack, 0, 1 },
385 static void enable_service(const char *name, int ena)
388 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
389 if (!strcmp(daemon_service[i].name, name)) {
390 daemon_service[i].enabled = ena;
394 die("No such service %s", name);
397 static void make_service_overridable(const char *name, int ena)
400 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
401 if (!strcmp(daemon_service[i].name, name)) {
402 daemon_service[i].overridable = ena;
406 die("No such service %s", name);
410 * Separate the "extra args" information as supplied by the client connection.
412 static void parse_extra_args(char *extra_args, int buflen)
416 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 static void fill_in_extra_table_entries(void)
448 * Replace literal host with lowercase-ized hostname.
457 * Locate canonical hostname and its IP address.
461 struct addrinfo hints;
462 struct addrinfo *ai, *ai0;
464 static char addrbuf[HOST_NAME_MAX + 1];
466 memset(&hints, 0, sizeof(hints));
467 hints.ai_flags = AI_CANONNAME;
469 gai = getaddrinfo(hostname, 0, &hints, &ai0);
471 for (ai = ai0; ai; ai = ai->ai_next) {
472 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
474 inet_ntop(AF_INET, &sin_addr->sin_addr,
475 addrbuf, sizeof(addrbuf));
476 free(canon_hostname);
477 canon_hostname = xstrdup(ai->ai_canonname);
479 ip_address = xstrdup(addrbuf);
487 struct hostent *hent;
488 struct sockaddr_in sa;
490 static char addrbuf[HOST_NAME_MAX + 1];
492 hent = gethostbyname(hostname);
494 ap = hent->h_addr_list;
495 memset(&sa, 0, sizeof sa);
496 sa.sin_family = hent->h_addrtype;
497 sa.sin_port = htons(0);
498 memcpy(&sa.sin_addr, *ap, hent->h_length);
500 inet_ntop(hent->h_addrtype, &sa.sin_addr,
501 addrbuf, sizeof(addrbuf));
503 free(canon_hostname);
504 canon_hostname = xstrdup(hent->h_name);
506 ip_address = xstrdup(addrbuf);
512 static int execute(struct sockaddr *addr)
514 static char line[1000];
518 char addrbuf[256] = "";
521 if (addr->sa_family == AF_INET) {
522 struct sockaddr_in *sin_addr = (void *) addr;
523 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
524 port = ntohs(sin_addr->sin_port);
526 } else if (addr && addr->sa_family == AF_INET6) {
527 struct sockaddr_in6 *sin6_addr = (void *) addr;
530 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
531 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
534 port = ntohs(sin6_addr->sin6_port);
537 loginfo("Connection from %s:%d", addrbuf, port);
538 setenv("REMOTE_ADDR", addrbuf, 1);
541 unsetenv("REMOTE_ADDR");
544 alarm(init_timeout ? init_timeout : timeout);
545 pktlen = packet_read_line(0, line, sizeof(line));
550 loginfo("Extended attributes (%d bytes) exist <%.*s>",
552 (int) pktlen - len, line + len + 1);
553 if (len && line[len-1] == '\n') {
559 free(canon_hostname);
563 hostname = canon_hostname = ip_address = tcp_port = directory = NULL;
566 parse_extra_args(line + len + 1, pktlen - len - 1);
567 fill_in_extra_table_entries();
570 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
571 struct daemon_service *s = &(daemon_service[i]);
572 int namelen = strlen(s->name);
573 if (!prefixcmp(line, "git-") &&
574 !strncmp(s->name, line + 4, namelen) &&
575 line[namelen + 4] == ' ') {
577 * Note: The directory here is probably context sensitive,
578 * and might depend on the actual service being performed.
581 directory = xstrdup(line + namelen + 5);
582 return run_service(s);
586 logerror("Protocol error: '%s'", line);
590 static int max_connections = 32;
592 static unsigned int live_children;
594 static struct child {
597 struct sockaddr_storage address;
600 static void add_child(pid_t pid, struct sockaddr *addr, int addrlen)
602 struct child *newborn, **cradle;
605 * This must be xcalloc() -- we'll compare the whole sockaddr_storage
606 * but individual address may be shorter.
608 newborn = xcalloc(1, sizeof(*newborn));
611 memcpy(&newborn->address, addr, addrlen);
612 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
613 if (!memcmp(&(*cradle)->address, &newborn->address,
614 sizeof(newborn->address)))
616 newborn->next = *cradle;
620 static void remove_child(pid_t pid)
622 struct child **cradle, *blanket;
624 for (cradle = &firstborn; (blanket = *cradle); cradle = &blanket->next)
625 if (blanket->pid == pid) {
626 *cradle = blanket->next;
634 * This gets called if the number of connections grows
635 * past "max_connections".
637 * We kill the newest connection from a duplicate IP.
639 static void kill_some_child(void)
641 const struct child *blanket, *next;
643 if (!(blanket = firstborn))
646 for (; (next = blanket->next); blanket = next)
647 if (!memcmp(&blanket->address, &next->address,
648 sizeof(next->address))) {
649 kill(blanket->pid, SIGTERM);
654 static void check_dead_children(void)
659 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
660 const char *dead = "";
662 if (!WIFEXITED(status) || (WEXITSTATUS(status) > 0))
663 dead = " (with error)";
664 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
668 static void handle(int incoming, struct sockaddr *addr, int addrlen)
672 if (max_connections && live_children >= max_connections) {
674 sleep(1); /* give it some time to die */
675 check_dead_children();
676 if (live_children >= max_connections) {
678 logerror("Too many children, dropping connection");
683 if ((pid = fork())) {
686 logerror("Couldn't fork %s", strerror(errno));
690 add_child(pid, addr, addrlen);
701 static void child_handler(int signo)
704 * Otherwise empty handler because systemcalls will get interrupted
705 * upon signal receipt
706 * SysV needs the handler to be rearmed
708 signal(SIGCHLD, child_handler);
711 static int set_reuse_addr(int sockfd)
717 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
723 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
725 int socknum = 0, *socklist = NULL;
727 char pbuf[NI_MAXSERV];
728 struct addrinfo hints, *ai0, *ai;
732 sprintf(pbuf, "%d", listen_port);
733 memset(&hints, 0, sizeof(hints));
734 hints.ai_family = AF_UNSPEC;
735 hints.ai_socktype = SOCK_STREAM;
736 hints.ai_protocol = IPPROTO_TCP;
737 hints.ai_flags = AI_PASSIVE;
739 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
741 die("getaddrinfo() failed: %s\n", gai_strerror(gai));
743 for (ai = ai0; ai; ai = ai->ai_next) {
746 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
749 if (sockfd >= FD_SETSIZE) {
750 logerror("Socket descriptor too large");
756 if (ai->ai_family == AF_INET6) {
758 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
760 /* Note: error is not fatal */
764 if (set_reuse_addr(sockfd)) {
769 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
771 continue; /* not fatal */
773 if (listen(sockfd, 5) < 0) {
775 continue; /* not fatal */
778 flags = fcntl(sockfd, F_GETFD, 0);
780 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
782 socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
783 socklist[socknum++] = sockfd;
791 *socklist_p = socklist;
797 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
799 struct sockaddr_in sin;
803 memset(&sin, 0, sizeof sin);
804 sin.sin_family = AF_INET;
805 sin.sin_port = htons(listen_port);
808 /* Well, host better be an IP address here. */
809 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
812 sin.sin_addr.s_addr = htonl(INADDR_ANY);
815 sockfd = socket(AF_INET, SOCK_STREAM, 0);
819 if (set_reuse_addr(sockfd)) {
824 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
829 if (listen(sockfd, 5) < 0) {
834 flags = fcntl(sockfd, F_GETFD, 0);
836 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
838 *socklist_p = xmalloc(sizeof(int));
839 **socklist_p = sockfd;
845 static int service_loop(int socknum, int *socklist)
850 pfd = xcalloc(socknum, sizeof(struct pollfd));
852 for (i = 0; i < socknum; i++) {
853 pfd[i].fd = socklist[i];
854 pfd[i].events = POLLIN;
857 signal(SIGCHLD, child_handler);
862 check_dead_children();
864 if (poll(pfd, socknum, -1) < 0) {
865 if (errno != EINTR) {
866 logerror("Poll failed, resuming: %s",
873 for (i = 0; i < socknum; i++) {
874 if (pfd[i].revents & POLLIN) {
875 struct sockaddr_storage ss;
876 unsigned int sslen = sizeof(ss);
877 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
885 die("accept returned %s", strerror(errno));
888 handle(incoming, (struct sockaddr *)&ss, sslen);
894 /* if any standard file descriptor is missing open it to /dev/null */
895 static void sanitize_stdfds(void)
897 int fd = open("/dev/null", O_RDWR, 0);
898 while (fd != -1 && fd < 2)
901 die("open /dev/null or dup failed: %s", strerror(errno));
906 static void daemonize(void)
912 die("fork failed: %s", strerror(errno));
917 die("setsid failed: %s", strerror(errno));
924 static void store_pid(const char *path)
926 FILE *f = fopen(path, "w");
928 die("cannot open pid file %s: %s", path, strerror(errno));
929 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
930 die("failed to write pid file %s: %s", path, strerror(errno));
933 static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
935 int socknum, *socklist;
937 socknum = socksetup(listen_addr, listen_port, &socklist);
939 die("unable to allocate any listen sockets on host %s port %u",
940 listen_addr, listen_port);
943 (initgroups(pass->pw_name, gid) || setgid (gid) ||
944 setuid(pass->pw_uid)))
945 die("cannot drop privileges");
947 return service_loop(socknum, socklist);
950 int main(int argc, char **argv)
953 char *listen_addr = NULL;
955 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
957 struct passwd *pass = NULL;
962 for (i = 1; i < argc; i++) {
965 if (!prefixcmp(arg, "--listen=")) {
967 char *ph = listen_addr = xmalloc(strlen(arg + 9) + 1);
969 *ph++ = tolower(*p++);
973 if (!prefixcmp(arg, "--port=")) {
976 n = strtoul(arg+7, &end, 0);
977 if (arg[7] && !*end) {
982 if (!strcmp(arg, "--inetd")) {
987 if (!strcmp(arg, "--verbose")) {
991 if (!strcmp(arg, "--syslog")) {
995 if (!strcmp(arg, "--export-all")) {
996 export_all_trees = 1;
999 if (!prefixcmp(arg, "--timeout=")) {
1000 timeout = atoi(arg+10);
1003 if (!prefixcmp(arg, "--init-timeout=")) {
1004 init_timeout = atoi(arg+15);
1007 if (!prefixcmp(arg, "--max-connections=")) {
1008 max_connections = atoi(arg+18);
1009 if (max_connections < 0)
1010 max_connections = 0; /* unlimited */
1013 if (!strcmp(arg, "--strict-paths")) {
1017 if (!prefixcmp(arg, "--base-path=")) {
1021 if (!strcmp(arg, "--base-path-relaxed")) {
1022 base_path_relaxed = 1;
1025 if (!prefixcmp(arg, "--interpolated-path=")) {
1026 interpolated_path = arg+20;
1029 if (!strcmp(arg, "--reuseaddr")) {
1033 if (!strcmp(arg, "--user-path")) {
1037 if (!prefixcmp(arg, "--user-path=")) {
1038 user_path = arg + 12;
1041 if (!prefixcmp(arg, "--pid-file=")) {
1042 pid_file = arg + 11;
1045 if (!strcmp(arg, "--detach")) {
1050 if (!prefixcmp(arg, "--user=")) {
1051 user_name = arg + 7;
1054 if (!prefixcmp(arg, "--group=")) {
1055 group_name = arg + 8;
1058 if (!prefixcmp(arg, "--enable=")) {
1059 enable_service(arg + 9, 1);
1062 if (!prefixcmp(arg, "--disable=")) {
1063 enable_service(arg + 10, 0);
1066 if (!prefixcmp(arg, "--allow-override=")) {
1067 make_service_overridable(arg + 17, 1);
1070 if (!prefixcmp(arg, "--forbid-override=")) {
1071 make_service_overridable(arg + 18, 0);
1074 if (!strcmp(arg, "--")) {
1075 ok_paths = &argv[i+1];
1077 } else if (arg[0] != '-') {
1078 ok_paths = &argv[i];
1082 usage(daemon_usage);
1086 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1087 set_die_routine(daemon_die);
1089 /* avoid splitting a message in the middle */
1090 setvbuf(stderr, NULL, _IOLBF, 0);
1092 if (inetd_mode && (group_name || user_name))
1093 die("--user and --group are incompatible with --inetd");
1095 if (inetd_mode && (listen_port || listen_addr))
1096 die("--listen= and --port= are incompatible with --inetd");
1097 else if (listen_port == 0)
1098 listen_port = DEFAULT_GIT_PORT;
1100 if (group_name && !user_name)
1101 die("--group supplied without --user");
1104 pass = getpwnam(user_name);
1106 die("user not found - %s", user_name);
1111 group = getgrnam(group_name);
1113 die("group not found - %s", group_name);
1115 gid = group->gr_gid;
1119 if (strict_paths && (!ok_paths || !*ok_paths))
1120 die("option --strict-paths requires a whitelist");
1122 if (base_path && !is_directory(base_path))
1123 die("base-path '%s' does not exist or is not a directory",
1127 struct sockaddr_storage ss;
1128 struct sockaddr *peer = (struct sockaddr *)&ss;
1129 socklen_t slen = sizeof(ss);
1131 freopen("/dev/null", "w", stderr);
1133 if (getpeername(0, peer, &slen))
1136 return execute(peer);
1141 loginfo("Ready to rumble");
1147 store_pid(pid_file);
1149 return serve(listen_addr, listen_port, pass, gid);