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];
158 if (avoid_alias(dir)) {
159 logerror("'%s': aliased", dir);
165 logerror("'%s': User-path not allowed", dir);
169 /* Got either "~alice" or "~alice/foo";
170 * rewrite them to "~alice/%s" or
173 int namlen, restlen = strlen(dir);
174 char *slash = strchr(dir, '/');
176 slash = dir + restlen;
177 namlen = slash - dir;
179 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
180 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
181 namlen, dir, user_path, restlen, slash);
185 else if (interpolated_path && saw_extended_args) {
186 struct strbuf expanded_path = STRBUF_INIT;
187 struct strbuf_expand_dict_entry dict[] = {
189 { "CH", canon_hostname },
190 { "IP", ip_address },
198 /* Allow only absolute */
199 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
203 strbuf_expand(&expanded_path, interpolated_path,
204 strbuf_expand_dict_cb, &dict);
205 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
206 strbuf_release(&expanded_path);
207 loginfo("Interpolated dir '%s'", interp_path);
211 else if (base_path) {
213 /* Allow only absolute */
214 logerror("'%s': Non-absolute path denied (base-path active)", dir);
217 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
221 path = enter_repo(dir, strict_paths);
222 if (!path && base_path && base_path_relaxed) {
224 * if we fail and base_path_relaxed is enabled, try without
225 * prefixing the base path
228 path = enter_repo(dir, strict_paths);
232 logerror("'%s' does not appear to be a git repository", dir);
236 if ( ok_paths && *ok_paths ) {
238 int pathlen = strlen(path);
240 /* The validation is done on the paths after enter_repo
241 * appends optional {.git,.git/.git} and friends, but
242 * it does not use getcwd(). So if your /pub is
243 * a symlink to /mnt/pub, you can whitelist /pub and
244 * do not have to say /mnt/pub.
247 for ( pp = ok_paths ; *pp ; pp++ ) {
248 int len = strlen(*pp);
249 if (len <= pathlen &&
250 !memcmp(*pp, path, len) &&
251 (path[len] == '\0' ||
252 (!strict_paths && path[len] == '/')))
257 /* be backwards compatible */
262 logerror("'%s': not in whitelist", path);
263 return NULL; /* Fallthrough. Deny by default */
266 typedef int (*daemon_service_fn)(void);
267 struct daemon_service {
269 const char *config_name;
270 daemon_service_fn fn;
275 static struct daemon_service *service_looking_at;
276 static int service_enabled;
278 static int git_daemon_config(const char *var, const char *value, void *cb)
280 if (!prefixcmp(var, "daemon.") &&
281 !strcmp(var + 7, service_looking_at->config_name)) {
282 service_enabled = git_config_bool(var, value);
286 /* we are not interested in parsing any other configuration here */
290 static int run_service(char *dir, struct daemon_service *service)
293 int enabled = service->enabled;
295 loginfo("Request %s for '%s'", service->name, dir);
297 if (!enabled && !service->overridable) {
298 logerror("'%s': service not enabled.", service->name);
303 if (!(path = path_ok(dir)))
307 * Security on the cheap.
309 * We want a readable HEAD, usable "objects" directory, and
310 * a "git-daemon-export-ok" flag that says that the other side
311 * is ok with us doing this.
313 * path_ok() uses enter_repo() and does whitelist checking.
314 * We only need to make sure the repository is exported.
317 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
318 logerror("'%s': repository not exported.", path);
323 if (service->overridable) {
324 service_looking_at = service;
325 service_enabled = -1;
326 git_config(git_daemon_config, NULL);
327 if (0 <= service_enabled)
328 enabled = service_enabled;
331 logerror("'%s': service not enabled for '%s'",
332 service->name, path);
338 * We'll ignore SIGTERM from now on, we have a
341 signal(SIGTERM, SIG_IGN);
343 return service->fn();
346 static int upload_pack(void)
348 /* Timeout as string */
349 char timeout_buf[64];
351 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
353 /* git-upload-pack only ever reads stuff, so this is safe */
354 execl_git_cmd("upload-pack", "--strict", timeout_buf, ".", NULL);
358 static int upload_archive(void)
360 execl_git_cmd("upload-archive", ".", NULL);
364 static int receive_pack(void)
366 execl_git_cmd("receive-pack", ".", NULL);
370 static struct daemon_service daemon_service[] = {
371 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
372 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
373 { "receive-pack", "receivepack", receive_pack, 0, 1 },
376 static void enable_service(const char *name, int ena)
379 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
380 if (!strcmp(daemon_service[i].name, name)) {
381 daemon_service[i].enabled = ena;
385 die("No such service %s", name);
388 static void make_service_overridable(const char *name, int ena)
391 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
392 if (!strcmp(daemon_service[i].name, name)) {
393 daemon_service[i].overridable = ena;
397 die("No such service %s", name);
400 static char *xstrdup_tolower(const char *str)
402 char *p, *dup = xstrdup(str);
403 for (p = dup; *p; p++)
409 * Read the host as supplied by the client connection.
411 static void parse_host_arg(char *extra_args, int buflen)
415 char *end = extra_args + buflen;
417 if (extra_args < end && *extra_args) {
418 saw_extended_args = 1;
419 if (strncasecmp("host=", extra_args, 5) == 0) {
420 val = extra_args + 5;
421 vallen = strlen(val) + 1;
423 /* Split <host>:<port> at colon. */
425 char *port = strrchr(host, ':');
430 tcp_port = xstrdup(port);
433 hostname = xstrdup_tolower(host);
436 /* On to the next one */
437 extra_args = val + vallen;
439 if (extra_args < end && *extra_args)
440 die("Invalid request");
444 * Locate canonical hostname and its IP address.
448 struct addrinfo hints;
451 static char addrbuf[HOST_NAME_MAX + 1];
453 memset(&hints, 0, sizeof(hints));
454 hints.ai_flags = AI_CANONNAME;
456 gai = getaddrinfo(hostname, NULL, &hints, &ai);
458 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
460 inet_ntop(AF_INET, &sin_addr->sin_addr,
461 addrbuf, sizeof(addrbuf));
463 ip_address = xstrdup(addrbuf);
465 free(canon_hostname);
466 canon_hostname = xstrdup(ai->ai_canonname ?
467 ai->ai_canonname : ip_address);
472 struct hostent *hent;
473 struct sockaddr_in sa;
475 static char addrbuf[HOST_NAME_MAX + 1];
477 hent = gethostbyname(hostname);
479 ap = hent->h_addr_list;
480 memset(&sa, 0, sizeof sa);
481 sa.sin_family = hent->h_addrtype;
482 sa.sin_port = htons(0);
483 memcpy(&sa.sin_addr, *ap, hent->h_length);
485 inet_ntop(hent->h_addrtype, &sa.sin_addr,
486 addrbuf, sizeof(addrbuf));
488 free(canon_hostname);
489 canon_hostname = xstrdup(hent->h_name);
491 ip_address = xstrdup(addrbuf);
497 static int execute(struct sockaddr *addr)
499 static char line[1000];
503 char addrbuf[256] = "";
506 if (addr->sa_family == AF_INET) {
507 struct sockaddr_in *sin_addr = (void *) addr;
508 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
509 port = ntohs(sin_addr->sin_port);
511 } else if (addr && addr->sa_family == AF_INET6) {
512 struct sockaddr_in6 *sin6_addr = (void *) addr;
515 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
516 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
519 port = ntohs(sin6_addr->sin6_port);
522 loginfo("Connection from %s:%d", addrbuf, port);
523 setenv("REMOTE_ADDR", addrbuf, 1);
526 unsetenv("REMOTE_ADDR");
529 alarm(init_timeout ? init_timeout : timeout);
530 pktlen = packet_read_line(0, line, sizeof(line));
535 loginfo("Extended attributes (%d bytes) exist <%.*s>",
537 (int) pktlen - len, line + len + 1);
538 if (len && line[len-1] == '\n') {
544 free(canon_hostname);
547 hostname = canon_hostname = ip_address = tcp_port = NULL;
550 parse_host_arg(line + len + 1, pktlen - len - 1);
552 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
553 struct daemon_service *s = &(daemon_service[i]);
554 int namelen = strlen(s->name);
555 if (!prefixcmp(line, "git-") &&
556 !strncmp(s->name, line + 4, namelen) &&
557 line[namelen + 4] == ' ') {
559 * Note: The directory here is probably context sensitive,
560 * and might depend on the actual service being performed.
562 return run_service(line + namelen + 5, s);
566 logerror("Protocol error: '%s'", line);
570 static int max_connections = 32;
572 static unsigned int live_children;
574 static struct child {
577 struct sockaddr_storage address;
580 static void add_child(pid_t pid, struct sockaddr *addr, int addrlen)
582 struct child *newborn, **cradle;
585 * This must be xcalloc() -- we'll compare the whole sockaddr_storage
586 * but individual address may be shorter.
588 newborn = xcalloc(1, sizeof(*newborn));
591 memcpy(&newborn->address, addr, addrlen);
592 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
593 if (!memcmp(&(*cradle)->address, &newborn->address,
594 sizeof(newborn->address)))
596 newborn->next = *cradle;
600 static void remove_child(pid_t pid)
602 struct child **cradle, *blanket;
604 for (cradle = &firstborn; (blanket = *cradle); cradle = &blanket->next)
605 if (blanket->pid == pid) {
606 *cradle = blanket->next;
614 * This gets called if the number of connections grows
615 * past "max_connections".
617 * We kill the newest connection from a duplicate IP.
619 static void kill_some_child(void)
621 const struct child *blanket, *next;
623 if (!(blanket = firstborn))
626 for (; (next = blanket->next); blanket = next)
627 if (!memcmp(&blanket->address, &next->address,
628 sizeof(next->address))) {
629 kill(blanket->pid, SIGTERM);
634 static void check_dead_children(void)
639 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
640 const char *dead = "";
642 if (!WIFEXITED(status) || (WEXITSTATUS(status) > 0))
643 dead = " (with error)";
644 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
648 static void handle(int incoming, struct sockaddr *addr, int addrlen)
652 if (max_connections && live_children >= max_connections) {
654 sleep(1); /* give it some time to die */
655 check_dead_children();
656 if (live_children >= max_connections) {
658 logerror("Too many children, dropping connection");
663 if ((pid = fork())) {
666 logerror("Couldn't fork %s", strerror(errno));
670 add_child(pid, addr, addrlen);
681 static void child_handler(int signo)
684 * Otherwise empty handler because systemcalls will get interrupted
685 * upon signal receipt
686 * SysV needs the handler to be rearmed
688 signal(SIGCHLD, child_handler);
691 static int set_reuse_addr(int sockfd)
697 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
703 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
705 int socknum = 0, *socklist = NULL;
707 char pbuf[NI_MAXSERV];
708 struct addrinfo hints, *ai0, *ai;
712 sprintf(pbuf, "%d", listen_port);
713 memset(&hints, 0, sizeof(hints));
714 hints.ai_family = AF_UNSPEC;
715 hints.ai_socktype = SOCK_STREAM;
716 hints.ai_protocol = IPPROTO_TCP;
717 hints.ai_flags = AI_PASSIVE;
719 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
721 die("getaddrinfo() failed: %s", gai_strerror(gai));
723 for (ai = ai0; ai; ai = ai->ai_next) {
726 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
729 if (sockfd >= FD_SETSIZE) {
730 logerror("Socket descriptor too large");
736 if (ai->ai_family == AF_INET6) {
738 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
740 /* Note: error is not fatal */
744 if (set_reuse_addr(sockfd)) {
749 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
751 continue; /* not fatal */
753 if (listen(sockfd, 5) < 0) {
755 continue; /* not fatal */
758 flags = fcntl(sockfd, F_GETFD, 0);
760 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
762 socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
763 socklist[socknum++] = sockfd;
771 *socklist_p = socklist;
777 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
779 struct sockaddr_in sin;
783 memset(&sin, 0, sizeof sin);
784 sin.sin_family = AF_INET;
785 sin.sin_port = htons(listen_port);
788 /* Well, host better be an IP address here. */
789 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
792 sin.sin_addr.s_addr = htonl(INADDR_ANY);
795 sockfd = socket(AF_INET, SOCK_STREAM, 0);
799 if (set_reuse_addr(sockfd)) {
804 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
809 if (listen(sockfd, 5) < 0) {
814 flags = fcntl(sockfd, F_GETFD, 0);
816 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
818 *socklist_p = xmalloc(sizeof(int));
819 **socklist_p = sockfd;
825 static int service_loop(int socknum, int *socklist)
830 pfd = xcalloc(socknum, sizeof(struct pollfd));
832 for (i = 0; i < socknum; i++) {
833 pfd[i].fd = socklist[i];
834 pfd[i].events = POLLIN;
837 signal(SIGCHLD, child_handler);
842 check_dead_children();
844 if (poll(pfd, socknum, -1) < 0) {
845 if (errno != EINTR) {
846 logerror("Poll failed, resuming: %s",
853 for (i = 0; i < socknum; i++) {
854 if (pfd[i].revents & POLLIN) {
855 struct sockaddr_storage ss;
856 unsigned int sslen = sizeof(ss);
857 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
865 die("accept returned %s", strerror(errno));
868 handle(incoming, (struct sockaddr *)&ss, sslen);
874 /* if any standard file descriptor is missing open it to /dev/null */
875 static void sanitize_stdfds(void)
877 int fd = open("/dev/null", O_RDWR, 0);
878 while (fd != -1 && fd < 2)
881 die("open /dev/null or dup failed: %s", strerror(errno));
886 static void daemonize(void)
892 die("fork failed: %s", strerror(errno));
897 die("setsid failed: %s", strerror(errno));
904 static void store_pid(const char *path)
906 FILE *f = fopen(path, "w");
908 die("cannot open pid file %s: %s", path, strerror(errno));
909 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
910 die("failed to write pid file %s: %s", path, strerror(errno));
913 static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
915 int socknum, *socklist;
917 socknum = socksetup(listen_addr, listen_port, &socklist);
919 die("unable to allocate any listen sockets on host %s port %u",
920 listen_addr, listen_port);
923 (initgroups(pass->pw_name, gid) || setgid (gid) ||
924 setuid(pass->pw_uid)))
925 die("cannot drop privileges");
927 return service_loop(socknum, socklist);
930 int main(int argc, char **argv)
933 char *listen_addr = NULL;
935 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
937 struct passwd *pass = NULL;
942 git_extract_argv0_path(argv[0]);
944 for (i = 1; i < argc; i++) {
947 if (!prefixcmp(arg, "--listen=")) {
948 listen_addr = xstrdup_tolower(arg + 9);
951 if (!prefixcmp(arg, "--port=")) {
954 n = strtoul(arg+7, &end, 0);
955 if (arg[7] && !*end) {
960 if (!strcmp(arg, "--inetd")) {
965 if (!strcmp(arg, "--verbose")) {
969 if (!strcmp(arg, "--syslog")) {
973 if (!strcmp(arg, "--export-all")) {
974 export_all_trees = 1;
977 if (!prefixcmp(arg, "--timeout=")) {
978 timeout = atoi(arg+10);
981 if (!prefixcmp(arg, "--init-timeout=")) {
982 init_timeout = atoi(arg+15);
985 if (!prefixcmp(arg, "--max-connections=")) {
986 max_connections = atoi(arg+18);
987 if (max_connections < 0)
988 max_connections = 0; /* unlimited */
991 if (!strcmp(arg, "--strict-paths")) {
995 if (!prefixcmp(arg, "--base-path=")) {
999 if (!strcmp(arg, "--base-path-relaxed")) {
1000 base_path_relaxed = 1;
1003 if (!prefixcmp(arg, "--interpolated-path=")) {
1004 interpolated_path = arg+20;
1007 if (!strcmp(arg, "--reuseaddr")) {
1011 if (!strcmp(arg, "--user-path")) {
1015 if (!prefixcmp(arg, "--user-path=")) {
1016 user_path = arg + 12;
1019 if (!prefixcmp(arg, "--pid-file=")) {
1020 pid_file = arg + 11;
1023 if (!strcmp(arg, "--detach")) {
1028 if (!prefixcmp(arg, "--user=")) {
1029 user_name = arg + 7;
1032 if (!prefixcmp(arg, "--group=")) {
1033 group_name = arg + 8;
1036 if (!prefixcmp(arg, "--enable=")) {
1037 enable_service(arg + 9, 1);
1040 if (!prefixcmp(arg, "--disable=")) {
1041 enable_service(arg + 10, 0);
1044 if (!prefixcmp(arg, "--allow-override=")) {
1045 make_service_overridable(arg + 17, 1);
1048 if (!prefixcmp(arg, "--forbid-override=")) {
1049 make_service_overridable(arg + 18, 0);
1052 if (!strcmp(arg, "--")) {
1053 ok_paths = &argv[i+1];
1055 } else if (arg[0] != '-') {
1056 ok_paths = &argv[i];
1060 usage(daemon_usage);
1064 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1065 set_die_routine(daemon_die);
1067 /* avoid splitting a message in the middle */
1068 setvbuf(stderr, NULL, _IOLBF, 0);
1070 if (inetd_mode && (group_name || user_name))
1071 die("--user and --group are incompatible with --inetd");
1073 if (inetd_mode && (listen_port || listen_addr))
1074 die("--listen= and --port= are incompatible with --inetd");
1075 else if (listen_port == 0)
1076 listen_port = DEFAULT_GIT_PORT;
1078 if (group_name && !user_name)
1079 die("--group supplied without --user");
1082 pass = getpwnam(user_name);
1084 die("user not found - %s", user_name);
1089 group = getgrnam(group_name);
1091 die("group not found - %s", group_name);
1093 gid = group->gr_gid;
1097 if (strict_paths && (!ok_paths || !*ok_paths))
1098 die("option --strict-paths requires a whitelist");
1100 if (base_path && !is_directory(base_path))
1101 die("base-path '%s' does not exist or is not a directory",
1105 struct sockaddr_storage ss;
1106 struct sockaddr *peer = (struct sockaddr *)&ss;
1107 socklen_t slen = sizeof(ss);
1109 if (!freopen("/dev/null", "w", stderr))
1110 die("failed to redirect stderr to /dev/null: %s",
1113 if (getpeername(0, peer, &slen))
1116 return execute(peer);
1121 loginfo("Ready to rumble");
1127 store_pid(pid_file);
1129 return serve(listen_addr, listen_port, pass, gid);