git-compat-util.h: Provide missing netdb.h definitions
[git/jnareb-git.git] / daemon.c
blob34d95c1674930aa6ea429f7ee9173c239aae6bd5
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 #ifndef HOST_NAME_MAX
9 #define HOST_NAME_MAX 256
10 #endif
12 #ifdef NO_INITGROUPS
13 #define initgroups(x, y) (0) /* nothing */
14 #endif
16 static int log_syslog;
17 static int verbose;
18 static int reuseaddr;
19 static int informative_errors;
21 static const char daemon_usage[] =
22 "git daemon [--verbose] [--syslog] [--export-all]\n"
23 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
24 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
25 " [--user-path | --user-path=<path>]\n"
26 " [--interpolated-path=<path>]\n"
27 " [--reuseaddr] [--pid-file=<file>]\n"
28 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
29 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
30 " [--detach] [--user=<user> [--group=<group>]]\n"
31 " [<directory>...]";
33 /* List of acceptable pathname prefixes */
34 static char **ok_paths;
35 static int strict_paths;
37 /* If this is set, git-daemon-export-ok is not required */
38 static int export_all_trees;
40 /* Take all paths relative to this one if non-NULL */
41 static char *base_path;
42 static char *interpolated_path;
43 static int base_path_relaxed;
45 /* Flag indicating client sent extra args. */
46 static int saw_extended_args;
48 /* If defined, ~user notation is allowed and the string is inserted
49 * after ~user/. E.g. a request to git://host/~alice/frotz would
50 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
52 static const char *user_path;
54 /* Timeout, and initial timeout */
55 static unsigned int timeout;
56 static unsigned int init_timeout;
58 static char *hostname;
59 static char *canon_hostname;
60 static char *ip_address;
61 static char *tcp_port;
63 static void logreport(int priority, const char *err, va_list params)
65 if (log_syslog) {
66 char buf[1024];
67 vsnprintf(buf, sizeof(buf), err, params);
68 syslog(priority, "%s", buf);
69 } else {
71 * Since stderr is set to buffered mode, the
72 * logging of different processes will not overlap
73 * unless they overflow the (rather big) buffers.
75 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
76 vfprintf(stderr, err, params);
77 fputc('\n', stderr);
78 fflush(stderr);
82 __attribute__((format (printf, 1, 2)))
83 static void logerror(const char *err, ...)
85 va_list params;
86 va_start(params, err);
87 logreport(LOG_ERR, err, params);
88 va_end(params);
91 __attribute__((format (printf, 1, 2)))
92 static void loginfo(const char *err, ...)
94 va_list params;
95 if (!verbose)
96 return;
97 va_start(params, err);
98 logreport(LOG_INFO, err, params);
99 va_end(params);
102 static void NORETURN daemon_die(const char *err, va_list params)
104 logreport(LOG_ERR, err, params);
105 exit(1);
108 static const char *path_ok(char *directory)
110 static char rpath[PATH_MAX];
111 static char interp_path[PATH_MAX];
112 const char *path;
113 char *dir;
115 dir = directory;
117 if (daemon_avoid_alias(dir)) {
118 logerror("'%s': aliased", dir);
119 return NULL;
122 if (*dir == '~') {
123 if (!user_path) {
124 logerror("'%s': User-path not allowed", dir);
125 return NULL;
127 if (*user_path) {
128 /* Got either "~alice" or "~alice/foo";
129 * rewrite them to "~alice/%s" or
130 * "~alice/%s/foo".
132 int namlen, restlen = strlen(dir);
133 char *slash = strchr(dir, '/');
134 if (!slash)
135 slash = dir + restlen;
136 namlen = slash - dir;
137 restlen -= namlen;
138 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
139 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
140 namlen, dir, user_path, restlen, slash);
141 dir = rpath;
144 else if (interpolated_path && saw_extended_args) {
145 struct strbuf expanded_path = STRBUF_INIT;
146 struct strbuf_expand_dict_entry dict[6];
148 dict[0].placeholder = "H"; dict[0].value = hostname;
149 dict[1].placeholder = "CH"; dict[1].value = canon_hostname;
150 dict[2].placeholder = "IP"; dict[2].value = ip_address;
151 dict[3].placeholder = "P"; dict[3].value = tcp_port;
152 dict[4].placeholder = "D"; dict[4].value = directory;
153 dict[5].placeholder = NULL; dict[5].value = NULL;
154 if (*dir != '/') {
155 /* Allow only absolute */
156 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
157 return NULL;
160 strbuf_expand(&expanded_path, interpolated_path,
161 strbuf_expand_dict_cb, &dict);
162 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
163 strbuf_release(&expanded_path);
164 loginfo("Interpolated dir '%s'", interp_path);
166 dir = interp_path;
168 else if (base_path) {
169 if (*dir != '/') {
170 /* Allow only absolute */
171 logerror("'%s': Non-absolute path denied (base-path active)", dir);
172 return NULL;
174 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
175 dir = rpath;
178 path = enter_repo(dir, strict_paths);
179 if (!path && base_path && base_path_relaxed) {
181 * if we fail and base_path_relaxed is enabled, try without
182 * prefixing the base path
184 dir = directory;
185 path = enter_repo(dir, strict_paths);
188 if (!path) {
189 logerror("'%s' does not appear to be a git repository", dir);
190 return NULL;
193 if ( ok_paths && *ok_paths ) {
194 char **pp;
195 int pathlen = strlen(path);
197 /* The validation is done on the paths after enter_repo
198 * appends optional {.git,.git/.git} and friends, but
199 * it does not use getcwd(). So if your /pub is
200 * a symlink to /mnt/pub, you can whitelist /pub and
201 * do not have to say /mnt/pub.
202 * Do not say /pub/.
204 for ( pp = ok_paths ; *pp ; pp++ ) {
205 int len = strlen(*pp);
206 if (len <= pathlen &&
207 !memcmp(*pp, path, len) &&
208 (path[len] == '\0' ||
209 (!strict_paths && path[len] == '/')))
210 return path;
213 else {
214 /* be backwards compatible */
215 if (!strict_paths)
216 return path;
219 logerror("'%s': not in whitelist", path);
220 return NULL; /* Fallthrough. Deny by default */
223 typedef int (*daemon_service_fn)(void);
224 struct daemon_service {
225 const char *name;
226 const char *config_name;
227 daemon_service_fn fn;
228 int enabled;
229 int overridable;
232 static struct daemon_service *service_looking_at;
233 static int service_enabled;
235 static int git_daemon_config(const char *var, const char *value, void *cb)
237 if (!prefixcmp(var, "daemon.") &&
238 !strcmp(var + 7, service_looking_at->config_name)) {
239 service_enabled = git_config_bool(var, value);
240 return 0;
243 /* we are not interested in parsing any other configuration here */
244 return 0;
247 static int daemon_error(const char *dir, const char *msg)
249 if (!informative_errors)
250 msg = "access denied or repository not exported";
251 packet_write(1, "ERR %s: %s", msg, dir);
252 return -1;
255 static int run_service(char *dir, struct daemon_service *service)
257 const char *path;
258 int enabled = service->enabled;
260 loginfo("Request %s for '%s'", service->name, dir);
262 if (!enabled && !service->overridable) {
263 logerror("'%s': service not enabled.", service->name);
264 errno = EACCES;
265 return daemon_error(dir, "service not enabled");
268 if (!(path = path_ok(dir)))
269 return daemon_error(dir, "no such repository");
272 * Security on the cheap.
274 * We want a readable HEAD, usable "objects" directory, and
275 * a "git-daemon-export-ok" flag that says that the other side
276 * is ok with us doing this.
278 * path_ok() uses enter_repo() and does whitelist checking.
279 * We only need to make sure the repository is exported.
282 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
283 logerror("'%s': repository not exported.", path);
284 errno = EACCES;
285 return daemon_error(dir, "repository not exported");
288 if (service->overridable) {
289 service_looking_at = service;
290 service_enabled = -1;
291 git_config(git_daemon_config, NULL);
292 if (0 <= service_enabled)
293 enabled = service_enabled;
295 if (!enabled) {
296 logerror("'%s': service not enabled for '%s'",
297 service->name, path);
298 errno = EACCES;
299 return daemon_error(dir, "service not enabled");
303 * We'll ignore SIGTERM from now on, we have a
304 * good client.
306 signal(SIGTERM, SIG_IGN);
308 return service->fn();
311 static void copy_to_log(int fd)
313 struct strbuf line = STRBUF_INIT;
314 FILE *fp;
316 fp = fdopen(fd, "r");
317 if (fp == NULL) {
318 logerror("fdopen of error channel failed");
319 close(fd);
320 return;
323 while (strbuf_getline(&line, fp, '\n') != EOF) {
324 logerror("%s", line.buf);
325 strbuf_setlen(&line, 0);
328 strbuf_release(&line);
329 fclose(fp);
332 static int run_service_command(const char **argv)
334 struct child_process cld;
336 memset(&cld, 0, sizeof(cld));
337 cld.argv = argv;
338 cld.git_cmd = 1;
339 cld.err = -1;
340 if (start_command(&cld))
341 return -1;
343 close(0);
344 close(1);
346 copy_to_log(cld.err);
348 return finish_command(&cld);
351 static int upload_pack(void)
353 /* Timeout as string */
354 char timeout_buf[64];
355 const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
357 argv[2] = timeout_buf;
359 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
360 return run_service_command(argv);
363 static int upload_archive(void)
365 static const char *argv[] = { "upload-archive", ".", NULL };
366 return run_service_command(argv);
369 static int receive_pack(void)
371 static const char *argv[] = { "receive-pack", ".", NULL };
372 return run_service_command(argv);
375 static struct daemon_service daemon_service[] = {
376 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
377 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
378 { "receive-pack", "receivepack", receive_pack, 0, 1 },
381 static void enable_service(const char *name, int ena)
383 int i;
384 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
385 if (!strcmp(daemon_service[i].name, name)) {
386 daemon_service[i].enabled = ena;
387 return;
390 die("No such service %s", name);
393 static void make_service_overridable(const char *name, int ena)
395 int i;
396 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
397 if (!strcmp(daemon_service[i].name, name)) {
398 daemon_service[i].overridable = ena;
399 return;
402 die("No such service %s", name);
405 static char *xstrdup_tolower(const char *str)
407 char *p, *dup = xstrdup(str);
408 for (p = dup; *p; p++)
409 *p = tolower(*p);
410 return dup;
413 static void parse_host_and_port(char *hostport, char **host,
414 char **port)
416 if (*hostport == '[') {
417 char *end;
419 end = strchr(hostport, ']');
420 if (!end)
421 die("Invalid request ('[' without ']')");
422 *end = '\0';
423 *host = hostport + 1;
424 if (!end[1])
425 *port = NULL;
426 else if (end[1] == ':')
427 *port = end + 2;
428 else
429 die("Garbage after end of host part");
430 } else {
431 *host = hostport;
432 *port = strrchr(hostport, ':');
433 if (*port) {
434 **port = '\0';
435 ++*port;
441 * Read the host as supplied by the client connection.
443 static void parse_host_arg(char *extra_args, int buflen)
445 char *val;
446 int vallen;
447 char *end = extra_args + buflen;
449 if (extra_args < end && *extra_args) {
450 saw_extended_args = 1;
451 if (strncasecmp("host=", extra_args, 5) == 0) {
452 val = extra_args + 5;
453 vallen = strlen(val) + 1;
454 if (*val) {
455 /* Split <host>:<port> at colon. */
456 char *host;
457 char *port;
458 parse_host_and_port(val, &host, &port);
459 if (port) {
460 free(tcp_port);
461 tcp_port = xstrdup(port);
463 free(hostname);
464 hostname = xstrdup_tolower(host);
467 /* On to the next one */
468 extra_args = val + vallen;
470 if (extra_args < end && *extra_args)
471 die("Invalid request");
475 * Locate canonical hostname and its IP address.
477 if (hostname) {
478 #ifndef NO_IPV6
479 struct addrinfo hints;
480 struct addrinfo *ai;
481 int gai;
482 static char addrbuf[HOST_NAME_MAX + 1];
484 memset(&hints, 0, sizeof(hints));
485 hints.ai_flags = AI_CANONNAME;
487 gai = getaddrinfo(hostname, NULL, &hints, &ai);
488 if (!gai) {
489 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
491 inet_ntop(AF_INET, &sin_addr->sin_addr,
492 addrbuf, sizeof(addrbuf));
493 free(ip_address);
494 ip_address = xstrdup(addrbuf);
496 free(canon_hostname);
497 canon_hostname = xstrdup(ai->ai_canonname ?
498 ai->ai_canonname : ip_address);
500 freeaddrinfo(ai);
502 #else
503 struct hostent *hent;
504 struct sockaddr_in sa;
505 char **ap;
506 static char addrbuf[HOST_NAME_MAX + 1];
508 hent = gethostbyname(hostname);
510 ap = hent->h_addr_list;
511 memset(&sa, 0, sizeof sa);
512 sa.sin_family = hent->h_addrtype;
513 sa.sin_port = htons(0);
514 memcpy(&sa.sin_addr, *ap, hent->h_length);
516 inet_ntop(hent->h_addrtype, &sa.sin_addr,
517 addrbuf, sizeof(addrbuf));
519 free(canon_hostname);
520 canon_hostname = xstrdup(hent->h_name);
521 free(ip_address);
522 ip_address = xstrdup(addrbuf);
523 #endif
528 static int execute(void)
530 static char line[1000];
531 int pktlen, len, i;
532 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
534 if (addr)
535 loginfo("Connection from %s:%s", addr, port);
537 alarm(init_timeout ? init_timeout : timeout);
538 pktlen = packet_read_line(0, line, sizeof(line));
539 alarm(0);
541 len = strlen(line);
542 if (pktlen != len)
543 loginfo("Extended attributes (%d bytes) exist <%.*s>",
544 (int) pktlen - len,
545 (int) pktlen - len, line + len + 1);
546 if (len && line[len-1] == '\n') {
547 line[--len] = 0;
548 pktlen--;
551 free(hostname);
552 free(canon_hostname);
553 free(ip_address);
554 free(tcp_port);
555 hostname = canon_hostname = ip_address = tcp_port = NULL;
557 if (len != pktlen)
558 parse_host_arg(line + len + 1, pktlen - len - 1);
560 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
561 struct daemon_service *s = &(daemon_service[i]);
562 int namelen = strlen(s->name);
563 if (!prefixcmp(line, "git-") &&
564 !strncmp(s->name, line + 4, namelen) &&
565 line[namelen + 4] == ' ') {
567 * Note: The directory here is probably context sensitive,
568 * and might depend on the actual service being performed.
570 return run_service(line + namelen + 5, s);
574 logerror("Protocol error: '%s'", line);
575 return -1;
578 static int addrcmp(const struct sockaddr_storage *s1,
579 const struct sockaddr_storage *s2)
581 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
582 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
584 if (sa1->sa_family != sa2->sa_family)
585 return sa1->sa_family - sa2->sa_family;
586 if (sa1->sa_family == AF_INET)
587 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
588 &((struct sockaddr_in *)s2)->sin_addr,
589 sizeof(struct in_addr));
590 #ifndef NO_IPV6
591 if (sa1->sa_family == AF_INET6)
592 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
593 &((struct sockaddr_in6 *)s2)->sin6_addr,
594 sizeof(struct in6_addr));
595 #endif
596 return 0;
599 static int max_connections = 32;
601 static unsigned int live_children;
603 static struct child {
604 struct child *next;
605 struct child_process cld;
606 struct sockaddr_storage address;
607 } *firstborn;
609 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
611 struct child *newborn, **cradle;
613 newborn = xcalloc(1, sizeof(*newborn));
614 live_children++;
615 memcpy(&newborn->cld, cld, sizeof(*cld));
616 memcpy(&newborn->address, addr, addrlen);
617 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
618 if (!addrcmp(&(*cradle)->address, &newborn->address))
619 break;
620 newborn->next = *cradle;
621 *cradle = newborn;
625 * This gets called if the number of connections grows
626 * past "max_connections".
628 * We kill the newest connection from a duplicate IP.
630 static void kill_some_child(void)
632 const struct child *blanket, *next;
634 if (!(blanket = firstborn))
635 return;
637 for (; (next = blanket->next); blanket = next)
638 if (!addrcmp(&blanket->address, &next->address)) {
639 kill(blanket->cld.pid, SIGTERM);
640 break;
644 static void check_dead_children(void)
646 int status;
647 pid_t pid;
649 struct child **cradle, *blanket;
650 for (cradle = &firstborn; (blanket = *cradle);)
651 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
652 const char *dead = "";
653 if (status)
654 dead = " (with error)";
655 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
657 /* remove the child */
658 *cradle = blanket->next;
659 live_children--;
660 free(blanket);
661 } else
662 cradle = &blanket->next;
665 static char **cld_argv;
666 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
668 struct child_process cld = { NULL };
669 char addrbuf[300] = "REMOTE_ADDR=", portbuf[300];
670 char *env[] = { addrbuf, portbuf, NULL };
672 if (max_connections && live_children >= max_connections) {
673 kill_some_child();
674 sleep(1); /* give it some time to die */
675 check_dead_children();
676 if (live_children >= max_connections) {
677 close(incoming);
678 logerror("Too many children, dropping connection");
679 return;
683 if (addr->sa_family == AF_INET) {
684 struct sockaddr_in *sin_addr = (void *) addr;
685 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf + 12,
686 sizeof(addrbuf) - 12);
687 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
688 ntohs(sin_addr->sin_port));
689 #ifndef NO_IPV6
690 } else if (addr && addr->sa_family == AF_INET6) {
691 struct sockaddr_in6 *sin6_addr = (void *) addr;
693 char *buf = addrbuf + 12;
694 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
695 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf,
696 sizeof(addrbuf) - 13);
697 strcat(buf, "]");
699 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
700 ntohs(sin6_addr->sin6_port));
701 #endif
704 cld.env = (const char **)env;
705 cld.argv = (const char **)cld_argv;
706 cld.in = incoming;
707 cld.out = dup(incoming);
709 if (start_command(&cld))
710 logerror("unable to fork");
711 else
712 add_child(&cld, addr, addrlen);
713 close(incoming);
716 static void child_handler(int signo)
719 * Otherwise empty handler because systemcalls will get interrupted
720 * upon signal receipt
721 * SysV needs the handler to be rearmed
723 signal(SIGCHLD, child_handler);
726 static int set_reuse_addr(int sockfd)
728 int on = 1;
730 if (!reuseaddr)
731 return 0;
732 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
733 &on, sizeof(on));
736 struct socketlist {
737 int *list;
738 size_t nr;
739 size_t alloc;
742 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
744 #ifdef NO_IPV6
745 static char ip[INET_ADDRSTRLEN];
746 #else
747 static char ip[INET6_ADDRSTRLEN];
748 #endif
750 switch (family) {
751 #ifndef NO_IPV6
752 case AF_INET6:
753 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
754 break;
755 #endif
756 case AF_INET:
757 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
758 break;
759 default:
760 strcpy(ip, "<unknown>");
762 return ip;
765 #ifndef NO_IPV6
767 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
769 int socknum = 0;
770 int maxfd = -1;
771 char pbuf[NI_MAXSERV];
772 struct addrinfo hints, *ai0, *ai;
773 int gai;
774 long flags;
776 sprintf(pbuf, "%d", listen_port);
777 memset(&hints, 0, sizeof(hints));
778 hints.ai_family = AF_UNSPEC;
779 hints.ai_socktype = SOCK_STREAM;
780 hints.ai_protocol = IPPROTO_TCP;
781 hints.ai_flags = AI_PASSIVE;
783 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
784 if (gai) {
785 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
786 return 0;
789 for (ai = ai0; ai; ai = ai->ai_next) {
790 int sockfd;
792 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
793 if (sockfd < 0)
794 continue;
795 if (sockfd >= FD_SETSIZE) {
796 logerror("Socket descriptor too large");
797 close(sockfd);
798 continue;
801 #ifdef IPV6_V6ONLY
802 if (ai->ai_family == AF_INET6) {
803 int on = 1;
804 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
805 &on, sizeof(on));
806 /* Note: error is not fatal */
808 #endif
810 if (set_reuse_addr(sockfd)) {
811 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
812 close(sockfd);
813 continue;
816 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
817 logerror("Could not bind to %s: %s",
818 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
819 strerror(errno));
820 close(sockfd);
821 continue; /* not fatal */
823 if (listen(sockfd, 5) < 0) {
824 logerror("Could not listen to %s: %s",
825 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
826 strerror(errno));
827 close(sockfd);
828 continue; /* not fatal */
831 flags = fcntl(sockfd, F_GETFD, 0);
832 if (flags >= 0)
833 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
835 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
836 socklist->list[socklist->nr++] = sockfd;
837 socknum++;
839 if (maxfd < sockfd)
840 maxfd = sockfd;
843 freeaddrinfo(ai0);
845 return socknum;
848 #else /* NO_IPV6 */
850 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
852 struct sockaddr_in sin;
853 int sockfd;
854 long flags;
856 memset(&sin, 0, sizeof sin);
857 sin.sin_family = AF_INET;
858 sin.sin_port = htons(listen_port);
860 if (listen_addr) {
861 /* Well, host better be an IP address here. */
862 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
863 return 0;
864 } else {
865 sin.sin_addr.s_addr = htonl(INADDR_ANY);
868 sockfd = socket(AF_INET, SOCK_STREAM, 0);
869 if (sockfd < 0)
870 return 0;
872 if (set_reuse_addr(sockfd)) {
873 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
874 close(sockfd);
875 return 0;
878 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
879 logerror("Could not listen to %s: %s",
880 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
881 strerror(errno));
882 close(sockfd);
883 return 0;
886 if (listen(sockfd, 5) < 0) {
887 logerror("Could not listen to %s: %s",
888 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
889 strerror(errno));
890 close(sockfd);
891 return 0;
894 flags = fcntl(sockfd, F_GETFD, 0);
895 if (flags >= 0)
896 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
898 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
899 socklist->list[socklist->nr++] = sockfd;
900 return 1;
903 #endif
905 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
907 if (!listen_addr->nr)
908 setup_named_sock(NULL, listen_port, socklist);
909 else {
910 int i, socknum;
911 for (i = 0; i < listen_addr->nr; i++) {
912 socknum = setup_named_sock(listen_addr->items[i].string,
913 listen_port, socklist);
915 if (socknum == 0)
916 logerror("unable to allocate any listen sockets for host %s on port %u",
917 listen_addr->items[i].string, listen_port);
922 static int service_loop(struct socketlist *socklist)
924 struct pollfd *pfd;
925 int i;
927 pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
929 for (i = 0; i < socklist->nr; i++) {
930 pfd[i].fd = socklist->list[i];
931 pfd[i].events = POLLIN;
934 signal(SIGCHLD, child_handler);
936 for (;;) {
937 int i;
939 check_dead_children();
941 if (poll(pfd, socklist->nr, -1) < 0) {
942 if (errno != EINTR) {
943 logerror("Poll failed, resuming: %s",
944 strerror(errno));
945 sleep(1);
947 continue;
950 for (i = 0; i < socklist->nr; i++) {
951 if (pfd[i].revents & POLLIN) {
952 union {
953 struct sockaddr sa;
954 struct sockaddr_in sai;
955 #ifndef NO_IPV6
956 struct sockaddr_in6 sai6;
957 #endif
958 } ss;
959 socklen_t sslen = sizeof(ss);
960 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
961 if (incoming < 0) {
962 switch (errno) {
963 case EAGAIN:
964 case EINTR:
965 case ECONNABORTED:
966 continue;
967 default:
968 die_errno("accept returned");
971 handle(incoming, &ss.sa, sslen);
977 /* if any standard file descriptor is missing open it to /dev/null */
978 static void sanitize_stdfds(void)
980 int fd = open("/dev/null", O_RDWR, 0);
981 while (fd != -1 && fd < 2)
982 fd = dup(fd);
983 if (fd == -1)
984 die_errno("open /dev/null or dup failed");
985 if (fd > 2)
986 close(fd);
989 #ifdef NO_POSIX_GOODIES
991 struct credentials;
993 static void drop_privileges(struct credentials *cred)
995 /* nothing */
998 static void daemonize(void)
1000 die("--detach not supported on this platform");
1003 static struct credentials *prepare_credentials(const char *user_name,
1004 const char *group_name)
1006 die("--user not supported on this platform");
1009 #else
1011 struct credentials {
1012 struct passwd *pass;
1013 gid_t gid;
1016 static void drop_privileges(struct credentials *cred)
1018 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1019 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1020 die("cannot drop privileges");
1023 static struct credentials *prepare_credentials(const char *user_name,
1024 const char *group_name)
1026 static struct credentials c;
1028 c.pass = getpwnam(user_name);
1029 if (!c.pass)
1030 die("user not found - %s", user_name);
1032 if (!group_name)
1033 c.gid = c.pass->pw_gid;
1034 else {
1035 struct group *group = getgrnam(group_name);
1036 if (!group)
1037 die("group not found - %s", group_name);
1039 c.gid = group->gr_gid;
1042 return &c;
1045 static void daemonize(void)
1047 switch (fork()) {
1048 case 0:
1049 break;
1050 case -1:
1051 die_errno("fork failed");
1052 default:
1053 exit(0);
1055 if (setsid() == -1)
1056 die_errno("setsid failed");
1057 close(0);
1058 close(1);
1059 close(2);
1060 sanitize_stdfds();
1062 #endif
1064 static void store_pid(const char *path)
1066 FILE *f = fopen(path, "w");
1067 if (!f)
1068 die_errno("cannot open pid file '%s'", path);
1069 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
1070 die_errno("failed to write pid file '%s'", path);
1073 static int serve(struct string_list *listen_addr, int listen_port,
1074 struct credentials *cred)
1076 struct socketlist socklist = { NULL, 0, 0 };
1078 socksetup(listen_addr, listen_port, &socklist);
1079 if (socklist.nr == 0)
1080 die("unable to allocate any listen sockets on port %u",
1081 listen_port);
1083 drop_privileges(cred);
1085 loginfo("Ready to rumble");
1087 return service_loop(&socklist);
1090 int main(int argc, char **argv)
1092 int listen_port = 0;
1093 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1094 int serve_mode = 0, inetd_mode = 0;
1095 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1096 int detach = 0;
1097 struct credentials *cred = NULL;
1098 int i;
1100 git_setup_gettext();
1102 git_extract_argv0_path(argv[0]);
1104 for (i = 1; i < argc; i++) {
1105 char *arg = argv[i];
1107 if (!prefixcmp(arg, "--listen=")) {
1108 string_list_append(&listen_addr, xstrdup_tolower(arg + 9));
1109 continue;
1111 if (!prefixcmp(arg, "--port=")) {
1112 char *end;
1113 unsigned long n;
1114 n = strtoul(arg+7, &end, 0);
1115 if (arg[7] && !*end) {
1116 listen_port = n;
1117 continue;
1120 if (!strcmp(arg, "--serve")) {
1121 serve_mode = 1;
1122 continue;
1124 if (!strcmp(arg, "--inetd")) {
1125 inetd_mode = 1;
1126 log_syslog = 1;
1127 continue;
1129 if (!strcmp(arg, "--verbose")) {
1130 verbose = 1;
1131 continue;
1133 if (!strcmp(arg, "--syslog")) {
1134 log_syslog = 1;
1135 continue;
1137 if (!strcmp(arg, "--export-all")) {
1138 export_all_trees = 1;
1139 continue;
1141 if (!prefixcmp(arg, "--timeout=")) {
1142 timeout = atoi(arg+10);
1143 continue;
1145 if (!prefixcmp(arg, "--init-timeout=")) {
1146 init_timeout = atoi(arg+15);
1147 continue;
1149 if (!prefixcmp(arg, "--max-connections=")) {
1150 max_connections = atoi(arg+18);
1151 if (max_connections < 0)
1152 max_connections = 0; /* unlimited */
1153 continue;
1155 if (!strcmp(arg, "--strict-paths")) {
1156 strict_paths = 1;
1157 continue;
1159 if (!prefixcmp(arg, "--base-path=")) {
1160 base_path = arg+12;
1161 continue;
1163 if (!strcmp(arg, "--base-path-relaxed")) {
1164 base_path_relaxed = 1;
1165 continue;
1167 if (!prefixcmp(arg, "--interpolated-path=")) {
1168 interpolated_path = arg+20;
1169 continue;
1171 if (!strcmp(arg, "--reuseaddr")) {
1172 reuseaddr = 1;
1173 continue;
1175 if (!strcmp(arg, "--user-path")) {
1176 user_path = "";
1177 continue;
1179 if (!prefixcmp(arg, "--user-path=")) {
1180 user_path = arg + 12;
1181 continue;
1183 if (!prefixcmp(arg, "--pid-file=")) {
1184 pid_file = arg + 11;
1185 continue;
1187 if (!strcmp(arg, "--detach")) {
1188 detach = 1;
1189 log_syslog = 1;
1190 continue;
1192 if (!prefixcmp(arg, "--user=")) {
1193 user_name = arg + 7;
1194 continue;
1196 if (!prefixcmp(arg, "--group=")) {
1197 group_name = arg + 8;
1198 continue;
1200 if (!prefixcmp(arg, "--enable=")) {
1201 enable_service(arg + 9, 1);
1202 continue;
1204 if (!prefixcmp(arg, "--disable=")) {
1205 enable_service(arg + 10, 0);
1206 continue;
1208 if (!prefixcmp(arg, "--allow-override=")) {
1209 make_service_overridable(arg + 17, 1);
1210 continue;
1212 if (!prefixcmp(arg, "--forbid-override=")) {
1213 make_service_overridable(arg + 18, 0);
1214 continue;
1216 if (!prefixcmp(arg, "--informative-errors")) {
1217 informative_errors = 1;
1218 continue;
1220 if (!prefixcmp(arg, "--no-informative-errors")) {
1221 informative_errors = 0;
1222 continue;
1224 if (!strcmp(arg, "--")) {
1225 ok_paths = &argv[i+1];
1226 break;
1227 } else if (arg[0] != '-') {
1228 ok_paths = &argv[i];
1229 break;
1232 usage(daemon_usage);
1235 if (log_syslog) {
1236 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1237 set_die_routine(daemon_die);
1238 } else
1239 /* avoid splitting a message in the middle */
1240 setvbuf(stderr, NULL, _IOFBF, 4096);
1242 if (inetd_mode && (detach || group_name || user_name))
1243 die("--detach, --user and --group are incompatible with --inetd");
1245 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1246 die("--listen= and --port= are incompatible with --inetd");
1247 else if (listen_port == 0)
1248 listen_port = DEFAULT_GIT_PORT;
1250 if (group_name && !user_name)
1251 die("--group supplied without --user");
1253 if (user_name)
1254 cred = prepare_credentials(user_name, group_name);
1256 if (strict_paths && (!ok_paths || !*ok_paths))
1257 die("option --strict-paths requires a whitelist");
1259 if (base_path && !is_directory(base_path))
1260 die("base-path '%s' does not exist or is not a directory",
1261 base_path);
1263 if (inetd_mode) {
1264 if (!freopen("/dev/null", "w", stderr))
1265 die_errno("failed to redirect stderr to /dev/null");
1268 if (inetd_mode || serve_mode)
1269 return execute();
1271 if (detach)
1272 daemonize();
1273 else
1274 sanitize_stdfds();
1276 if (pid_file)
1277 store_pid(pid_file);
1279 /* prepare argv for serving-processes */
1280 cld_argv = xmalloc(sizeof (char *) * (argc + 2));
1281 cld_argv[0] = argv[0]; /* git-daemon */
1282 cld_argv[1] = "--serve";
1283 for (i = 1; i < argc; ++i)
1284 cld_argv[i+1] = argv[i];
1285 cld_argv[argc+1] = NULL;
1287 return serve(&listen_addr, listen_port, cred);