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;
419 while (extra_args < end && *extra_args) {
420 saw_extended_args = 1;
421 if (strncasecmp("host=", extra_args, 5) == 0) {
422 val = extra_args + 5;
423 vallen = strlen(val) + 1;
425 /* Split <host>:<port> at colon. */
427 char *port = strrchr(host, ':');
432 tcp_port = xstrdup(port);
435 hostname = xstrdup(host);
438 /* On to the next one */
439 extra_args = val + vallen;
444 * Replace literal host with lowercase-ized hostname.
453 * Locate canonical hostname and its IP address.
457 struct addrinfo hints;
458 struct addrinfo *ai, *ai0;
460 static char addrbuf[HOST_NAME_MAX + 1];
462 memset(&hints, 0, sizeof(hints));
463 hints.ai_flags = AI_CANONNAME;
465 gai = getaddrinfo(hostname, 0, &hints, &ai0);
467 for (ai = ai0; ai; ai = ai->ai_next) {
468 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
470 inet_ntop(AF_INET, &sin_addr->sin_addr,
471 addrbuf, sizeof(addrbuf));
472 free(canon_hostname);
473 canon_hostname = xstrdup(ai->ai_canonname);
475 ip_address = xstrdup(addrbuf);
483 struct hostent *hent;
484 struct sockaddr_in sa;
486 static char addrbuf[HOST_NAME_MAX + 1];
488 hent = gethostbyname(hostname);
490 ap = hent->h_addr_list;
491 memset(&sa, 0, sizeof sa);
492 sa.sin_family = hent->h_addrtype;
493 sa.sin_port = htons(0);
494 memcpy(&sa.sin_addr, *ap, hent->h_length);
496 inet_ntop(hent->h_addrtype, &sa.sin_addr,
497 addrbuf, sizeof(addrbuf));
499 free(canon_hostname);
500 canon_hostname = xstrdup(hent->h_name);
502 ip_address = xstrdup(addrbuf);
508 static int execute(struct sockaddr *addr)
510 static char line[1000];
514 char addrbuf[256] = "";
517 if (addr->sa_family == AF_INET) {
518 struct sockaddr_in *sin_addr = (void *) addr;
519 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
520 port = ntohs(sin_addr->sin_port);
522 } else if (addr && addr->sa_family == AF_INET6) {
523 struct sockaddr_in6 *sin6_addr = (void *) addr;
526 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
527 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
530 port = ntohs(sin6_addr->sin6_port);
533 loginfo("Connection from %s:%d", addrbuf, port);
534 setenv("REMOTE_ADDR", addrbuf, 1);
537 unsetenv("REMOTE_ADDR");
540 alarm(init_timeout ? init_timeout : timeout);
541 pktlen = packet_read_line(0, line, sizeof(line));
546 loginfo("Extended attributes (%d bytes) exist <%.*s>",
548 (int) pktlen - len, line + len + 1);
549 if (len && line[len-1] == '\n') {
555 free(canon_hostname);
559 hostname = canon_hostname = ip_address = tcp_port = directory = NULL;
562 parse_extra_args(line + len + 1, pktlen - len - 1);
564 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
565 struct daemon_service *s = &(daemon_service[i]);
566 int namelen = strlen(s->name);
567 if (!prefixcmp(line, "git-") &&
568 !strncmp(s->name, line + 4, namelen) &&
569 line[namelen + 4] == ' ') {
571 * Note: The directory here is probably context sensitive,
572 * and might depend on the actual service being performed.
575 directory = xstrdup(line + namelen + 5);
576 return run_service(s);
580 logerror("Protocol error: '%s'", line);
584 static int max_connections = 32;
586 static unsigned int live_children;
588 static struct child {
591 struct sockaddr_storage address;
594 static void add_child(pid_t pid, struct sockaddr *addr, int addrlen)
596 struct child *newborn, **cradle;
599 * This must be xcalloc() -- we'll compare the whole sockaddr_storage
600 * but individual address may be shorter.
602 newborn = xcalloc(1, sizeof(*newborn));
605 memcpy(&newborn->address, addr, addrlen);
606 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
607 if (!memcmp(&(*cradle)->address, &newborn->address,
608 sizeof(newborn->address)))
610 newborn->next = *cradle;
614 static void remove_child(pid_t pid)
616 struct child **cradle, *blanket;
618 for (cradle = &firstborn; (blanket = *cradle); cradle = &blanket->next)
619 if (blanket->pid == pid) {
620 *cradle = blanket->next;
628 * This gets called if the number of connections grows
629 * past "max_connections".
631 * We kill the newest connection from a duplicate IP.
633 static void kill_some_child(void)
635 const struct child *blanket, *next;
637 if (!(blanket = firstborn))
640 for (; (next = blanket->next); blanket = next)
641 if (!memcmp(&blanket->address, &next->address,
642 sizeof(next->address))) {
643 kill(blanket->pid, SIGTERM);
648 static void check_dead_children(void)
653 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
654 const char *dead = "";
656 if (!WIFEXITED(status) || (WEXITSTATUS(status) > 0))
657 dead = " (with error)";
658 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
662 static void handle(int incoming, struct sockaddr *addr, int addrlen)
666 if (max_connections && live_children >= max_connections) {
668 sleep(1); /* give it some time to die */
669 check_dead_children();
670 if (live_children >= max_connections) {
672 logerror("Too many children, dropping connection");
677 if ((pid = fork())) {
680 logerror("Couldn't fork %s", strerror(errno));
684 add_child(pid, addr, addrlen);
695 static void child_handler(int signo)
698 * Otherwise empty handler because systemcalls will get interrupted
699 * upon signal receipt
700 * SysV needs the handler to be rearmed
702 signal(SIGCHLD, child_handler);
705 static int set_reuse_addr(int sockfd)
711 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
717 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
719 int socknum = 0, *socklist = NULL;
721 char pbuf[NI_MAXSERV];
722 struct addrinfo hints, *ai0, *ai;
726 sprintf(pbuf, "%d", listen_port);
727 memset(&hints, 0, sizeof(hints));
728 hints.ai_family = AF_UNSPEC;
729 hints.ai_socktype = SOCK_STREAM;
730 hints.ai_protocol = IPPROTO_TCP;
731 hints.ai_flags = AI_PASSIVE;
733 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
735 die("getaddrinfo() failed: %s\n", gai_strerror(gai));
737 for (ai = ai0; ai; ai = ai->ai_next) {
740 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
743 if (sockfd >= FD_SETSIZE) {
744 logerror("Socket descriptor too large");
750 if (ai->ai_family == AF_INET6) {
752 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
754 /* Note: error is not fatal */
758 if (set_reuse_addr(sockfd)) {
763 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
765 continue; /* not fatal */
767 if (listen(sockfd, 5) < 0) {
769 continue; /* not fatal */
772 flags = fcntl(sockfd, F_GETFD, 0);
774 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
776 socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
777 socklist[socknum++] = sockfd;
785 *socklist_p = socklist;
791 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
793 struct sockaddr_in sin;
797 memset(&sin, 0, sizeof sin);
798 sin.sin_family = AF_INET;
799 sin.sin_port = htons(listen_port);
802 /* Well, host better be an IP address here. */
803 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
806 sin.sin_addr.s_addr = htonl(INADDR_ANY);
809 sockfd = socket(AF_INET, SOCK_STREAM, 0);
813 if (set_reuse_addr(sockfd)) {
818 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
823 if (listen(sockfd, 5) < 0) {
828 flags = fcntl(sockfd, F_GETFD, 0);
830 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
832 *socklist_p = xmalloc(sizeof(int));
833 **socklist_p = sockfd;
839 static int service_loop(int socknum, int *socklist)
844 pfd = xcalloc(socknum, sizeof(struct pollfd));
846 for (i = 0; i < socknum; i++) {
847 pfd[i].fd = socklist[i];
848 pfd[i].events = POLLIN;
851 signal(SIGCHLD, child_handler);
856 check_dead_children();
858 if (poll(pfd, socknum, -1) < 0) {
859 if (errno != EINTR) {
860 logerror("Poll failed, resuming: %s",
867 for (i = 0; i < socknum; i++) {
868 if (pfd[i].revents & POLLIN) {
869 struct sockaddr_storage ss;
870 unsigned int sslen = sizeof(ss);
871 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
879 die("accept returned %s", strerror(errno));
882 handle(incoming, (struct sockaddr *)&ss, sslen);
888 /* if any standard file descriptor is missing open it to /dev/null */
889 static void sanitize_stdfds(void)
891 int fd = open("/dev/null", O_RDWR, 0);
892 while (fd != -1 && fd < 2)
895 die("open /dev/null or dup failed: %s", strerror(errno));
900 static void daemonize(void)
906 die("fork failed: %s", strerror(errno));
911 die("setsid failed: %s", strerror(errno));
918 static void store_pid(const char *path)
920 FILE *f = fopen(path, "w");
922 die("cannot open pid file %s: %s", path, strerror(errno));
923 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
924 die("failed to write pid file %s: %s", path, strerror(errno));
927 static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
929 int socknum, *socklist;
931 socknum = socksetup(listen_addr, listen_port, &socklist);
933 die("unable to allocate any listen sockets on host %s port %u",
934 listen_addr, listen_port);
937 (initgroups(pass->pw_name, gid) || setgid (gid) ||
938 setuid(pass->pw_uid)))
939 die("cannot drop privileges");
941 return service_loop(socknum, socklist);
944 int main(int argc, char **argv)
947 char *listen_addr = NULL;
949 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
951 struct passwd *pass = NULL;
956 for (i = 1; i < argc; i++) {
959 if (!prefixcmp(arg, "--listen=")) {
961 char *ph = listen_addr = xmalloc(strlen(arg + 9) + 1);
963 *ph++ = tolower(*p++);
967 if (!prefixcmp(arg, "--port=")) {
970 n = strtoul(arg+7, &end, 0);
971 if (arg[7] && !*end) {
976 if (!strcmp(arg, "--inetd")) {
981 if (!strcmp(arg, "--verbose")) {
985 if (!strcmp(arg, "--syslog")) {
989 if (!strcmp(arg, "--export-all")) {
990 export_all_trees = 1;
993 if (!prefixcmp(arg, "--timeout=")) {
994 timeout = atoi(arg+10);
997 if (!prefixcmp(arg, "--init-timeout=")) {
998 init_timeout = atoi(arg+15);
1001 if (!prefixcmp(arg, "--max-connections=")) {
1002 max_connections = atoi(arg+18);
1003 if (max_connections < 0)
1004 max_connections = 0; /* unlimited */
1007 if (!strcmp(arg, "--strict-paths")) {
1011 if (!prefixcmp(arg, "--base-path=")) {
1015 if (!strcmp(arg, "--base-path-relaxed")) {
1016 base_path_relaxed = 1;
1019 if (!prefixcmp(arg, "--interpolated-path=")) {
1020 interpolated_path = arg+20;
1023 if (!strcmp(arg, "--reuseaddr")) {
1027 if (!strcmp(arg, "--user-path")) {
1031 if (!prefixcmp(arg, "--user-path=")) {
1032 user_path = arg + 12;
1035 if (!prefixcmp(arg, "--pid-file=")) {
1036 pid_file = arg + 11;
1039 if (!strcmp(arg, "--detach")) {
1044 if (!prefixcmp(arg, "--user=")) {
1045 user_name = arg + 7;
1048 if (!prefixcmp(arg, "--group=")) {
1049 group_name = arg + 8;
1052 if (!prefixcmp(arg, "--enable=")) {
1053 enable_service(arg + 9, 1);
1056 if (!prefixcmp(arg, "--disable=")) {
1057 enable_service(arg + 10, 0);
1060 if (!prefixcmp(arg, "--allow-override=")) {
1061 make_service_overridable(arg + 17, 1);
1064 if (!prefixcmp(arg, "--forbid-override=")) {
1065 make_service_overridable(arg + 18, 0);
1068 if (!strcmp(arg, "--")) {
1069 ok_paths = &argv[i+1];
1071 } else if (arg[0] != '-') {
1072 ok_paths = &argv[i];
1076 usage(daemon_usage);
1080 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1081 set_die_routine(daemon_die);
1083 /* avoid splitting a message in the middle */
1084 setvbuf(stderr, NULL, _IOLBF, 0);
1086 if (inetd_mode && (group_name || user_name))
1087 die("--user and --group are incompatible with --inetd");
1089 if (inetd_mode && (listen_port || listen_addr))
1090 die("--listen= and --port= are incompatible with --inetd");
1091 else if (listen_port == 0)
1092 listen_port = DEFAULT_GIT_PORT;
1094 if (group_name && !user_name)
1095 die("--group supplied without --user");
1098 pass = getpwnam(user_name);
1100 die("user not found - %s", user_name);
1105 group = getgrnam(group_name);
1107 die("group not found - %s", group_name);
1109 gid = group->gr_gid;
1113 if (strict_paths && (!ok_paths || !*ok_paths))
1114 die("option --strict-paths requires a whitelist");
1116 if (base_path && !is_directory(base_path))
1117 die("base-path '%s' does not exist or is not a directory",
1121 struct sockaddr_storage ss;
1122 struct sockaddr *peer = (struct sockaddr *)&ss;
1123 socklen_t slen = sizeof(ss);
1125 freopen("/dev/null", "w", stderr);
1127 if (getpeername(0, peer, &slen))
1130 return execute(peer);
1135 loginfo("Ready to rumble");
1141 store_pid(pid_file);
1143 return serve(listen_addr, listen_port, pass, gid);