bash: remove unnecessary checks for long options with argument
[git/spearce.git] / daemon.c
blob540700ee844eb47c417c10a04a85af9af5b23569
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 char *path;
154 char *dir;
156 dir = directory;
158 if (avoid_alias(dir)) {
159 logerror("'%s': aliased", dir);
160 return NULL;
163 if (*dir == '~') {
164 if (!user_path) {
165 logerror("'%s': User-path not allowed", dir);
166 return NULL;
168 if (*user_path) {
169 /* Got either "~alice" or "~alice/foo";
170 * rewrite them to "~alice/%s" or
171 * "~alice/%s/foo".
173 int namlen, restlen = strlen(dir);
174 char *slash = strchr(dir, '/');
175 if (!slash)
176 slash = dir + restlen;
177 namlen = slash - dir;
178 restlen -= namlen;
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);
182 dir = rpath;
185 else if (interpolated_path && saw_extended_args) {
186 struct strbuf expanded_path = STRBUF_INIT;
187 struct strbuf_expand_dict_entry dict[] = {
188 { "H", hostname },
189 { "CH", canon_hostname },
190 { "IP", ip_address },
191 { "P", tcp_port },
192 { "D", directory },
193 { "%", "%" },
194 { NULL }
197 if (*dir != '/') {
198 /* Allow only absolute */
199 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
200 return NULL;
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);
209 dir = interp_path;
211 else if (base_path) {
212 if (*dir != '/') {
213 /* Allow only absolute */
214 logerror("'%s': Non-absolute path denied (base-path active)", dir);
215 return NULL;
217 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
218 dir = rpath;
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
227 dir = directory;
228 path = enter_repo(dir, strict_paths);
231 if (!path) {
232 logerror("'%s': unable to chdir or not a git archive", dir);
233 return NULL;
236 if ( ok_paths && *ok_paths ) {
237 char **pp;
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.
245 * Do not say /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] == '/')))
253 return path;
256 else {
257 /* be backwards compatible */
258 if (!strict_paths)
259 return path;
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 {
268 const char *name;
269 const char *config_name;
270 daemon_service_fn fn;
271 int enabled;
272 int overridable;
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);
283 return 0;
286 /* we are not interested in parsing any other configuration here */
287 return 0;
290 static int run_service(char *dir, struct daemon_service *service)
292 const char *path;
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);
299 errno = EACCES;
300 return -1;
303 if (!(path = path_ok(dir)))
304 return -1;
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);
319 errno = EACCES;
320 return -1;
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;
330 if (!enabled) {
331 logerror("'%s': service not enabled for '%s'",
332 service->name, path);
333 errno = EACCES;
334 return -1;
338 * We'll ignore SIGTERM from now on, we have a
339 * good client.
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);
355 return -1;
358 static int upload_archive(void)
360 execl_git_cmd("upload-archive", ".", NULL);
361 return -1;
364 static int receive_pack(void)
366 execl_git_cmd("receive-pack", ".", NULL);
367 return -1;
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)
378 int i;
379 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
380 if (!strcmp(daemon_service[i].name, name)) {
381 daemon_service[i].enabled = ena;
382 return;
385 die("No such service %s", name);
388 static void make_service_overridable(const char *name, int ena)
390 int i;
391 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
392 if (!strcmp(daemon_service[i].name, name)) {
393 daemon_service[i].overridable = ena;
394 return;
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++)
404 *p = tolower(*p);
405 return dup;
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;
417 while (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;
422 if (*val) {
423 /* Split <host>:<port> at colon. */
424 char *host = val;
425 char *port = strrchr(host, ':');
426 if (port) {
427 *port = 0;
428 port++;
429 free(tcp_port);
430 tcp_port = xstrdup(port);
432 free(hostname);
433 hostname = xstrdup_tolower(host);
436 /* On to the next one */
437 extra_args = val + vallen;
442 * Locate canonical hostname and its IP address.
444 if (hostname) {
445 #ifndef NO_IPV6
446 struct addrinfo hints;
447 struct addrinfo *ai, *ai0;
448 int gai;
449 static char addrbuf[HOST_NAME_MAX + 1];
451 memset(&hints, 0, sizeof(hints));
452 hints.ai_flags = AI_CANONNAME;
454 gai = getaddrinfo(hostname, 0, &hints, &ai0);
455 if (!gai) {
456 for (ai = ai0; ai; ai = ai->ai_next) {
457 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
459 inet_ntop(AF_INET, &sin_addr->sin_addr,
460 addrbuf, sizeof(addrbuf));
461 free(canon_hostname);
462 canon_hostname = xstrdup(ai->ai_canonname);
463 free(ip_address);
464 ip_address = xstrdup(addrbuf);
465 break;
467 freeaddrinfo(ai0);
469 #else
470 struct hostent *hent;
471 struct sockaddr_in sa;
472 char **ap;
473 static char addrbuf[HOST_NAME_MAX + 1];
475 hent = gethostbyname(hostname);
477 ap = hent->h_addr_list;
478 memset(&sa, 0, sizeof sa);
479 sa.sin_family = hent->h_addrtype;
480 sa.sin_port = htons(0);
481 memcpy(&sa.sin_addr, *ap, hent->h_length);
483 inet_ntop(hent->h_addrtype, &sa.sin_addr,
484 addrbuf, sizeof(addrbuf));
486 free(canon_hostname);
487 canon_hostname = xstrdup(hent->h_name);
488 free(ip_address);
489 ip_address = xstrdup(addrbuf);
490 #endif
495 static int execute(struct sockaddr *addr)
497 static char line[1000];
498 int pktlen, len, i;
500 if (addr) {
501 char addrbuf[256] = "";
502 int port = -1;
504 if (addr->sa_family == AF_INET) {
505 struct sockaddr_in *sin_addr = (void *) addr;
506 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
507 port = ntohs(sin_addr->sin_port);
508 #ifndef NO_IPV6
509 } else if (addr && addr->sa_family == AF_INET6) {
510 struct sockaddr_in6 *sin6_addr = (void *) addr;
512 char *buf = addrbuf;
513 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
514 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
515 strcat(buf, "]");
517 port = ntohs(sin6_addr->sin6_port);
518 #endif
520 loginfo("Connection from %s:%d", addrbuf, port);
521 setenv("REMOTE_ADDR", addrbuf, 1);
523 else {
524 unsetenv("REMOTE_ADDR");
527 alarm(init_timeout ? init_timeout : timeout);
528 pktlen = packet_read_line(0, line, sizeof(line));
529 alarm(0);
531 len = strlen(line);
532 if (pktlen != len)
533 loginfo("Extended attributes (%d bytes) exist <%.*s>",
534 (int) pktlen - len,
535 (int) pktlen - len, line + len + 1);
536 if (len && line[len-1] == '\n') {
537 line[--len] = 0;
538 pktlen--;
541 free(hostname);
542 free(canon_hostname);
543 free(ip_address);
544 free(tcp_port);
545 hostname = canon_hostname = ip_address = tcp_port = NULL;
547 if (len != pktlen)
548 parse_extra_args(line + len + 1, pktlen - len - 1);
550 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
551 struct daemon_service *s = &(daemon_service[i]);
552 int namelen = strlen(s->name);
553 if (!prefixcmp(line, "git-") &&
554 !strncmp(s->name, line + 4, namelen) &&
555 line[namelen + 4] == ' ') {
557 * Note: The directory here is probably context sensitive,
558 * and might depend on the actual service being performed.
560 return run_service(line + namelen + 5, s);
564 logerror("Protocol error: '%s'", line);
565 return -1;
568 static int max_connections = 32;
570 static unsigned int live_children;
572 static struct child {
573 struct child *next;
574 pid_t pid;
575 struct sockaddr_storage address;
576 } *firstborn;
578 static void add_child(pid_t pid, struct sockaddr *addr, int addrlen)
580 struct child *newborn, **cradle;
583 * This must be xcalloc() -- we'll compare the whole sockaddr_storage
584 * but individual address may be shorter.
586 newborn = xcalloc(1, sizeof(*newborn));
587 live_children++;
588 newborn->pid = pid;
589 memcpy(&newborn->address, addr, addrlen);
590 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
591 if (!memcmp(&(*cradle)->address, &newborn->address,
592 sizeof(newborn->address)))
593 break;
594 newborn->next = *cradle;
595 *cradle = newborn;
598 static void remove_child(pid_t pid)
600 struct child **cradle, *blanket;
602 for (cradle = &firstborn; (blanket = *cradle); cradle = &blanket->next)
603 if (blanket->pid == pid) {
604 *cradle = blanket->next;
605 live_children--;
606 free(blanket);
607 break;
612 * This gets called if the number of connections grows
613 * past "max_connections".
615 * We kill the newest connection from a duplicate IP.
617 static void kill_some_child(void)
619 const struct child *blanket, *next;
621 if (!(blanket = firstborn))
622 return;
624 for (; (next = blanket->next); blanket = next)
625 if (!memcmp(&blanket->address, &next->address,
626 sizeof(next->address))) {
627 kill(blanket->pid, SIGTERM);
628 break;
632 static void check_dead_children(void)
634 int status;
635 pid_t pid;
637 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
638 const char *dead = "";
639 remove_child(pid);
640 if (!WIFEXITED(status) || (WEXITSTATUS(status) > 0))
641 dead = " (with error)";
642 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
646 static void handle(int incoming, struct sockaddr *addr, int addrlen)
648 pid_t pid;
650 if (max_connections && live_children >= max_connections) {
651 kill_some_child();
652 sleep(1); /* give it some time to die */
653 check_dead_children();
654 if (live_children >= max_connections) {
655 close(incoming);
656 logerror("Too many children, dropping connection");
657 return;
661 if ((pid = fork())) {
662 close(incoming);
663 if (pid < 0) {
664 logerror("Couldn't fork %s", strerror(errno));
665 return;
668 add_child(pid, addr, addrlen);
669 return;
672 dup2(incoming, 0);
673 dup2(incoming, 1);
674 close(incoming);
676 exit(execute(addr));
679 static void child_handler(int signo)
682 * Otherwise empty handler because systemcalls will get interrupted
683 * upon signal receipt
684 * SysV needs the handler to be rearmed
686 signal(SIGCHLD, child_handler);
689 static int set_reuse_addr(int sockfd)
691 int on = 1;
693 if (!reuseaddr)
694 return 0;
695 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
696 &on, sizeof(on));
699 #ifndef NO_IPV6
701 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
703 int socknum = 0, *socklist = NULL;
704 int maxfd = -1;
705 char pbuf[NI_MAXSERV];
706 struct addrinfo hints, *ai0, *ai;
707 int gai;
708 long flags;
710 sprintf(pbuf, "%d", listen_port);
711 memset(&hints, 0, sizeof(hints));
712 hints.ai_family = AF_UNSPEC;
713 hints.ai_socktype = SOCK_STREAM;
714 hints.ai_protocol = IPPROTO_TCP;
715 hints.ai_flags = AI_PASSIVE;
717 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
718 if (gai)
719 die("getaddrinfo() failed: %s", gai_strerror(gai));
721 for (ai = ai0; ai; ai = ai->ai_next) {
722 int sockfd;
724 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
725 if (sockfd < 0)
726 continue;
727 if (sockfd >= FD_SETSIZE) {
728 logerror("Socket descriptor too large");
729 close(sockfd);
730 continue;
733 #ifdef IPV6_V6ONLY
734 if (ai->ai_family == AF_INET6) {
735 int on = 1;
736 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
737 &on, sizeof(on));
738 /* Note: error is not fatal */
740 #endif
742 if (set_reuse_addr(sockfd)) {
743 close(sockfd);
744 continue;
747 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
748 close(sockfd);
749 continue; /* not fatal */
751 if (listen(sockfd, 5) < 0) {
752 close(sockfd);
753 continue; /* not fatal */
756 flags = fcntl(sockfd, F_GETFD, 0);
757 if (flags >= 0)
758 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
760 socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
761 socklist[socknum++] = sockfd;
763 if (maxfd < sockfd)
764 maxfd = sockfd;
767 freeaddrinfo(ai0);
769 *socklist_p = socklist;
770 return socknum;
773 #else /* NO_IPV6 */
775 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
777 struct sockaddr_in sin;
778 int sockfd;
779 long flags;
781 memset(&sin, 0, sizeof sin);
782 sin.sin_family = AF_INET;
783 sin.sin_port = htons(listen_port);
785 if (listen_addr) {
786 /* Well, host better be an IP address here. */
787 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
788 return 0;
789 } else {
790 sin.sin_addr.s_addr = htonl(INADDR_ANY);
793 sockfd = socket(AF_INET, SOCK_STREAM, 0);
794 if (sockfd < 0)
795 return 0;
797 if (set_reuse_addr(sockfd)) {
798 close(sockfd);
799 return 0;
802 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
803 close(sockfd);
804 return 0;
807 if (listen(sockfd, 5) < 0) {
808 close(sockfd);
809 return 0;
812 flags = fcntl(sockfd, F_GETFD, 0);
813 if (flags >= 0)
814 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
816 *socklist_p = xmalloc(sizeof(int));
817 **socklist_p = sockfd;
818 return 1;
821 #endif
823 static int service_loop(int socknum, int *socklist)
825 struct pollfd *pfd;
826 int i;
828 pfd = xcalloc(socknum, sizeof(struct pollfd));
830 for (i = 0; i < socknum; i++) {
831 pfd[i].fd = socklist[i];
832 pfd[i].events = POLLIN;
835 signal(SIGCHLD, child_handler);
837 for (;;) {
838 int i;
840 check_dead_children();
842 if (poll(pfd, socknum, -1) < 0) {
843 if (errno != EINTR) {
844 logerror("Poll failed, resuming: %s",
845 strerror(errno));
846 sleep(1);
848 continue;
851 for (i = 0; i < socknum; i++) {
852 if (pfd[i].revents & POLLIN) {
853 struct sockaddr_storage ss;
854 unsigned int sslen = sizeof(ss);
855 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
856 if (incoming < 0) {
857 switch (errno) {
858 case EAGAIN:
859 case EINTR:
860 case ECONNABORTED:
861 continue;
862 default:
863 die("accept returned %s", strerror(errno));
866 handle(incoming, (struct sockaddr *)&ss, sslen);
872 /* if any standard file descriptor is missing open it to /dev/null */
873 static void sanitize_stdfds(void)
875 int fd = open("/dev/null", O_RDWR, 0);
876 while (fd != -1 && fd < 2)
877 fd = dup(fd);
878 if (fd == -1)
879 die("open /dev/null or dup failed: %s", strerror(errno));
880 if (fd > 2)
881 close(fd);
884 static void daemonize(void)
886 switch (fork()) {
887 case 0:
888 break;
889 case -1:
890 die("fork failed: %s", strerror(errno));
891 default:
892 exit(0);
894 if (setsid() == -1)
895 die("setsid failed: %s", strerror(errno));
896 close(0);
897 close(1);
898 close(2);
899 sanitize_stdfds();
902 static void store_pid(const char *path)
904 FILE *f = fopen(path, "w");
905 if (!f)
906 die("cannot open pid file %s: %s", path, strerror(errno));
907 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
908 die("failed to write pid file %s: %s", path, strerror(errno));
911 static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
913 int socknum, *socklist;
915 socknum = socksetup(listen_addr, listen_port, &socklist);
916 if (socknum == 0)
917 die("unable to allocate any listen sockets on host %s port %u",
918 listen_addr, listen_port);
920 if (pass && gid &&
921 (initgroups(pass->pw_name, gid) || setgid (gid) ||
922 setuid(pass->pw_uid)))
923 die("cannot drop privileges");
925 return service_loop(socknum, socklist);
928 int main(int argc, char **argv)
930 int listen_port = 0;
931 char *listen_addr = NULL;
932 int inetd_mode = 0;
933 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
934 int detach = 0;
935 struct passwd *pass = NULL;
936 struct group *group;
937 gid_t gid = 0;
938 int i;
940 for (i = 1; i < argc; i++) {
941 char *arg = argv[i];
943 if (!prefixcmp(arg, "--listen=")) {
944 listen_addr = xstrdup_tolower(arg + 9);
945 continue;
947 if (!prefixcmp(arg, "--port=")) {
948 char *end;
949 unsigned long n;
950 n = strtoul(arg+7, &end, 0);
951 if (arg[7] && !*end) {
952 listen_port = n;
953 continue;
956 if (!strcmp(arg, "--inetd")) {
957 inetd_mode = 1;
958 log_syslog = 1;
959 continue;
961 if (!strcmp(arg, "--verbose")) {
962 verbose = 1;
963 continue;
965 if (!strcmp(arg, "--syslog")) {
966 log_syslog = 1;
967 continue;
969 if (!strcmp(arg, "--export-all")) {
970 export_all_trees = 1;
971 continue;
973 if (!prefixcmp(arg, "--timeout=")) {
974 timeout = atoi(arg+10);
975 continue;
977 if (!prefixcmp(arg, "--init-timeout=")) {
978 init_timeout = atoi(arg+15);
979 continue;
981 if (!prefixcmp(arg, "--max-connections=")) {
982 max_connections = atoi(arg+18);
983 if (max_connections < 0)
984 max_connections = 0; /* unlimited */
985 continue;
987 if (!strcmp(arg, "--strict-paths")) {
988 strict_paths = 1;
989 continue;
991 if (!prefixcmp(arg, "--base-path=")) {
992 base_path = arg+12;
993 continue;
995 if (!strcmp(arg, "--base-path-relaxed")) {
996 base_path_relaxed = 1;
997 continue;
999 if (!prefixcmp(arg, "--interpolated-path=")) {
1000 interpolated_path = arg+20;
1001 continue;
1003 if (!strcmp(arg, "--reuseaddr")) {
1004 reuseaddr = 1;
1005 continue;
1007 if (!strcmp(arg, "--user-path")) {
1008 user_path = "";
1009 continue;
1011 if (!prefixcmp(arg, "--user-path=")) {
1012 user_path = arg + 12;
1013 continue;
1015 if (!prefixcmp(arg, "--pid-file=")) {
1016 pid_file = arg + 11;
1017 continue;
1019 if (!strcmp(arg, "--detach")) {
1020 detach = 1;
1021 log_syslog = 1;
1022 continue;
1024 if (!prefixcmp(arg, "--user=")) {
1025 user_name = arg + 7;
1026 continue;
1028 if (!prefixcmp(arg, "--group=")) {
1029 group_name = arg + 8;
1030 continue;
1032 if (!prefixcmp(arg, "--enable=")) {
1033 enable_service(arg + 9, 1);
1034 continue;
1036 if (!prefixcmp(arg, "--disable=")) {
1037 enable_service(arg + 10, 0);
1038 continue;
1040 if (!prefixcmp(arg, "--allow-override=")) {
1041 make_service_overridable(arg + 17, 1);
1042 continue;
1044 if (!prefixcmp(arg, "--forbid-override=")) {
1045 make_service_overridable(arg + 18, 0);
1046 continue;
1048 if (!strcmp(arg, "--")) {
1049 ok_paths = &argv[i+1];
1050 break;
1051 } else if (arg[0] != '-') {
1052 ok_paths = &argv[i];
1053 break;
1056 usage(daemon_usage);
1059 if (log_syslog) {
1060 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1061 set_die_routine(daemon_die);
1062 } else
1063 /* avoid splitting a message in the middle */
1064 setvbuf(stderr, NULL, _IOLBF, 0);
1066 if (inetd_mode && (group_name || user_name))
1067 die("--user and --group are incompatible with --inetd");
1069 if (inetd_mode && (listen_port || listen_addr))
1070 die("--listen= and --port= are incompatible with --inetd");
1071 else if (listen_port == 0)
1072 listen_port = DEFAULT_GIT_PORT;
1074 if (group_name && !user_name)
1075 die("--group supplied without --user");
1077 if (user_name) {
1078 pass = getpwnam(user_name);
1079 if (!pass)
1080 die("user not found - %s", user_name);
1082 if (!group_name)
1083 gid = pass->pw_gid;
1084 else {
1085 group = getgrnam(group_name);
1086 if (!group)
1087 die("group not found - %s", group_name);
1089 gid = group->gr_gid;
1093 if (strict_paths && (!ok_paths || !*ok_paths))
1094 die("option --strict-paths requires a whitelist");
1096 if (base_path && !is_directory(base_path))
1097 die("base-path '%s' does not exist or is not a directory",
1098 base_path);
1100 if (inetd_mode) {
1101 struct sockaddr_storage ss;
1102 struct sockaddr *peer = (struct sockaddr *)&ss;
1103 socklen_t slen = sizeof(ss);
1105 if (!freopen("/dev/null", "w", stderr))
1106 die("failed to redirect stderr to /dev/null: %s",
1107 strerror(errno));
1109 if (getpeername(0, peer, &slen))
1110 peer = NULL;
1112 return execute(peer);
1115 if (detach) {
1116 daemonize();
1117 loginfo("Ready to rumble");
1119 else
1120 sanitize_stdfds();
1122 if (pid_file)
1123 store_pid(pid_file);
1125 return serve(listen_addr, listen_port, pass, gid);