daemon: handle freopen() failure
[tgit.git] / daemon.c
blob8c317bed4a3bc4e2e8e5afe301084071789e3362
1 #include "cache.h"
2 #include "pkt-line.h"
3 #include "exec_cmd.h"
5 #include <syslog.h>
7 #ifndef HOST_NAME_MAX
8 #define HOST_NAME_MAX 256
9 #endif
11 #ifndef NI_MAXSERV
12 #define NI_MAXSERV 32
13 #endif
15 static int log_syslog;
16 static int verbose;
17 static int reuseaddr;
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"
29 " [directory...]";
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)
63 if (log_syslog) {
64 char buf[1024];
65 vsnprintf(buf, sizeof(buf), err, params);
66 syslog(priority, "%s", buf);
67 } else {
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);
74 fputc('\n', stderr);
78 static void logerror(const char *err, ...)
80 va_list params;
81 va_start(params, err);
82 logreport(LOG_ERR, err, params);
83 va_end(params);
86 static void loginfo(const char *err, ...)
88 va_list params;
89 if (!verbose)
90 return;
91 va_start(params, err);
92 logreport(LOG_INFO, err, params);
93 va_end(params);
96 static void NORETURN daemon_die(const char *err, va_list params)
98 logreport(LOG_ERR, err, params);
99 exit(1);
102 static int avoid_alias(char *p)
104 int sl, ndot;
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
113 * non-dot character.
115 if (!p || (*p != '/' && *p != '~'))
116 return -1;
117 sl = 1; ndot = 0;
118 p++;
120 while (1) {
121 char ch = *p++;
122 if (sl) {
123 if (ch == '.')
124 ndot++;
125 else if (ch == '/') {
126 if (ndot < 3)
127 /* reject //, /./ and /../ */
128 return -1;
129 ndot = 0;
131 else if (ch == 0) {
132 if (0 < ndot && ndot < 3)
133 /* reject /.$ and /..$ */
134 return -1;
135 return 0;
137 else
138 sl = ndot = 0;
140 else if (ch == 0)
141 return 0;
142 else if (ch == '/') {
143 sl = 1;
144 ndot = 0;
149 static char *path_ok(char *directory)
151 static char rpath[PATH_MAX];
152 static char interp_path[PATH_MAX];
153 int retried_path = 0;
154 char *path;
155 char *dir;
157 dir = directory;
159 if (avoid_alias(dir)) {
160 logerror("'%s': aliased", dir);
161 return NULL;
164 if (*dir == '~') {
165 if (!user_path) {
166 logerror("'%s': User-path not allowed", dir);
167 return NULL;
169 if (*user_path) {
170 /* Got either "~alice" or "~alice/foo";
171 * rewrite them to "~alice/%s" or
172 * "~alice/%s/foo".
174 int namlen, restlen = strlen(dir);
175 char *slash = strchr(dir, '/');
176 if (!slash)
177 slash = dir + restlen;
178 namlen = slash - dir;
179 restlen -= namlen;
180 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
181 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
182 namlen, dir, user_path, restlen, slash);
183 dir = rpath;
186 else if (interpolated_path && saw_extended_args) {
187 struct strbuf expanded_path = STRBUF_INIT;
188 struct strbuf_expand_dict_entry dict[] = {
189 { "H", hostname },
190 { "CH", canon_hostname },
191 { "IP", ip_address },
192 { "P", tcp_port },
193 { "D", directory },
194 { "%", "%" },
195 { NULL }
198 if (*dir != '/') {
199 /* Allow only absolute */
200 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
201 return NULL;
204 strbuf_expand(&expanded_path, interpolated_path,
205 strbuf_expand_dict_cb, &dict);
206 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
207 strbuf_release(&expanded_path);
208 loginfo("Interpolated dir '%s'", interp_path);
210 dir = interp_path;
212 else if (base_path) {
213 if (*dir != '/') {
214 /* Allow only absolute */
215 logerror("'%s': Non-absolute path denied (base-path active)", dir);
216 return NULL;
218 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
219 dir = rpath;
222 do {
223 path = enter_repo(dir, strict_paths);
224 if (path)
225 break;
228 * if we fail and base_path_relaxed is enabled, try without
229 * prefixing the base path
231 if (base_path && base_path_relaxed && !retried_path) {
232 dir = directory;
233 retried_path = 1;
234 continue;
236 break;
237 } while (1);
239 if (!path) {
240 logerror("'%s': unable to chdir or not a git archive", dir);
241 return NULL;
244 if ( ok_paths && *ok_paths ) {
245 char **pp;
246 int pathlen = strlen(path);
248 /* The validation is done on the paths after enter_repo
249 * appends optional {.git,.git/.git} and friends, but
250 * it does not use getcwd(). So if your /pub is
251 * a symlink to /mnt/pub, you can whitelist /pub and
252 * do not have to say /mnt/pub.
253 * Do not say /pub/.
255 for ( pp = ok_paths ; *pp ; pp++ ) {
256 int len = strlen(*pp);
257 if (len <= pathlen &&
258 !memcmp(*pp, path, len) &&
259 (path[len] == '\0' ||
260 (!strict_paths && path[len] == '/')))
261 return path;
264 else {
265 /* be backwards compatible */
266 if (!strict_paths)
267 return path;
270 logerror("'%s': not in whitelist", path);
271 return NULL; /* Fallthrough. Deny by default */
274 typedef int (*daemon_service_fn)(void);
275 struct daemon_service {
276 const char *name;
277 const char *config_name;
278 daemon_service_fn fn;
279 int enabled;
280 int overridable;
283 static struct daemon_service *service_looking_at;
284 static int service_enabled;
286 static int git_daemon_config(const char *var, const char *value, void *cb)
288 if (!prefixcmp(var, "daemon.") &&
289 !strcmp(var + 7, service_looking_at->config_name)) {
290 service_enabled = git_config_bool(var, value);
291 return 0;
294 /* we are not interested in parsing any other configuration here */
295 return 0;
298 static int run_service(char *dir, struct daemon_service *service)
300 const char *path;
301 int enabled = service->enabled;
303 loginfo("Request %s for '%s'", service->name, dir);
305 if (!enabled && !service->overridable) {
306 logerror("'%s': service not enabled.", service->name);
307 errno = EACCES;
308 return -1;
311 if (!(path = path_ok(dir)))
312 return -1;
315 * Security on the cheap.
317 * We want a readable HEAD, usable "objects" directory, and
318 * a "git-daemon-export-ok" flag that says that the other side
319 * is ok with us doing this.
321 * path_ok() uses enter_repo() and does whitelist checking.
322 * We only need to make sure the repository is exported.
325 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
326 logerror("'%s': repository not exported.", path);
327 errno = EACCES;
328 return -1;
331 if (service->overridable) {
332 service_looking_at = service;
333 service_enabled = -1;
334 git_config(git_daemon_config, NULL);
335 if (0 <= service_enabled)
336 enabled = service_enabled;
338 if (!enabled) {
339 logerror("'%s': service not enabled for '%s'",
340 service->name, path);
341 errno = EACCES;
342 return -1;
346 * We'll ignore SIGTERM from now on, we have a
347 * good client.
349 signal(SIGTERM, SIG_IGN);
351 return service->fn();
354 static int upload_pack(void)
356 /* Timeout as string */
357 char timeout_buf[64];
359 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
361 /* git-upload-pack only ever reads stuff, so this is safe */
362 execl_git_cmd("upload-pack", "--strict", timeout_buf, ".", NULL);
363 return -1;
366 static int upload_archive(void)
368 execl_git_cmd("upload-archive", ".", NULL);
369 return -1;
372 static int receive_pack(void)
374 execl_git_cmd("receive-pack", ".", NULL);
375 return -1;
378 static struct daemon_service daemon_service[] = {
379 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
380 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
381 { "receive-pack", "receivepack", receive_pack, 0, 1 },
384 static void enable_service(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].enabled = ena;
390 return;
393 die("No such service %s", name);
396 static void make_service_overridable(const char *name, int ena)
398 int i;
399 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
400 if (!strcmp(daemon_service[i].name, name)) {
401 daemon_service[i].overridable = ena;
402 return;
405 die("No such service %s", name);
409 * Separate the "extra args" information as supplied by the client connection.
411 static void parse_extra_args(char *extra_args, int buflen)
413 char *val;
414 int vallen;
415 char *end = extra_args + buflen;
416 char *hp;
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;
423 if (*val) {
424 /* Split <host>:<port> at colon. */
425 char *host = val;
426 char *port = strrchr(host, ':');
427 if (port) {
428 *port = 0;
429 port++;
430 free(tcp_port);
431 tcp_port = xstrdup(port);
433 free(hostname);
434 hostname = xstrdup(host);
437 /* On to the next one */
438 extra_args = val + vallen;
443 * Replace literal host with lowercase-ized hostname.
445 hp = hostname;
446 if (!hp)
447 return;
448 for ( ; *hp; hp++)
449 *hp = tolower(*hp);
452 * Locate canonical hostname and its IP address.
454 #ifndef NO_IPV6
456 struct addrinfo hints;
457 struct addrinfo *ai, *ai0;
458 int gai;
459 static char addrbuf[HOST_NAME_MAX + 1];
461 memset(&hints, 0, sizeof(hints));
462 hints.ai_flags = AI_CANONNAME;
464 gai = getaddrinfo(hostname, 0, &hints, &ai0);
465 if (!gai) {
466 for (ai = ai0; ai; ai = ai->ai_next) {
467 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
469 inet_ntop(AF_INET, &sin_addr->sin_addr,
470 addrbuf, sizeof(addrbuf));
471 free(canon_hostname);
472 canon_hostname = xstrdup(ai->ai_canonname);
473 free(ip_address);
474 ip_address = xstrdup(addrbuf);
475 break;
477 freeaddrinfo(ai0);
480 #else
482 struct hostent *hent;
483 struct sockaddr_in sa;
484 char **ap;
485 static char addrbuf[HOST_NAME_MAX + 1];
487 hent = gethostbyname(hostname);
489 ap = hent->h_addr_list;
490 memset(&sa, 0, sizeof sa);
491 sa.sin_family = hent->h_addrtype;
492 sa.sin_port = htons(0);
493 memcpy(&sa.sin_addr, *ap, hent->h_length);
495 inet_ntop(hent->h_addrtype, &sa.sin_addr,
496 addrbuf, sizeof(addrbuf));
498 free(canon_hostname);
499 canon_hostname = xstrdup(hent->h_name);
500 free(ip_address);
501 ip_address = xstrdup(addrbuf);
503 #endif
507 static int execute(struct sockaddr *addr)
509 static char line[1000];
510 int pktlen, len, i;
512 if (addr) {
513 char addrbuf[256] = "";
514 int port = -1;
516 if (addr->sa_family == AF_INET) {
517 struct sockaddr_in *sin_addr = (void *) addr;
518 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
519 port = ntohs(sin_addr->sin_port);
520 #ifndef NO_IPV6
521 } else if (addr && addr->sa_family == AF_INET6) {
522 struct sockaddr_in6 *sin6_addr = (void *) addr;
524 char *buf = addrbuf;
525 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
526 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
527 strcat(buf, "]");
529 port = ntohs(sin6_addr->sin6_port);
530 #endif
532 loginfo("Connection from %s:%d", addrbuf, port);
533 setenv("REMOTE_ADDR", addrbuf, 1);
535 else {
536 unsetenv("REMOTE_ADDR");
539 alarm(init_timeout ? init_timeout : timeout);
540 pktlen = packet_read_line(0, line, sizeof(line));
541 alarm(0);
543 len = strlen(line);
544 if (pktlen != len)
545 loginfo("Extended attributes (%d bytes) exist <%.*s>",
546 (int) pktlen - len,
547 (int) pktlen - len, line + len + 1);
548 if (len && line[len-1] == '\n') {
549 line[--len] = 0;
550 pktlen--;
553 free(hostname);
554 free(canon_hostname);
555 free(ip_address);
556 free(tcp_port);
557 hostname = canon_hostname = ip_address = tcp_port = NULL;
559 if (len != pktlen)
560 parse_extra_args(line + len + 1, pktlen - len - 1);
562 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
563 struct daemon_service *s = &(daemon_service[i]);
564 int namelen = strlen(s->name);
565 if (!prefixcmp(line, "git-") &&
566 !strncmp(s->name, line + 4, namelen) &&
567 line[namelen + 4] == ' ') {
569 * Note: The directory here is probably context sensitive,
570 * and might depend on the actual service being performed.
572 return run_service(line + namelen + 5, s);
576 logerror("Protocol error: '%s'", line);
577 return -1;
580 static int max_connections = 32;
582 static unsigned int live_children;
584 static struct child {
585 struct child *next;
586 pid_t pid;
587 struct sockaddr_storage address;
588 } *firstborn;
590 static void add_child(pid_t pid, struct sockaddr *addr, int addrlen)
592 struct child *newborn, **cradle;
595 * This must be xcalloc() -- we'll compare the whole sockaddr_storage
596 * but individual address may be shorter.
598 newborn = xcalloc(1, sizeof(*newborn));
599 live_children++;
600 newborn->pid = pid;
601 memcpy(&newborn->address, addr, addrlen);
602 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
603 if (!memcmp(&(*cradle)->address, &newborn->address,
604 sizeof(newborn->address)))
605 break;
606 newborn->next = *cradle;
607 *cradle = newborn;
610 static void remove_child(pid_t pid)
612 struct child **cradle, *blanket;
614 for (cradle = &firstborn; (blanket = *cradle); cradle = &blanket->next)
615 if (blanket->pid == pid) {
616 *cradle = blanket->next;
617 live_children--;
618 free(blanket);
619 break;
624 * This gets called if the number of connections grows
625 * past "max_connections".
627 * We kill the newest connection from a duplicate IP.
629 static void kill_some_child(void)
631 const struct child *blanket, *next;
633 if (!(blanket = firstborn))
634 return;
636 for (; (next = blanket->next); blanket = next)
637 if (!memcmp(&blanket->address, &next->address,
638 sizeof(next->address))) {
639 kill(blanket->pid, SIGTERM);
640 break;
644 static void check_dead_children(void)
646 int status;
647 pid_t pid;
649 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
650 const char *dead = "";
651 remove_child(pid);
652 if (!WIFEXITED(status) || (WEXITSTATUS(status) > 0))
653 dead = " (with error)";
654 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
658 static void handle(int incoming, struct sockaddr *addr, int addrlen)
660 pid_t pid;
662 if (max_connections && live_children >= max_connections) {
663 kill_some_child();
664 sleep(1); /* give it some time to die */
665 check_dead_children();
666 if (live_children >= max_connections) {
667 close(incoming);
668 logerror("Too many children, dropping connection");
669 return;
673 if ((pid = fork())) {
674 close(incoming);
675 if (pid < 0) {
676 logerror("Couldn't fork %s", strerror(errno));
677 return;
680 add_child(pid, addr, addrlen);
681 return;
684 dup2(incoming, 0);
685 dup2(incoming, 1);
686 close(incoming);
688 exit(execute(addr));
691 static void child_handler(int signo)
694 * Otherwise empty handler because systemcalls will get interrupted
695 * upon signal receipt
696 * SysV needs the handler to be rearmed
698 signal(SIGCHLD, child_handler);
701 static int set_reuse_addr(int sockfd)
703 int on = 1;
705 if (!reuseaddr)
706 return 0;
707 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
708 &on, sizeof(on));
711 #ifndef NO_IPV6
713 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
715 int socknum = 0, *socklist = NULL;
716 int maxfd = -1;
717 char pbuf[NI_MAXSERV];
718 struct addrinfo hints, *ai0, *ai;
719 int gai;
720 long flags;
722 sprintf(pbuf, "%d", listen_port);
723 memset(&hints, 0, sizeof(hints));
724 hints.ai_family = AF_UNSPEC;
725 hints.ai_socktype = SOCK_STREAM;
726 hints.ai_protocol = IPPROTO_TCP;
727 hints.ai_flags = AI_PASSIVE;
729 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
730 if (gai)
731 die("getaddrinfo() failed: %s\n", gai_strerror(gai));
733 for (ai = ai0; ai; ai = ai->ai_next) {
734 int sockfd;
736 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
737 if (sockfd < 0)
738 continue;
739 if (sockfd >= FD_SETSIZE) {
740 logerror("Socket descriptor too large");
741 close(sockfd);
742 continue;
745 #ifdef IPV6_V6ONLY
746 if (ai->ai_family == AF_INET6) {
747 int on = 1;
748 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
749 &on, sizeof(on));
750 /* Note: error is not fatal */
752 #endif
754 if (set_reuse_addr(sockfd)) {
755 close(sockfd);
756 continue;
759 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
760 close(sockfd);
761 continue; /* not fatal */
763 if (listen(sockfd, 5) < 0) {
764 close(sockfd);
765 continue; /* not fatal */
768 flags = fcntl(sockfd, F_GETFD, 0);
769 if (flags >= 0)
770 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
772 socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
773 socklist[socknum++] = sockfd;
775 if (maxfd < sockfd)
776 maxfd = sockfd;
779 freeaddrinfo(ai0);
781 *socklist_p = socklist;
782 return socknum;
785 #else /* NO_IPV6 */
787 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
789 struct sockaddr_in sin;
790 int sockfd;
791 long flags;
793 memset(&sin, 0, sizeof sin);
794 sin.sin_family = AF_INET;
795 sin.sin_port = htons(listen_port);
797 if (listen_addr) {
798 /* Well, host better be an IP address here. */
799 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
800 return 0;
801 } else {
802 sin.sin_addr.s_addr = htonl(INADDR_ANY);
805 sockfd = socket(AF_INET, SOCK_STREAM, 0);
806 if (sockfd < 0)
807 return 0;
809 if (set_reuse_addr(sockfd)) {
810 close(sockfd);
811 return 0;
814 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
815 close(sockfd);
816 return 0;
819 if (listen(sockfd, 5) < 0) {
820 close(sockfd);
821 return 0;
824 flags = fcntl(sockfd, F_GETFD, 0);
825 if (flags >= 0)
826 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
828 *socklist_p = xmalloc(sizeof(int));
829 **socklist_p = sockfd;
830 return 1;
833 #endif
835 static int service_loop(int socknum, int *socklist)
837 struct pollfd *pfd;
838 int i;
840 pfd = xcalloc(socknum, sizeof(struct pollfd));
842 for (i = 0; i < socknum; i++) {
843 pfd[i].fd = socklist[i];
844 pfd[i].events = POLLIN;
847 signal(SIGCHLD, child_handler);
849 for (;;) {
850 int i;
852 check_dead_children();
854 if (poll(pfd, socknum, -1) < 0) {
855 if (errno != EINTR) {
856 logerror("Poll failed, resuming: %s",
857 strerror(errno));
858 sleep(1);
860 continue;
863 for (i = 0; i < socknum; i++) {
864 if (pfd[i].revents & POLLIN) {
865 struct sockaddr_storage ss;
866 unsigned int sslen = sizeof(ss);
867 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
868 if (incoming < 0) {
869 switch (errno) {
870 case EAGAIN:
871 case EINTR:
872 case ECONNABORTED:
873 continue;
874 default:
875 die("accept returned %s", strerror(errno));
878 handle(incoming, (struct sockaddr *)&ss, sslen);
884 /* if any standard file descriptor is missing open it to /dev/null */
885 static void sanitize_stdfds(void)
887 int fd = open("/dev/null", O_RDWR, 0);
888 while (fd != -1 && fd < 2)
889 fd = dup(fd);
890 if (fd == -1)
891 die("open /dev/null or dup failed: %s", strerror(errno));
892 if (fd > 2)
893 close(fd);
896 static void daemonize(void)
898 switch (fork()) {
899 case 0:
900 break;
901 case -1:
902 die("fork failed: %s", strerror(errno));
903 default:
904 exit(0);
906 if (setsid() == -1)
907 die("setsid failed: %s", strerror(errno));
908 close(0);
909 close(1);
910 close(2);
911 sanitize_stdfds();
914 static void store_pid(const char *path)
916 FILE *f = fopen(path, "w");
917 if (!f)
918 die("cannot open pid file %s: %s", path, strerror(errno));
919 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
920 die("failed to write pid file %s: %s", path, strerror(errno));
923 static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
925 int socknum, *socklist;
927 socknum = socksetup(listen_addr, listen_port, &socklist);
928 if (socknum == 0)
929 die("unable to allocate any listen sockets on host %s port %u",
930 listen_addr, listen_port);
932 if (pass && gid &&
933 (initgroups(pass->pw_name, gid) || setgid (gid) ||
934 setuid(pass->pw_uid)))
935 die("cannot drop privileges");
937 return service_loop(socknum, socklist);
940 int main(int argc, char **argv)
942 int listen_port = 0;
943 char *listen_addr = NULL;
944 int inetd_mode = 0;
945 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
946 int detach = 0;
947 struct passwd *pass = NULL;
948 struct group *group;
949 gid_t gid = 0;
950 int i;
952 for (i = 1; i < argc; i++) {
953 char *arg = argv[i];
955 if (!prefixcmp(arg, "--listen=")) {
956 char *p = arg + 9;
957 char *ph = listen_addr = xmalloc(strlen(arg + 9) + 1);
958 while (*p)
959 *ph++ = tolower(*p++);
960 *ph = 0;
961 continue;
963 if (!prefixcmp(arg, "--port=")) {
964 char *end;
965 unsigned long n;
966 n = strtoul(arg+7, &end, 0);
967 if (arg[7] && !*end) {
968 listen_port = n;
969 continue;
972 if (!strcmp(arg, "--inetd")) {
973 inetd_mode = 1;
974 log_syslog = 1;
975 continue;
977 if (!strcmp(arg, "--verbose")) {
978 verbose = 1;
979 continue;
981 if (!strcmp(arg, "--syslog")) {
982 log_syslog = 1;
983 continue;
985 if (!strcmp(arg, "--export-all")) {
986 export_all_trees = 1;
987 continue;
989 if (!prefixcmp(arg, "--timeout=")) {
990 timeout = atoi(arg+10);
991 continue;
993 if (!prefixcmp(arg, "--init-timeout=")) {
994 init_timeout = atoi(arg+15);
995 continue;
997 if (!prefixcmp(arg, "--max-connections=")) {
998 max_connections = atoi(arg+18);
999 if (max_connections < 0)
1000 max_connections = 0; /* unlimited */
1001 continue;
1003 if (!strcmp(arg, "--strict-paths")) {
1004 strict_paths = 1;
1005 continue;
1007 if (!prefixcmp(arg, "--base-path=")) {
1008 base_path = arg+12;
1009 continue;
1011 if (!strcmp(arg, "--base-path-relaxed")) {
1012 base_path_relaxed = 1;
1013 continue;
1015 if (!prefixcmp(arg, "--interpolated-path=")) {
1016 interpolated_path = arg+20;
1017 continue;
1019 if (!strcmp(arg, "--reuseaddr")) {
1020 reuseaddr = 1;
1021 continue;
1023 if (!strcmp(arg, "--user-path")) {
1024 user_path = "";
1025 continue;
1027 if (!prefixcmp(arg, "--user-path=")) {
1028 user_path = arg + 12;
1029 continue;
1031 if (!prefixcmp(arg, "--pid-file=")) {
1032 pid_file = arg + 11;
1033 continue;
1035 if (!strcmp(arg, "--detach")) {
1036 detach = 1;
1037 log_syslog = 1;
1038 continue;
1040 if (!prefixcmp(arg, "--user=")) {
1041 user_name = arg + 7;
1042 continue;
1044 if (!prefixcmp(arg, "--group=")) {
1045 group_name = arg + 8;
1046 continue;
1048 if (!prefixcmp(arg, "--enable=")) {
1049 enable_service(arg + 9, 1);
1050 continue;
1052 if (!prefixcmp(arg, "--disable=")) {
1053 enable_service(arg + 10, 0);
1054 continue;
1056 if (!prefixcmp(arg, "--allow-override=")) {
1057 make_service_overridable(arg + 17, 1);
1058 continue;
1060 if (!prefixcmp(arg, "--forbid-override=")) {
1061 make_service_overridable(arg + 18, 0);
1062 continue;
1064 if (!strcmp(arg, "--")) {
1065 ok_paths = &argv[i+1];
1066 break;
1067 } else if (arg[0] != '-') {
1068 ok_paths = &argv[i];
1069 break;
1072 usage(daemon_usage);
1075 if (log_syslog) {
1076 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1077 set_die_routine(daemon_die);
1078 } else
1079 /* avoid splitting a message in the middle */
1080 setvbuf(stderr, NULL, _IOLBF, 0);
1082 if (inetd_mode && (group_name || user_name))
1083 die("--user and --group are incompatible with --inetd");
1085 if (inetd_mode && (listen_port || listen_addr))
1086 die("--listen= and --port= are incompatible with --inetd");
1087 else if (listen_port == 0)
1088 listen_port = DEFAULT_GIT_PORT;
1090 if (group_name && !user_name)
1091 die("--group supplied without --user");
1093 if (user_name) {
1094 pass = getpwnam(user_name);
1095 if (!pass)
1096 die("user not found - %s", user_name);
1098 if (!group_name)
1099 gid = pass->pw_gid;
1100 else {
1101 group = getgrnam(group_name);
1102 if (!group)
1103 die("group not found - %s", group_name);
1105 gid = group->gr_gid;
1109 if (strict_paths && (!ok_paths || !*ok_paths))
1110 die("option --strict-paths requires a whitelist");
1112 if (base_path && !is_directory(base_path))
1113 die("base-path '%s' does not exist or is not a directory",
1114 base_path);
1116 if (inetd_mode) {
1117 struct sockaddr_storage ss;
1118 struct sockaddr *peer = (struct sockaddr *)&ss;
1119 socklen_t slen = sizeof(ss);
1121 if (!freopen("/dev/null", "w", stderr))
1122 die("failed to redirect stderr to /dev/null: %s",
1123 strerror(errno));
1125 if (getpeername(0, peer, &slen))
1126 peer = NULL;
1128 return execute(peer);
1131 if (detach) {
1132 daemonize();
1133 loginfo("Ready to rumble");
1135 else
1136 sanitize_stdfds();
1138 if (pid_file)
1139 store_pid(pid_file);
1141 return serve(listen_addr, listen_port, pass, gid);