config.c: trivial fix for compile-time warning
[git/dscho.git] / daemon.c
blobfa283003ea8809a2defc63f3b36cebe135028ddb
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 #ifndef NI_MAXSERV
13 #define NI_MAXSERV 32
14 #endif
16 #ifdef NO_INITGROUPS
17 #define initgroups(x, y) (0) /* nothing */
18 #endif
20 static int log_syslog;
21 static int verbose;
22 static int reuseaddr;
23 static int informative_errors;
25 static const char daemon_usage[] =
26 "git daemon [--verbose] [--syslog] [--export-all]\n"
27 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
28 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
29 " [--user-path | --user-path=<path>]\n"
30 " [--interpolated-path=<path>]\n"
31 " [--reuseaddr] [--pid-file=<file>]\n"
32 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
33 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
34 " [--detach] [--user=<user> [--group=<group>]]\n"
35 " [<directory>...]";
37 /* List of acceptable pathname prefixes */
38 static char **ok_paths;
39 static int strict_paths;
41 /* If this is set, git-daemon-export-ok is not required */
42 static int export_all_trees;
44 /* Take all paths relative to this one if non-NULL */
45 static char *base_path;
46 static char *interpolated_path;
47 static int base_path_relaxed;
49 /* Flag indicating client sent extra args. */
50 static int saw_extended_args;
52 /* If defined, ~user notation is allowed and the string is inserted
53 * after ~user/. E.g. a request to git://host/~alice/frotz would
54 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
56 static const char *user_path;
58 /* Timeout, and initial timeout */
59 static unsigned int timeout;
60 static unsigned int init_timeout;
62 static char *hostname;
63 static char *canon_hostname;
64 static char *ip_address;
65 static char *tcp_port;
67 static void logreport(int priority, const char *err, va_list params)
69 if (log_syslog) {
70 char buf[1024];
71 vsnprintf(buf, sizeof(buf), err, params);
72 syslog(priority, "%s", buf);
73 } else {
75 * Since stderr is set to buffered mode, the
76 * logging of different processes will not overlap
77 * unless they overflow the (rather big) buffers.
79 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
80 vfprintf(stderr, err, params);
81 fputc('\n', stderr);
82 fflush(stderr);
86 __attribute__((format (printf, 1, 2)))
87 static void logerror(const char *err, ...)
89 va_list params;
90 va_start(params, err);
91 logreport(LOG_ERR, err, params);
92 va_end(params);
95 __attribute__((format (printf, 1, 2)))
96 static void loginfo(const char *err, ...)
98 va_list params;
99 if (!verbose)
100 return;
101 va_start(params, err);
102 logreport(LOG_INFO, err, params);
103 va_end(params);
106 static void NORETURN daemon_die(const char *err, va_list params)
108 logreport(LOG_ERR, err, params);
109 exit(1);
112 static const char *path_ok(char *directory)
114 static char rpath[PATH_MAX];
115 static char interp_path[PATH_MAX];
116 const char *path;
117 char *dir;
119 dir = directory;
121 if (daemon_avoid_alias(dir)) {
122 logerror("'%s': aliased", dir);
123 return NULL;
126 if (*dir == '~') {
127 if (!user_path) {
128 logerror("'%s': User-path not allowed", dir);
129 return NULL;
131 if (*user_path) {
132 /* Got either "~alice" or "~alice/foo";
133 * rewrite them to "~alice/%s" or
134 * "~alice/%s/foo".
136 int namlen, restlen = strlen(dir);
137 char *slash = strchr(dir, '/');
138 if (!slash)
139 slash = dir + restlen;
140 namlen = slash - dir;
141 restlen -= namlen;
142 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
143 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
144 namlen, dir, user_path, restlen, slash);
145 dir = rpath;
148 else if (interpolated_path && saw_extended_args) {
149 struct strbuf expanded_path = STRBUF_INIT;
150 struct strbuf_expand_dict_entry dict[6];
152 dict[0].placeholder = "H"; dict[0].value = hostname;
153 dict[1].placeholder = "CH"; dict[1].value = canon_hostname;
154 dict[2].placeholder = "IP"; dict[2].value = ip_address;
155 dict[3].placeholder = "P"; dict[3].value = tcp_port;
156 dict[4].placeholder = "D"; dict[4].value = directory;
157 dict[5].placeholder = NULL; dict[5].value = NULL;
158 if (*dir != '/') {
159 /* Allow only absolute */
160 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
161 return NULL;
164 strbuf_expand(&expanded_path, interpolated_path,
165 strbuf_expand_dict_cb, &dict);
166 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
167 strbuf_release(&expanded_path);
168 loginfo("Interpolated dir '%s'", interp_path);
170 dir = interp_path;
172 else if (base_path) {
173 if (*dir != '/') {
174 /* Allow only absolute */
175 logerror("'%s': Non-absolute path denied (base-path active)", dir);
176 return NULL;
178 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
179 dir = rpath;
182 path = enter_repo(dir, strict_paths);
183 if (!path && base_path && base_path_relaxed) {
185 * if we fail and base_path_relaxed is enabled, try without
186 * prefixing the base path
188 dir = directory;
189 path = enter_repo(dir, strict_paths);
192 if (!path) {
193 logerror("'%s' does not appear to be a git repository", dir);
194 return NULL;
197 if ( ok_paths && *ok_paths ) {
198 char **pp;
199 int pathlen = strlen(path);
201 /* The validation is done on the paths after enter_repo
202 * appends optional {.git,.git/.git} and friends, but
203 * it does not use getcwd(). So if your /pub is
204 * a symlink to /mnt/pub, you can whitelist /pub and
205 * do not have to say /mnt/pub.
206 * Do not say /pub/.
208 for ( pp = ok_paths ; *pp ; pp++ ) {
209 int len = strlen(*pp);
210 if (len <= pathlen &&
211 !memcmp(*pp, path, len) &&
212 (path[len] == '\0' ||
213 (!strict_paths && path[len] == '/')))
214 return path;
217 else {
218 /* be backwards compatible */
219 if (!strict_paths)
220 return path;
223 logerror("'%s': not in whitelist", path);
224 return NULL; /* Fallthrough. Deny by default */
227 typedef int (*daemon_service_fn)(void);
228 struct daemon_service {
229 const char *name;
230 const char *config_name;
231 daemon_service_fn fn;
232 int enabled;
233 int overridable;
236 static struct daemon_service *service_looking_at;
237 static int service_enabled;
239 static int git_daemon_config(const char *var, const char *value, void *cb)
241 if (!prefixcmp(var, "daemon.") &&
242 !strcmp(var + 7, service_looking_at->config_name)) {
243 service_enabled = git_config_bool(var, value);
244 return 0;
247 /* we are not interested in parsing any other configuration here */
248 return 0;
251 static int daemon_error(const char *dir, const char *msg)
253 if (!informative_errors)
254 msg = "access denied or repository not exported";
255 packet_write(1, "ERR %s: %s", msg, dir);
256 return -1;
259 static int run_service(char *dir, struct daemon_service *service)
261 const char *path;
262 int enabled = service->enabled;
264 loginfo("Request %s for '%s'", service->name, dir);
266 if (!enabled && !service->overridable) {
267 logerror("'%s': service not enabled.", service->name);
268 errno = EACCES;
269 return daemon_error(dir, "service not enabled");
272 if (!(path = path_ok(dir)))
273 return daemon_error(dir, "no such repository");
276 * Security on the cheap.
278 * We want a readable HEAD, usable "objects" directory, and
279 * a "git-daemon-export-ok" flag that says that the other side
280 * is ok with us doing this.
282 * path_ok() uses enter_repo() and does whitelist checking.
283 * We only need to make sure the repository is exported.
286 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
287 logerror("'%s': repository not exported.", path);
288 errno = EACCES;
289 return daemon_error(dir, "repository not exported");
292 if (service->overridable) {
293 service_looking_at = service;
294 service_enabled = -1;
295 git_config(git_daemon_config, NULL);
296 if (0 <= service_enabled)
297 enabled = service_enabled;
299 if (!enabled) {
300 logerror("'%s': service not enabled for '%s'",
301 service->name, path);
302 errno = EACCES;
303 return daemon_error(dir, "service not enabled");
307 * We'll ignore SIGTERM from now on, we have a
308 * good client.
310 signal(SIGTERM, SIG_IGN);
312 return service->fn();
315 static void copy_to_log(int fd)
317 struct strbuf line = STRBUF_INIT;
318 FILE *fp;
320 fp = fdopen(fd, "r");
321 if (fp == NULL) {
322 logerror("fdopen of error channel failed");
323 close(fd);
324 return;
327 while (strbuf_getline(&line, fp, '\n') != EOF) {
328 logerror("%s", line.buf);
329 strbuf_setlen(&line, 0);
332 strbuf_release(&line);
333 fclose(fp);
336 static int run_service_command(const char **argv)
338 struct child_process cld;
340 memset(&cld, 0, sizeof(cld));
341 cld.argv = argv;
342 cld.git_cmd = 1;
343 cld.err = -1;
344 if (start_command(&cld))
345 return -1;
347 close(0);
348 close(1);
350 copy_to_log(cld.err);
352 return finish_command(&cld);
355 static int upload_pack(void)
357 /* Timeout as string */
358 char timeout_buf[64];
359 const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
361 argv[2] = timeout_buf;
363 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
364 return run_service_command(argv);
367 static int upload_archive(void)
369 static const char *argv[] = { "upload-archive", ".", NULL };
370 return run_service_command(argv);
373 static int receive_pack(void)
375 static const char *argv[] = { "receive-pack", ".", NULL };
376 return run_service_command(argv);
379 static struct daemon_service daemon_service[] = {
380 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
381 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
382 { "receive-pack", "receivepack", receive_pack, 0, 1 },
385 static void enable_service(const char *name, int ena)
387 int i;
388 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
389 if (!strcmp(daemon_service[i].name, name)) {
390 daemon_service[i].enabled = ena;
391 return;
394 die("No such service %s", name);
397 static void make_service_overridable(const char *name, int ena)
399 int i;
400 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
401 if (!strcmp(daemon_service[i].name, name)) {
402 daemon_service[i].overridable = ena;
403 return;
406 die("No such service %s", name);
409 static char *xstrdup_tolower(const char *str)
411 char *p, *dup = xstrdup(str);
412 for (p = dup; *p; p++)
413 *p = tolower(*p);
414 return dup;
417 static void parse_host_and_port(char *hostport, char **host,
418 char **port)
420 if (*hostport == '[') {
421 char *end;
423 end = strchr(hostport, ']');
424 if (!end)
425 die("Invalid request ('[' without ']')");
426 *end = '\0';
427 *host = hostport + 1;
428 if (!end[1])
429 *port = NULL;
430 else if (end[1] == ':')
431 *port = end + 2;
432 else
433 die("Garbage after end of host part");
434 } else {
435 *host = hostport;
436 *port = strrchr(hostport, ':');
437 if (*port) {
438 **port = '\0';
439 ++*port;
445 * Read the host as supplied by the client connection.
447 static void parse_host_arg(char *extra_args, int buflen)
449 char *val;
450 int vallen;
451 char *end = extra_args + buflen;
453 if (extra_args < end && *extra_args) {
454 saw_extended_args = 1;
455 if (strncasecmp("host=", extra_args, 5) == 0) {
456 val = extra_args + 5;
457 vallen = strlen(val) + 1;
458 if (*val) {
459 /* Split <host>:<port> at colon. */
460 char *host;
461 char *port;
462 parse_host_and_port(val, &host, &port);
463 if (port) {
464 free(tcp_port);
465 tcp_port = xstrdup(port);
467 free(hostname);
468 hostname = xstrdup_tolower(host);
471 /* On to the next one */
472 extra_args = val + vallen;
474 if (extra_args < end && *extra_args)
475 die("Invalid request");
479 * Locate canonical hostname and its IP address.
481 if (hostname) {
482 #ifndef NO_IPV6
483 struct addrinfo hints;
484 struct addrinfo *ai;
485 int gai;
486 static char addrbuf[HOST_NAME_MAX + 1];
488 memset(&hints, 0, sizeof(hints));
489 hints.ai_flags = AI_CANONNAME;
491 gai = getaddrinfo(hostname, NULL, &hints, &ai);
492 if (!gai) {
493 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
495 inet_ntop(AF_INET, &sin_addr->sin_addr,
496 addrbuf, sizeof(addrbuf));
497 free(ip_address);
498 ip_address = xstrdup(addrbuf);
500 free(canon_hostname);
501 canon_hostname = xstrdup(ai->ai_canonname ?
502 ai->ai_canonname : ip_address);
504 freeaddrinfo(ai);
506 #else
507 struct hostent *hent;
508 struct sockaddr_in sa;
509 char **ap;
510 static char addrbuf[HOST_NAME_MAX + 1];
512 hent = gethostbyname(hostname);
514 ap = hent->h_addr_list;
515 memset(&sa, 0, sizeof sa);
516 sa.sin_family = hent->h_addrtype;
517 sa.sin_port = htons(0);
518 memcpy(&sa.sin_addr, *ap, hent->h_length);
520 inet_ntop(hent->h_addrtype, &sa.sin_addr,
521 addrbuf, sizeof(addrbuf));
523 free(canon_hostname);
524 canon_hostname = xstrdup(hent->h_name);
525 free(ip_address);
526 ip_address = xstrdup(addrbuf);
527 #endif
532 static int execute(void)
534 static char line[1000];
535 int pktlen, len, i;
536 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
538 if (addr)
539 loginfo("Connection from %s:%s", addr, port);
541 alarm(init_timeout ? init_timeout : timeout);
542 pktlen = packet_read_line(0, line, sizeof(line));
543 alarm(0);
545 len = strlen(line);
546 if (pktlen != len)
547 loginfo("Extended attributes (%d bytes) exist <%.*s>",
548 (int) pktlen - len,
549 (int) pktlen - len, line + len + 1);
550 if (len && line[len-1] == '\n') {
551 line[--len] = 0;
552 pktlen--;
555 free(hostname);
556 free(canon_hostname);
557 free(ip_address);
558 free(tcp_port);
559 hostname = canon_hostname = ip_address = tcp_port = NULL;
561 if (len != pktlen)
562 parse_host_arg(line + len + 1, pktlen - len - 1);
564 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
565 struct daemon_service *s = &(daemon_service[i]);
566 int namelen = strlen(s->name);
567 if (!prefixcmp(line, "git-") &&
568 !strncmp(s->name, line + 4, namelen) &&
569 line[namelen + 4] == ' ') {
571 * Note: The directory here is probably context sensitive,
572 * and might depend on the actual service being performed.
574 return run_service(line + namelen + 5, s);
578 logerror("Protocol error: '%s'", line);
579 return -1;
582 static int addrcmp(const struct sockaddr_storage *s1,
583 const struct sockaddr_storage *s2)
585 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
586 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
588 if (sa1->sa_family != sa2->sa_family)
589 return sa1->sa_family - sa2->sa_family;
590 if (sa1->sa_family == AF_INET)
591 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
592 &((struct sockaddr_in *)s2)->sin_addr,
593 sizeof(struct in_addr));
594 #ifndef NO_IPV6
595 if (sa1->sa_family == AF_INET6)
596 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
597 &((struct sockaddr_in6 *)s2)->sin6_addr,
598 sizeof(struct in6_addr));
599 #endif
600 return 0;
603 static int max_connections = 32;
605 static unsigned int live_children;
607 static struct child {
608 struct child *next;
609 struct child_process cld;
610 struct sockaddr_storage address;
611 } *firstborn;
613 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
615 struct child *newborn, **cradle;
617 newborn = xcalloc(1, sizeof(*newborn));
618 live_children++;
619 memcpy(&newborn->cld, cld, sizeof(*cld));
620 memcpy(&newborn->address, addr, addrlen);
621 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
622 if (!addrcmp(&(*cradle)->address, &newborn->address))
623 break;
624 newborn->next = *cradle;
625 *cradle = newborn;
629 * This gets called if the number of connections grows
630 * past "max_connections".
632 * We kill the newest connection from a duplicate IP.
634 static void kill_some_child(void)
636 const struct child *blanket, *next;
638 if (!(blanket = firstborn))
639 return;
641 for (; (next = blanket->next); blanket = next)
642 if (!addrcmp(&blanket->address, &next->address)) {
643 kill(blanket->cld.pid, SIGTERM);
644 break;
648 static void check_dead_children(void)
650 int status;
651 pid_t pid;
653 struct child **cradle, *blanket;
654 for (cradle = &firstborn; (blanket = *cradle);)
655 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
656 const char *dead = "";
657 if (status)
658 dead = " (with error)";
659 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
661 /* remove the child */
662 *cradle = blanket->next;
663 live_children--;
664 free(blanket);
665 } else
666 cradle = &blanket->next;
669 static char **cld_argv;
670 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
672 struct child_process cld = { NULL };
673 char addrbuf[300] = "REMOTE_ADDR=", portbuf[300];
674 char *env[] = { addrbuf, portbuf, NULL };
676 if (max_connections && live_children >= max_connections) {
677 kill_some_child();
678 sleep(1); /* give it some time to die */
679 check_dead_children();
680 if (live_children >= max_connections) {
681 close(incoming);
682 logerror("Too many children, dropping connection");
683 return;
687 if (addr->sa_family == AF_INET) {
688 struct sockaddr_in *sin_addr = (void *) addr;
689 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf + 12,
690 sizeof(addrbuf) - 12);
691 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
692 ntohs(sin_addr->sin_port));
693 #ifndef NO_IPV6
694 } else if (addr && addr->sa_family == AF_INET6) {
695 struct sockaddr_in6 *sin6_addr = (void *) addr;
697 char *buf = addrbuf + 12;
698 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
699 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf,
700 sizeof(addrbuf) - 13);
701 strcat(buf, "]");
703 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
704 ntohs(sin6_addr->sin6_port));
705 #endif
708 cld.env = (const char **)env;
709 cld.argv = (const char **)cld_argv;
710 cld.in = incoming;
711 cld.out = dup(incoming);
713 if (start_command(&cld))
714 logerror("unable to fork");
715 else
716 add_child(&cld, addr, addrlen);
717 close(incoming);
720 static void child_handler(int signo)
723 * Otherwise empty handler because systemcalls will get interrupted
724 * upon signal receipt
725 * SysV needs the handler to be rearmed
727 signal(SIGCHLD, child_handler);
730 static int set_reuse_addr(int sockfd)
732 int on = 1;
734 if (!reuseaddr)
735 return 0;
736 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
737 &on, sizeof(on));
740 struct socketlist {
741 int *list;
742 size_t nr;
743 size_t alloc;
746 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
748 #ifdef NO_IPV6
749 static char ip[INET_ADDRSTRLEN];
750 #else
751 static char ip[INET6_ADDRSTRLEN];
752 #endif
754 switch (family) {
755 #ifndef NO_IPV6
756 case AF_INET6:
757 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
758 break;
759 #endif
760 case AF_INET:
761 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
762 break;
763 default:
764 strcpy(ip, "<unknown>");
766 return ip;
769 #ifndef NO_IPV6
771 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
773 int socknum = 0;
774 int maxfd = -1;
775 char pbuf[NI_MAXSERV];
776 struct addrinfo hints, *ai0, *ai;
777 int gai;
778 long flags;
780 sprintf(pbuf, "%d", listen_port);
781 memset(&hints, 0, sizeof(hints));
782 hints.ai_family = AF_UNSPEC;
783 hints.ai_socktype = SOCK_STREAM;
784 hints.ai_protocol = IPPROTO_TCP;
785 hints.ai_flags = AI_PASSIVE;
787 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
788 if (gai) {
789 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
790 return 0;
793 for (ai = ai0; ai; ai = ai->ai_next) {
794 int sockfd;
796 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
797 if (sockfd < 0)
798 continue;
799 if (sockfd >= FD_SETSIZE) {
800 logerror("Socket descriptor too large");
801 close(sockfd);
802 continue;
805 #ifdef IPV6_V6ONLY
806 if (ai->ai_family == AF_INET6) {
807 int on = 1;
808 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
809 &on, sizeof(on));
810 /* Note: error is not fatal */
812 #endif
814 if (set_reuse_addr(sockfd)) {
815 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
816 close(sockfd);
817 continue;
820 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
821 logerror("Could not bind to %s: %s",
822 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
823 strerror(errno));
824 close(sockfd);
825 continue; /* not fatal */
827 if (listen(sockfd, 5) < 0) {
828 logerror("Could not listen to %s: %s",
829 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
830 strerror(errno));
831 close(sockfd);
832 continue; /* not fatal */
835 flags = fcntl(sockfd, F_GETFD, 0);
836 if (flags >= 0)
837 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
839 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
840 socklist->list[socklist->nr++] = sockfd;
841 socknum++;
843 if (maxfd < sockfd)
844 maxfd = sockfd;
847 freeaddrinfo(ai0);
849 return socknum;
852 #else /* NO_IPV6 */
854 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
856 struct sockaddr_in sin;
857 int sockfd;
858 long flags;
860 memset(&sin, 0, sizeof sin);
861 sin.sin_family = AF_INET;
862 sin.sin_port = htons(listen_port);
864 if (listen_addr) {
865 /* Well, host better be an IP address here. */
866 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
867 return 0;
868 } else {
869 sin.sin_addr.s_addr = htonl(INADDR_ANY);
872 sockfd = socket(AF_INET, SOCK_STREAM, 0);
873 if (sockfd < 0)
874 return 0;
876 if (set_reuse_addr(sockfd)) {
877 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
878 close(sockfd);
879 return 0;
882 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
883 logerror("Could not listen to %s: %s",
884 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
885 strerror(errno));
886 close(sockfd);
887 return 0;
890 if (listen(sockfd, 5) < 0) {
891 logerror("Could not listen to %s: %s",
892 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
893 strerror(errno));
894 close(sockfd);
895 return 0;
898 flags = fcntl(sockfd, F_GETFD, 0);
899 if (flags >= 0)
900 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
902 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
903 socklist->list[socklist->nr++] = sockfd;
904 return 1;
907 #endif
909 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
911 if (!listen_addr->nr)
912 setup_named_sock(NULL, listen_port, socklist);
913 else {
914 int i, socknum;
915 for (i = 0; i < listen_addr->nr; i++) {
916 socknum = setup_named_sock(listen_addr->items[i].string,
917 listen_port, socklist);
919 if (socknum == 0)
920 logerror("unable to allocate any listen sockets for host %s on port %u",
921 listen_addr->items[i].string, listen_port);
926 static int service_loop(struct socketlist *socklist)
928 struct pollfd *pfd;
929 int i;
931 pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
933 for (i = 0; i < socklist->nr; i++) {
934 pfd[i].fd = socklist->list[i];
935 pfd[i].events = POLLIN;
938 signal(SIGCHLD, child_handler);
940 for (;;) {
941 int i;
943 check_dead_children();
945 if (poll(pfd, socklist->nr, -1) < 0) {
946 if (errno != EINTR) {
947 logerror("Poll failed, resuming: %s",
948 strerror(errno));
949 sleep(1);
951 continue;
954 for (i = 0; i < socklist->nr; i++) {
955 if (pfd[i].revents & POLLIN) {
956 union {
957 struct sockaddr sa;
958 struct sockaddr_in sai;
959 #ifndef NO_IPV6
960 struct sockaddr_in6 sai6;
961 #endif
962 } ss;
963 socklen_t sslen = sizeof(ss);
964 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
965 if (incoming < 0) {
966 switch (errno) {
967 case EAGAIN:
968 case EINTR:
969 case ECONNABORTED:
970 continue;
971 default:
972 die_errno("accept returned");
975 handle(incoming, &ss.sa, sslen);
981 /* if any standard file descriptor is missing open it to /dev/null */
982 static void sanitize_stdfds(void)
984 int fd = open("/dev/null", O_RDWR, 0);
985 while (fd != -1 && fd < 2)
986 fd = dup(fd);
987 if (fd == -1)
988 die_errno("open /dev/null or dup failed");
989 if (fd > 2)
990 close(fd);
993 #ifdef NO_POSIX_GOODIES
995 struct credentials;
997 static void drop_privileges(struct credentials *cred)
999 /* nothing */
1002 static void daemonize(void)
1004 die("--detach not supported on this platform");
1007 static struct credentials *prepare_credentials(const char *user_name,
1008 const char *group_name)
1010 die("--user not supported on this platform");
1013 #else
1015 struct credentials {
1016 struct passwd *pass;
1017 gid_t gid;
1020 static void drop_privileges(struct credentials *cred)
1022 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1023 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1024 die("cannot drop privileges");
1027 static struct credentials *prepare_credentials(const char *user_name,
1028 const char *group_name)
1030 static struct credentials c;
1032 c.pass = getpwnam(user_name);
1033 if (!c.pass)
1034 die("user not found - %s", user_name);
1036 if (!group_name)
1037 c.gid = c.pass->pw_gid;
1038 else {
1039 struct group *group = getgrnam(group_name);
1040 if (!group)
1041 die("group not found - %s", group_name);
1043 c.gid = group->gr_gid;
1046 return &c;
1049 static void daemonize(void)
1051 switch (fork()) {
1052 case 0:
1053 break;
1054 case -1:
1055 die_errno("fork failed");
1056 default:
1057 exit(0);
1059 if (setsid() == -1)
1060 die_errno("setsid failed");
1061 close(0);
1062 close(1);
1063 close(2);
1064 sanitize_stdfds();
1066 #endif
1068 static void store_pid(const char *path)
1070 FILE *f = fopen(path, "w");
1071 if (!f)
1072 die_errno("cannot open pid file '%s'", path);
1073 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
1074 die_errno("failed to write pid file '%s'", path);
1077 static int serve(struct string_list *listen_addr, int listen_port,
1078 struct credentials *cred)
1080 struct socketlist socklist = { NULL, 0, 0 };
1082 socksetup(listen_addr, listen_port, &socklist);
1083 if (socklist.nr == 0)
1084 die("unable to allocate any listen sockets on port %u",
1085 listen_port);
1087 drop_privileges(cred);
1089 return service_loop(&socklist);
1092 int main(int argc, char **argv)
1094 int listen_port = 0;
1095 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1096 int serve_mode = 0, inetd_mode = 0;
1097 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1098 int detach = 0;
1099 struct credentials *cred = NULL;
1100 int i;
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 loginfo("Ready to rumble");
1275 else
1276 sanitize_stdfds();
1278 if (pid_file)
1279 store_pid(pid_file);
1281 /* prepare argv for serving-processes */
1282 cld_argv = xmalloc(sizeof (char *) * (argc + 2));
1283 cld_argv[0] = argv[0]; /* git-daemon */
1284 cld_argv[1] = "--serve";
1285 for (i = 1; i < argc; ++i)
1286 cld_argv[i+1] = argv[i];
1287 cld_argv[argc+1] = NULL;
1289 return serve(&listen_addr, listen_port, cred);