Tests: make sure that $DIFF is non-empty
[git/dscho.git] / daemon.c
blobbd7574e8dc24b5c2157b4451e8bba2699e057068
1 #include "cache.h"
2 #include "pkt-line.h"
3 #include "exec_cmd.h"
4 #include "run-command.h"
5 #include "strbuf.h"
6 #include "string-list.h"
8 #include <syslog.h>
10 #ifndef HOST_NAME_MAX
11 #define HOST_NAME_MAX 256
12 #endif
14 #ifndef NI_MAXSERV
15 #define NI_MAXSERV 32
16 #endif
18 static int log_syslog;
19 static int verbose;
20 static int reuseaddr;
22 static const char daemon_usage[] =
23 "git daemon [--verbose] [--syslog] [--export-all]\n"
24 " [--timeout=n] [--init-timeout=n] [--max-connections=n]\n"
25 " [--strict-paths] [--base-path=path] [--base-path-relaxed]\n"
26 " [--user-path | --user-path=path]\n"
27 " [--interpolated-path=path]\n"
28 " [--reuseaddr] [--detach] [--pid-file=file]\n"
29 " [--[enable|disable|allow-override|forbid-override]=service]\n"
30 " [--inetd | [--listen=host_or_ipaddr] [--port=n]\n"
31 " [--user=user [--group=group]]\n"
32 " [directory...]";
34 /* List of acceptable pathname prefixes */
35 static char **ok_paths;
36 static int strict_paths;
38 /* If this is set, git-daemon-export-ok is not required */
39 static int export_all_trees;
41 /* Take all paths relative to this one if non-NULL */
42 static char *base_path;
43 static char *interpolated_path;
44 static int base_path_relaxed;
46 /* Flag indicating client sent extra args. */
47 static int saw_extended_args;
49 /* If defined, ~user notation is allowed and the string is inserted
50 * after ~user/. E.g. a request to git://host/~alice/frotz would
51 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
53 static const char *user_path;
55 /* Timeout, and initial timeout */
56 static unsigned int timeout;
57 static unsigned int init_timeout;
59 static char *hostname;
60 static char *canon_hostname;
61 static char *ip_address;
62 static char *tcp_port;
64 static void logreport(int priority, const char *err, va_list params)
66 if (log_syslog) {
67 char buf[1024];
68 vsnprintf(buf, sizeof(buf), err, params);
69 syslog(priority, "%s", buf);
70 } else {
72 * Since stderr is set to linebuffered mode, the
73 * logging of different processes will not overlap
75 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
76 vfprintf(stderr, err, params);
77 fputc('\n', stderr);
81 __attribute__((format (printf, 1, 2)))
82 static void logerror(const char *err, ...)
84 va_list params;
85 va_start(params, err);
86 logreport(LOG_ERR, err, params);
87 va_end(params);
90 __attribute__((format (printf, 1, 2)))
91 static void loginfo(const char *err, ...)
93 va_list params;
94 if (!verbose)
95 return;
96 va_start(params, err);
97 logreport(LOG_INFO, err, params);
98 va_end(params);
101 static void NORETURN daemon_die(const char *err, va_list params)
103 logreport(LOG_ERR, err, params);
104 exit(1);
107 static char *path_ok(char *directory)
109 static char rpath[PATH_MAX];
110 static char interp_path[PATH_MAX];
111 char *path;
112 char *dir;
114 dir = directory;
116 if (daemon_avoid_alias(dir)) {
117 logerror("'%s': aliased", dir);
118 return NULL;
121 if (*dir == '~') {
122 if (!user_path) {
123 logerror("'%s': User-path not allowed", dir);
124 return NULL;
126 if (*user_path) {
127 /* Got either "~alice" or "~alice/foo";
128 * rewrite them to "~alice/%s" or
129 * "~alice/%s/foo".
131 int namlen, restlen = strlen(dir);
132 char *slash = strchr(dir, '/');
133 if (!slash)
134 slash = dir + restlen;
135 namlen = slash - dir;
136 restlen -= namlen;
137 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
138 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
139 namlen, dir, user_path, restlen, slash);
140 dir = rpath;
143 else if (interpolated_path && saw_extended_args) {
144 struct strbuf expanded_path = STRBUF_INIT;
145 struct strbuf_expand_dict_entry dict[6];
147 dict[0].placeholder = "H"; dict[0].value = hostname;
148 dict[1].placeholder = "CH"; dict[1].value = canon_hostname;
149 dict[2].placeholder = "IP"; dict[2].value = ip_address;
150 dict[3].placeholder = "P"; dict[3].value = tcp_port;
151 dict[4].placeholder = "D"; dict[4].value = directory;
152 dict[5].placeholder = NULL; dict[5].value = NULL;
153 if (*dir != '/') {
154 /* Allow only absolute */
155 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
156 return NULL;
159 strbuf_expand(&expanded_path, interpolated_path,
160 strbuf_expand_dict_cb, &dict);
161 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
162 strbuf_release(&expanded_path);
163 loginfo("Interpolated dir '%s'", interp_path);
165 dir = interp_path;
167 else if (base_path) {
168 if (*dir != '/') {
169 /* Allow only absolute */
170 logerror("'%s': Non-absolute path denied (base-path active)", dir);
171 return NULL;
173 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
174 dir = rpath;
177 path = enter_repo(dir, strict_paths);
178 if (!path && base_path && base_path_relaxed) {
180 * if we fail and base_path_relaxed is enabled, try without
181 * prefixing the base path
183 dir = directory;
184 path = enter_repo(dir, strict_paths);
187 if (!path) {
188 logerror("'%s' does not appear to be a git repository", dir);
189 return NULL;
192 if ( ok_paths && *ok_paths ) {
193 char **pp;
194 int pathlen = strlen(path);
196 /* The validation is done on the paths after enter_repo
197 * appends optional {.git,.git/.git} and friends, but
198 * it does not use getcwd(). So if your /pub is
199 * a symlink to /mnt/pub, you can whitelist /pub and
200 * do not have to say /mnt/pub.
201 * Do not say /pub/.
203 for ( pp = ok_paths ; *pp ; pp++ ) {
204 int len = strlen(*pp);
205 if (len <= pathlen &&
206 !memcmp(*pp, path, len) &&
207 (path[len] == '\0' ||
208 (!strict_paths && path[len] == '/')))
209 return path;
212 else {
213 /* be backwards compatible */
214 if (!strict_paths)
215 return path;
218 logerror("'%s': not in whitelist", path);
219 return NULL; /* Fallthrough. Deny by default */
222 typedef int (*daemon_service_fn)(void);
223 struct daemon_service {
224 const char *name;
225 const char *config_name;
226 daemon_service_fn fn;
227 int enabled;
228 int overridable;
231 static struct daemon_service *service_looking_at;
232 static int service_enabled;
234 static int git_daemon_config(const char *var, const char *value, void *cb)
236 if (!prefixcmp(var, "daemon.") &&
237 !strcmp(var + 7, service_looking_at->config_name)) {
238 service_enabled = git_config_bool(var, value);
239 return 0;
242 /* we are not interested in parsing any other configuration here */
243 return 0;
246 static int run_service(char *dir, struct daemon_service *service)
248 const char *path;
249 int enabled = service->enabled;
251 loginfo("Request %s for '%s'", service->name, dir);
253 if (!enabled && !service->overridable) {
254 logerror("'%s': service not enabled.", service->name);
255 errno = EACCES;
256 return -1;
259 if (!(path = path_ok(dir)))
260 return -1;
263 * Security on the cheap.
265 * We want a readable HEAD, usable "objects" directory, and
266 * a "git-daemon-export-ok" flag that says that the other side
267 * is ok with us doing this.
269 * path_ok() uses enter_repo() and does whitelist checking.
270 * We only need to make sure the repository is exported.
273 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
274 logerror("'%s': repository not exported.", path);
275 errno = EACCES;
276 return -1;
279 if (service->overridable) {
280 service_looking_at = service;
281 service_enabled = -1;
282 git_config(git_daemon_config, NULL);
283 if (0 <= service_enabled)
284 enabled = service_enabled;
286 if (!enabled) {
287 logerror("'%s': service not enabled for '%s'",
288 service->name, path);
289 errno = EACCES;
290 return -1;
294 * We'll ignore SIGTERM from now on, we have a
295 * good client.
297 signal(SIGTERM, SIG_IGN);
299 return service->fn();
302 static void copy_to_log(int fd)
304 struct strbuf line = STRBUF_INIT;
305 FILE *fp;
307 fp = fdopen(fd, "r");
308 if (fp == NULL) {
309 logerror("fdopen of error channel failed");
310 close(fd);
311 return;
314 while (strbuf_getline(&line, fp, '\n') != EOF) {
315 logerror("%s", line.buf);
316 strbuf_setlen(&line, 0);
319 strbuf_release(&line);
320 fclose(fp);
323 static int run_service_command(const char **argv)
325 struct child_process cld;
327 memset(&cld, 0, sizeof(cld));
328 cld.argv = argv;
329 cld.git_cmd = 1;
330 cld.err = -1;
331 if (start_command(&cld))
332 return -1;
334 close(0);
335 close(1);
337 copy_to_log(cld.err);
339 return finish_command(&cld);
342 static int upload_pack(void)
344 /* Timeout as string */
345 char timeout_buf[64];
346 const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
348 argv[2] = timeout_buf;
350 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
351 return run_service_command(argv);
354 static int upload_archive(void)
356 static const char *argv[] = { "upload-archive", ".", NULL };
357 return run_service_command(argv);
360 static int receive_pack(void)
362 static const char *argv[] = { "receive-pack", ".", NULL };
363 return run_service_command(argv);
366 static struct daemon_service daemon_service[] = {
367 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
368 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
369 { "receive-pack", "receivepack", receive_pack, 0, 1 },
372 static void enable_service(const char *name, int ena)
374 int i;
375 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
376 if (!strcmp(daemon_service[i].name, name)) {
377 daemon_service[i].enabled = ena;
378 return;
381 die("No such service %s", name);
384 static void make_service_overridable(const char *name, int ena)
386 int i;
387 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
388 if (!strcmp(daemon_service[i].name, name)) {
389 daemon_service[i].overridable = ena;
390 return;
393 die("No such service %s", name);
396 static char *xstrdup_tolower(const char *str)
398 char *p, *dup = xstrdup(str);
399 for (p = dup; *p; p++)
400 *p = tolower(*p);
401 return dup;
404 static void parse_host_and_port(char *hostport, char **host,
405 char **port)
407 if (*hostport == '[') {
408 char *end;
410 end = strchr(hostport, ']');
411 if (!end)
412 die("Invalid request ('[' without ']')");
413 *end = '\0';
414 *host = hostport + 1;
415 if (!end[1])
416 *port = NULL;
417 else if (end[1] == ':')
418 *port = end + 2;
419 else
420 die("Garbage after end of host part");
421 } else {
422 *host = hostport;
423 *port = strrchr(hostport, ':');
424 if (*port) {
425 **port = '\0';
426 ++*port;
432 * Read the host as supplied by the client connection.
434 static void parse_host_arg(char *extra_args, int buflen)
436 char *val;
437 int vallen;
438 char *end = extra_args + buflen;
440 if (extra_args < end && *extra_args) {
441 saw_extended_args = 1;
442 if (strncasecmp("host=", extra_args, 5) == 0) {
443 val = extra_args + 5;
444 vallen = strlen(val) + 1;
445 if (*val) {
446 /* Split <host>:<port> at colon. */
447 char *host;
448 char *port;
449 parse_host_and_port(val, &host, &port);
450 if (port) {
451 free(tcp_port);
452 tcp_port = xstrdup(port);
454 free(hostname);
455 hostname = xstrdup_tolower(host);
458 /* On to the next one */
459 extra_args = val + vallen;
461 if (extra_args < end && *extra_args)
462 die("Invalid request");
466 * Locate canonical hostname and its IP address.
468 if (hostname) {
469 #ifndef NO_IPV6
470 struct addrinfo hints;
471 struct addrinfo *ai;
472 int gai;
473 static char addrbuf[HOST_NAME_MAX + 1];
475 memset(&hints, 0, sizeof(hints));
476 hints.ai_flags = AI_CANONNAME;
478 gai = getaddrinfo(hostname, NULL, &hints, &ai);
479 if (!gai) {
480 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
482 inet_ntop(AF_INET, &sin_addr->sin_addr,
483 addrbuf, sizeof(addrbuf));
484 free(ip_address);
485 ip_address = xstrdup(addrbuf);
487 free(canon_hostname);
488 canon_hostname = xstrdup(ai->ai_canonname ?
489 ai->ai_canonname : ip_address);
491 freeaddrinfo(ai);
493 #else
494 struct hostent *hent;
495 struct sockaddr_in sa;
496 char **ap;
497 static char addrbuf[HOST_NAME_MAX + 1];
499 hent = gethostbyname(hostname);
501 ap = hent->h_addr_list;
502 memset(&sa, 0, sizeof sa);
503 sa.sin_family = hent->h_addrtype;
504 sa.sin_port = htons(0);
505 memcpy(&sa.sin_addr, *ap, hent->h_length);
507 inet_ntop(hent->h_addrtype, &sa.sin_addr,
508 addrbuf, sizeof(addrbuf));
510 free(canon_hostname);
511 canon_hostname = xstrdup(hent->h_name);
512 free(ip_address);
513 ip_address = xstrdup(addrbuf);
514 #endif
519 static int execute(struct sockaddr *addr)
521 static char line[1000];
522 int pktlen, len, i;
524 if (addr) {
525 char addrbuf[256] = "";
526 int port = -1;
528 if (addr->sa_family == AF_INET) {
529 struct sockaddr_in *sin_addr = (void *) addr;
530 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
531 port = ntohs(sin_addr->sin_port);
532 #ifndef NO_IPV6
533 } else if (addr && addr->sa_family == AF_INET6) {
534 struct sockaddr_in6 *sin6_addr = (void *) addr;
536 char *buf = addrbuf;
537 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
538 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
539 strcat(buf, "]");
541 port = ntohs(sin6_addr->sin6_port);
542 #endif
544 loginfo("Connection from %s:%d", addrbuf, port);
545 setenv("REMOTE_ADDR", addrbuf, 1);
547 else {
548 unsetenv("REMOTE_ADDR");
551 alarm(init_timeout ? init_timeout : timeout);
552 pktlen = packet_read_line(0, line, sizeof(line));
553 alarm(0);
555 len = strlen(line);
556 if (pktlen != len)
557 loginfo("Extended attributes (%d bytes) exist <%.*s>",
558 (int) pktlen - len,
559 (int) pktlen - len, line + len + 1);
560 if (len && line[len-1] == '\n') {
561 line[--len] = 0;
562 pktlen--;
565 free(hostname);
566 free(canon_hostname);
567 free(ip_address);
568 free(tcp_port);
569 hostname = canon_hostname = ip_address = tcp_port = NULL;
571 if (len != pktlen)
572 parse_host_arg(line + len + 1, pktlen - len - 1);
574 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
575 struct daemon_service *s = &(daemon_service[i]);
576 int namelen = strlen(s->name);
577 if (!prefixcmp(line, "git-") &&
578 !strncmp(s->name, line + 4, namelen) &&
579 line[namelen + 4] == ' ') {
581 * Note: The directory here is probably context sensitive,
582 * and might depend on the actual service being performed.
584 return run_service(line + namelen + 5, s);
588 logerror("Protocol error: '%s'", line);
589 return -1;
592 static int addrcmp(const struct sockaddr_storage *s1,
593 const struct sockaddr_storage *s2)
595 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
596 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
598 if (sa1->sa_family != sa2->sa_family)
599 return sa1->sa_family - sa2->sa_family;
600 if (sa1->sa_family == AF_INET)
601 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
602 &((struct sockaddr_in *)s2)->sin_addr,
603 sizeof(struct in_addr));
604 #ifndef NO_IPV6
605 if (sa1->sa_family == AF_INET6)
606 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
607 &((struct sockaddr_in6 *)s2)->sin6_addr,
608 sizeof(struct in6_addr));
609 #endif
610 return 0;
613 static int max_connections = 32;
615 static unsigned int live_children;
617 static struct child {
618 struct child *next;
619 pid_t pid;
620 struct sockaddr_storage address;
621 } *firstborn;
623 static void add_child(pid_t pid, struct sockaddr *addr, int addrlen)
625 struct child *newborn, **cradle;
627 newborn = xcalloc(1, sizeof(*newborn));
628 live_children++;
629 newborn->pid = pid;
630 memcpy(&newborn->address, addr, addrlen);
631 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
632 if (!addrcmp(&(*cradle)->address, &newborn->address))
633 break;
634 newborn->next = *cradle;
635 *cradle = newborn;
638 static void remove_child(pid_t pid)
640 struct child **cradle, *blanket;
642 for (cradle = &firstborn; (blanket = *cradle); cradle = &blanket->next)
643 if (blanket->pid == pid) {
644 *cradle = blanket->next;
645 live_children--;
646 free(blanket);
647 break;
652 * This gets called if the number of connections grows
653 * past "max_connections".
655 * We kill the newest connection from a duplicate IP.
657 static void kill_some_child(void)
659 const struct child *blanket, *next;
661 if (!(blanket = firstborn))
662 return;
664 for (; (next = blanket->next); blanket = next)
665 if (!addrcmp(&blanket->address, &next->address)) {
666 kill(blanket->pid, SIGTERM);
667 break;
671 static void check_dead_children(void)
673 int status;
674 pid_t pid;
676 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
677 const char *dead = "";
678 remove_child(pid);
679 if (!WIFEXITED(status) || (WEXITSTATUS(status) > 0))
680 dead = " (with error)";
681 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
685 static void handle(int incoming, struct sockaddr *addr, int addrlen)
687 pid_t pid;
689 if (max_connections && live_children >= max_connections) {
690 kill_some_child();
691 sleep(1); /* give it some time to die */
692 check_dead_children();
693 if (live_children >= max_connections) {
694 close(incoming);
695 logerror("Too many children, dropping connection");
696 return;
700 if ((pid = fork())) {
701 close(incoming);
702 if (pid < 0) {
703 logerror("Couldn't fork %s", strerror(errno));
704 return;
707 add_child(pid, addr, addrlen);
708 return;
711 dup2(incoming, 0);
712 dup2(incoming, 1);
713 close(incoming);
715 exit(execute(addr));
718 static void child_handler(int signo)
721 * Otherwise empty handler because systemcalls will get interrupted
722 * upon signal receipt
723 * SysV needs the handler to be rearmed
725 signal(SIGCHLD, child_handler);
728 static int set_reuse_addr(int sockfd)
730 int on = 1;
732 if (!reuseaddr)
733 return 0;
734 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
735 &on, sizeof(on));
738 #ifndef NO_IPV6
740 static int setup_named_sock(char *listen_addr, int listen_port, int **socklist_p, int socknum)
742 int *socklist = *socklist_p;
743 int maxfd = -1;
744 char pbuf[NI_MAXSERV];
745 struct addrinfo hints, *ai0, *ai;
746 int gai;
747 long flags;
749 sprintf(pbuf, "%d", listen_port);
750 memset(&hints, 0, sizeof(hints));
751 hints.ai_family = AF_UNSPEC;
752 hints.ai_socktype = SOCK_STREAM;
753 hints.ai_protocol = IPPROTO_TCP;
754 hints.ai_flags = AI_PASSIVE;
756 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
757 if (gai)
758 die("getaddrinfo() failed: %s", gai_strerror(gai));
760 for (ai = ai0; ai; ai = ai->ai_next) {
761 int sockfd;
763 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
764 if (sockfd < 0)
765 continue;
766 if (sockfd >= FD_SETSIZE) {
767 logerror("Socket descriptor too large");
768 close(sockfd);
769 continue;
772 #ifdef IPV6_V6ONLY
773 if (ai->ai_family == AF_INET6) {
774 int on = 1;
775 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
776 &on, sizeof(on));
777 /* Note: error is not fatal */
779 #endif
781 if (set_reuse_addr(sockfd)) {
782 close(sockfd);
783 continue;
786 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
787 close(sockfd);
788 continue; /* not fatal */
790 if (listen(sockfd, 5) < 0) {
791 close(sockfd);
792 continue; /* not fatal */
795 flags = fcntl(sockfd, F_GETFD, 0);
796 if (flags >= 0)
797 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
799 socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
800 socklist[socknum++] = sockfd;
802 if (maxfd < sockfd)
803 maxfd = sockfd;
806 freeaddrinfo(ai0);
808 *socklist_p = socklist;
809 return socknum;
812 #else /* NO_IPV6 */
814 static int setup_named_sock(char *listen_addr, int listen_port, int **socklist_p, int socknum)
816 int *socklist = *socklist_p;
817 struct sockaddr_in sin;
818 int sockfd;
819 long flags;
821 memset(&sin, 0, sizeof sin);
822 sin.sin_family = AF_INET;
823 sin.sin_port = htons(listen_port);
825 if (listen_addr) {
826 /* Well, host better be an IP address here. */
827 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
828 return socknum;
829 } else {
830 sin.sin_addr.s_addr = htonl(INADDR_ANY);
833 sockfd = socket(AF_INET, SOCK_STREAM, 0);
834 if (sockfd < 0)
835 return socknum;
837 if (set_reuse_addr(sockfd)) {
838 close(sockfd);
839 return socknum;
842 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
843 close(sockfd);
844 return socknum;
847 if (listen(sockfd, 5) < 0) {
848 close(sockfd);
849 return socknum;
852 flags = fcntl(sockfd, F_GETFD, 0);
853 if (flags >= 0)
854 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
856 socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
857 socklist[socknum++] = sockfd;
859 *socklist_p = socklist;
860 return socknum;
863 #endif
865 static int socksetup(struct string_list *listen_addr, int listen_port, int **socklist_p)
867 int socknum = 0, *socklist = NULL;
869 if (!listen_addr->nr)
870 socknum = setup_named_sock(NULL, listen_port, &socklist,
871 socknum);
872 else {
873 int i;
874 for (i = 0; i < listen_addr->nr; i++)
875 socknum = setup_named_sock(listen_addr->items[i].string,
876 listen_port, &socklist,
877 socknum);
880 *socklist_p = socklist;
881 return socknum;
884 static int service_loop(int socknum, int *socklist)
886 struct pollfd *pfd;
887 int i;
889 pfd = xcalloc(socknum, sizeof(struct pollfd));
891 for (i = 0; i < socknum; i++) {
892 pfd[i].fd = socklist[i];
893 pfd[i].events = POLLIN;
896 signal(SIGCHLD, child_handler);
898 for (;;) {
899 int i;
901 check_dead_children();
903 if (poll(pfd, socknum, -1) < 0) {
904 if (errno != EINTR) {
905 logerror("Poll failed, resuming: %s",
906 strerror(errno));
907 sleep(1);
909 continue;
912 for (i = 0; i < socknum; i++) {
913 if (pfd[i].revents & POLLIN) {
914 struct sockaddr_storage ss;
915 unsigned int sslen = sizeof(ss);
916 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
917 if (incoming < 0) {
918 switch (errno) {
919 case EAGAIN:
920 case EINTR:
921 case ECONNABORTED:
922 continue;
923 default:
924 die_errno("accept returned");
927 handle(incoming, (struct sockaddr *)&ss, sslen);
933 /* if any standard file descriptor is missing open it to /dev/null */
934 static void sanitize_stdfds(void)
936 int fd = open("/dev/null", O_RDWR, 0);
937 while (fd != -1 && fd < 2)
938 fd = dup(fd);
939 if (fd == -1)
940 die_errno("open /dev/null or dup failed");
941 if (fd > 2)
942 close(fd);
945 static void daemonize(void)
947 switch (fork()) {
948 case 0:
949 break;
950 case -1:
951 die_errno("fork failed");
952 default:
953 exit(0);
955 if (setsid() == -1)
956 die_errno("setsid failed");
957 close(0);
958 close(1);
959 close(2);
960 sanitize_stdfds();
963 static void store_pid(const char *path)
965 FILE *f = fopen(path, "w");
966 if (!f)
967 die_errno("cannot open pid file '%s'", path);
968 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
969 die_errno("failed to write pid file '%s'", path);
972 static int serve(struct string_list *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
974 int socknum, *socklist;
976 socknum = socksetup(listen_addr, listen_port, &socklist);
977 if (socknum == 0)
978 die("unable to allocate any listen sockets on port %u",
979 listen_port);
981 if (pass && gid &&
982 (initgroups(pass->pw_name, gid) || setgid (gid) ||
983 setuid(pass->pw_uid)))
984 die("cannot drop privileges");
986 return service_loop(socknum, socklist);
989 int main(int argc, char **argv)
991 int listen_port = 0;
992 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
993 int inetd_mode = 0;
994 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
995 int detach = 0;
996 struct passwd *pass = NULL;
997 struct group *group;
998 gid_t gid = 0;
999 int i;
1000 int return_value;
1002 git_extract_argv0_path(argv[0]);
1004 for (i = 1; i < argc; i++) {
1005 char *arg = argv[i];
1007 if (!prefixcmp(arg, "--listen=")) {
1008 string_list_append(&listen_addr, xstrdup_tolower(arg + 9));
1009 continue;
1011 if (!prefixcmp(arg, "--port=")) {
1012 char *end;
1013 unsigned long n;
1014 n = strtoul(arg+7, &end, 0);
1015 if (arg[7] && !*end) {
1016 listen_port = n;
1017 continue;
1020 if (!strcmp(arg, "--inetd")) {
1021 inetd_mode = 1;
1022 log_syslog = 1;
1023 continue;
1025 if (!strcmp(arg, "--verbose")) {
1026 verbose = 1;
1027 continue;
1029 if (!strcmp(arg, "--syslog")) {
1030 log_syslog = 1;
1031 continue;
1033 if (!strcmp(arg, "--export-all")) {
1034 export_all_trees = 1;
1035 continue;
1037 if (!prefixcmp(arg, "--timeout=")) {
1038 timeout = atoi(arg+10);
1039 continue;
1041 if (!prefixcmp(arg, "--init-timeout=")) {
1042 init_timeout = atoi(arg+15);
1043 continue;
1045 if (!prefixcmp(arg, "--max-connections=")) {
1046 max_connections = atoi(arg+18);
1047 if (max_connections < 0)
1048 max_connections = 0; /* unlimited */
1049 continue;
1051 if (!strcmp(arg, "--strict-paths")) {
1052 strict_paths = 1;
1053 continue;
1055 if (!prefixcmp(arg, "--base-path=")) {
1056 base_path = arg+12;
1057 continue;
1059 if (!strcmp(arg, "--base-path-relaxed")) {
1060 base_path_relaxed = 1;
1061 continue;
1063 if (!prefixcmp(arg, "--interpolated-path=")) {
1064 interpolated_path = arg+20;
1065 continue;
1067 if (!strcmp(arg, "--reuseaddr")) {
1068 reuseaddr = 1;
1069 continue;
1071 if (!strcmp(arg, "--user-path")) {
1072 user_path = "";
1073 continue;
1075 if (!prefixcmp(arg, "--user-path=")) {
1076 user_path = arg + 12;
1077 continue;
1079 if (!prefixcmp(arg, "--pid-file=")) {
1080 pid_file = arg + 11;
1081 continue;
1083 if (!strcmp(arg, "--detach")) {
1084 detach = 1;
1085 log_syslog = 1;
1086 continue;
1088 if (!prefixcmp(arg, "--user=")) {
1089 user_name = arg + 7;
1090 continue;
1092 if (!prefixcmp(arg, "--group=")) {
1093 group_name = arg + 8;
1094 continue;
1096 if (!prefixcmp(arg, "--enable=")) {
1097 enable_service(arg + 9, 1);
1098 continue;
1100 if (!prefixcmp(arg, "--disable=")) {
1101 enable_service(arg + 10, 0);
1102 continue;
1104 if (!prefixcmp(arg, "--allow-override=")) {
1105 make_service_overridable(arg + 17, 1);
1106 continue;
1108 if (!prefixcmp(arg, "--forbid-override=")) {
1109 make_service_overridable(arg + 18, 0);
1110 continue;
1112 if (!strcmp(arg, "--")) {
1113 ok_paths = &argv[i+1];
1114 break;
1115 } else if (arg[0] != '-') {
1116 ok_paths = &argv[i];
1117 break;
1120 usage(daemon_usage);
1123 if (log_syslog) {
1124 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1125 set_die_routine(daemon_die);
1126 } else
1127 /* avoid splitting a message in the middle */
1128 setvbuf(stderr, NULL, _IOLBF, 0);
1130 if (inetd_mode && (group_name || user_name))
1131 die("--user and --group are incompatible with --inetd");
1133 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1134 die("--listen= and --port= are incompatible with --inetd");
1135 else if (listen_port == 0)
1136 listen_port = DEFAULT_GIT_PORT;
1138 if (group_name && !user_name)
1139 die("--group supplied without --user");
1141 if (user_name) {
1142 pass = getpwnam(user_name);
1143 if (!pass)
1144 die("user not found - %s", user_name);
1146 if (!group_name)
1147 gid = pass->pw_gid;
1148 else {
1149 group = getgrnam(group_name);
1150 if (!group)
1151 die("group not found - %s", group_name);
1153 gid = group->gr_gid;
1157 if (strict_paths && (!ok_paths || !*ok_paths))
1158 die("option --strict-paths requires a whitelist");
1160 if (base_path && !is_directory(base_path))
1161 die("base-path '%s' does not exist or is not a directory",
1162 base_path);
1164 if (inetd_mode) {
1165 struct sockaddr_storage ss;
1166 struct sockaddr *peer = (struct sockaddr *)&ss;
1167 socklen_t slen = sizeof(ss);
1169 if (!freopen("/dev/null", "w", stderr))
1170 die_errno("failed to redirect stderr to /dev/null");
1172 if (getpeername(0, peer, &slen))
1173 peer = NULL;
1175 return execute(peer);
1178 if (detach) {
1179 daemonize();
1180 loginfo("Ready to rumble");
1182 else
1183 sanitize_stdfds();
1185 if (pid_file)
1186 store_pid(pid_file);
1188 return_value = serve(&listen_addr, listen_port, pass, gid);
1190 string_list_clear(&listen_addr, 0);
1192 return return_value;