daemon: use strbuf for hostname info
[git/debian.git] / daemon.c
blob265c188823dae79731338a150b6e712ec0580401
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 " [--access-hook=<path>]\n"
30 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
31 " [--detach] [--user=<user> [--group=<group>]]\n"
32 " [<directory>...]";
34 /* List of acceptable pathname prefixes */
35 static char **ok_paths;
36 static int strict_paths;
38 /* If this is set, git-daemon-export-ok is not required */
39 static int export_all_trees;
41 /* Take all paths relative to this one if non-NULL */
42 static const char *base_path;
43 static const char *interpolated_path;
44 static int base_path_relaxed;
46 /* Flag indicating client sent extra args. */
47 static int saw_extended_args;
49 /* If defined, ~user notation is allowed and the string is inserted
50 * after ~user/. E.g. a request to git://host/~alice/frotz would
51 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
53 static const char *user_path;
55 /* Timeout, and initial timeout */
56 static unsigned int timeout;
57 static unsigned int init_timeout;
59 static struct strbuf hostname = STRBUF_INIT;
60 static struct strbuf canon_hostname = STRBUF_INIT;
61 static struct strbuf ip_address = STRBUF_INIT;
62 static struct strbuf tcp_port = STRBUF_INIT;
64 static int hostname_lookup_done;
66 static void lookup_hostname(void);
68 static const char *get_canon_hostname(void)
70 lookup_hostname();
71 return canon_hostname.buf;
74 static const char *get_ip_address(void)
76 lookup_hostname();
77 return ip_address.buf;
80 static void logreport(int priority, const char *err, va_list params)
82 if (log_syslog) {
83 char buf[1024];
84 vsnprintf(buf, sizeof(buf), err, params);
85 syslog(priority, "%s", buf);
86 } else {
88 * Since stderr is set to buffered mode, the
89 * logging of different processes will not overlap
90 * unless they overflow the (rather big) buffers.
92 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
93 vfprintf(stderr, err, params);
94 fputc('\n', stderr);
95 fflush(stderr);
99 __attribute__((format (printf, 1, 2)))
100 static void logerror(const char *err, ...)
102 va_list params;
103 va_start(params, err);
104 logreport(LOG_ERR, err, params);
105 va_end(params);
108 __attribute__((format (printf, 1, 2)))
109 static void loginfo(const char *err, ...)
111 va_list params;
112 if (!verbose)
113 return;
114 va_start(params, err);
115 logreport(LOG_INFO, err, params);
116 va_end(params);
119 static void NORETURN daemon_die(const char *err, va_list params)
121 logreport(LOG_ERR, err, params);
122 exit(1);
125 struct expand_path_context {
126 const char *directory;
129 static size_t expand_path(struct strbuf *sb, const char *placeholder, void *ctx)
131 struct expand_path_context *context = ctx;
133 switch (placeholder[0]) {
134 case 'H':
135 strbuf_addbuf(sb, &hostname);
136 return 1;
137 case 'C':
138 if (placeholder[1] == 'H') {
139 strbuf_addstr(sb, get_canon_hostname());
140 return 2;
142 break;
143 case 'I':
144 if (placeholder[1] == 'P') {
145 strbuf_addstr(sb, get_ip_address());
146 return 2;
148 break;
149 case 'P':
150 strbuf_addbuf(sb, &tcp_port);
151 return 1;
152 case 'D':
153 strbuf_addstr(sb, context->directory);
154 return 1;
156 return 0;
159 static const char *path_ok(const char *directory)
161 static char rpath[PATH_MAX];
162 static char interp_path[PATH_MAX];
163 const char *path;
164 const char *dir;
166 dir = directory;
168 if (daemon_avoid_alias(dir)) {
169 logerror("'%s': aliased", dir);
170 return NULL;
173 if (*dir == '~') {
174 if (!user_path) {
175 logerror("'%s': User-path not allowed", dir);
176 return NULL;
178 if (*user_path) {
179 /* Got either "~alice" or "~alice/foo";
180 * rewrite them to "~alice/%s" or
181 * "~alice/%s/foo".
183 int namlen, restlen = strlen(dir);
184 const char *slash = strchr(dir, '/');
185 if (!slash)
186 slash = dir + restlen;
187 namlen = slash - dir;
188 restlen -= namlen;
189 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
190 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
191 namlen, dir, user_path, restlen, slash);
192 dir = rpath;
195 else if (interpolated_path && saw_extended_args) {
196 struct strbuf expanded_path = STRBUF_INIT;
197 struct expand_path_context context;
199 context.directory = directory;
201 if (*dir != '/') {
202 /* Allow only absolute */
203 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
204 return NULL;
207 strbuf_expand(&expanded_path, interpolated_path,
208 expand_path, &context);
209 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
210 strbuf_release(&expanded_path);
211 loginfo("Interpolated dir '%s'", interp_path);
213 dir = interp_path;
215 else if (base_path) {
216 if (*dir != '/') {
217 /* Allow only absolute */
218 logerror("'%s': Non-absolute path denied (base-path active)", dir);
219 return NULL;
221 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
222 dir = rpath;
225 path = enter_repo(dir, strict_paths);
226 if (!path && base_path && base_path_relaxed) {
228 * if we fail and base_path_relaxed is enabled, try without
229 * prefixing the base path
231 dir = directory;
232 path = enter_repo(dir, strict_paths);
235 if (!path) {
236 logerror("'%s' does not appear to be a git repository", dir);
237 return NULL;
240 if ( ok_paths && *ok_paths ) {
241 char **pp;
242 int pathlen = strlen(path);
244 /* The validation is done on the paths after enter_repo
245 * appends optional {.git,.git/.git} and friends, but
246 * it does not use getcwd(). So if your /pub is
247 * a symlink to /mnt/pub, you can whitelist /pub and
248 * do not have to say /mnt/pub.
249 * Do not say /pub/.
251 for ( pp = ok_paths ; *pp ; pp++ ) {
252 int len = strlen(*pp);
253 if (len <= pathlen &&
254 !memcmp(*pp, path, len) &&
255 (path[len] == '\0' ||
256 (!strict_paths && path[len] == '/')))
257 return path;
260 else {
261 /* be backwards compatible */
262 if (!strict_paths)
263 return path;
266 logerror("'%s': not in whitelist", path);
267 return NULL; /* Fallthrough. Deny by default */
270 typedef int (*daemon_service_fn)(void);
271 struct daemon_service {
272 const char *name;
273 const char *config_name;
274 daemon_service_fn fn;
275 int enabled;
276 int overridable;
279 static int daemon_error(const char *dir, const char *msg)
281 if (!informative_errors)
282 msg = "access denied or repository not exported";
283 packet_write(1, "ERR %s: %s", msg, dir);
284 return -1;
287 static const char *access_hook;
289 static int run_access_hook(struct daemon_service *service, const char *dir, const char *path)
291 struct child_process child = CHILD_PROCESS_INIT;
292 struct strbuf buf = STRBUF_INIT;
293 const char *argv[8];
294 const char **arg = argv;
295 char *eol;
296 int seen_errors = 0;
298 *arg++ = access_hook;
299 *arg++ = service->name;
300 *arg++ = path;
301 *arg++ = hostname.buf;
302 *arg++ = get_canon_hostname();
303 *arg++ = get_ip_address();
304 *arg++ = tcp_port.buf;
305 *arg = NULL;
307 child.use_shell = 1;
308 child.argv = argv;
309 child.no_stdin = 1;
310 child.no_stderr = 1;
311 child.out = -1;
312 if (start_command(&child)) {
313 logerror("daemon access hook '%s' failed to start",
314 access_hook);
315 goto error_return;
317 if (strbuf_read(&buf, child.out, 0) < 0) {
318 logerror("failed to read from pipe to daemon access hook '%s'",
319 access_hook);
320 strbuf_reset(&buf);
321 seen_errors = 1;
323 if (close(child.out) < 0) {
324 logerror("failed to close pipe to daemon access hook '%s'",
325 access_hook);
326 seen_errors = 1;
328 if (finish_command(&child))
329 seen_errors = 1;
331 if (!seen_errors) {
332 strbuf_release(&buf);
333 return 0;
336 error_return:
337 strbuf_ltrim(&buf);
338 if (!buf.len)
339 strbuf_addstr(&buf, "service rejected");
340 eol = strchr(buf.buf, '\n');
341 if (eol)
342 *eol = '\0';
343 errno = EACCES;
344 daemon_error(dir, buf.buf);
345 strbuf_release(&buf);
346 return -1;
349 static int run_service(const char *dir, struct daemon_service *service)
351 const char *path;
352 int enabled = service->enabled;
353 struct strbuf var = STRBUF_INIT;
355 loginfo("Request %s for '%s'", service->name, dir);
357 if (!enabled && !service->overridable) {
358 logerror("'%s': service not enabled.", service->name);
359 errno = EACCES;
360 return daemon_error(dir, "service not enabled");
363 if (!(path = path_ok(dir)))
364 return daemon_error(dir, "no such repository");
367 * Security on the cheap.
369 * We want a readable HEAD, usable "objects" directory, and
370 * a "git-daemon-export-ok" flag that says that the other side
371 * is ok with us doing this.
373 * path_ok() uses enter_repo() and does whitelist checking.
374 * We only need to make sure the repository is exported.
377 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
378 logerror("'%s': repository not exported.", path);
379 errno = EACCES;
380 return daemon_error(dir, "repository not exported");
383 if (service->overridable) {
384 strbuf_addf(&var, "daemon.%s", service->config_name);
385 git_config_get_bool(var.buf, &enabled);
386 strbuf_release(&var);
388 if (!enabled) {
389 logerror("'%s': service not enabled for '%s'",
390 service->name, path);
391 errno = EACCES;
392 return daemon_error(dir, "service not enabled");
396 * Optionally, a hook can choose to deny access to the
397 * repository depending on the phase of the moon.
399 if (access_hook && run_access_hook(service, dir, path))
400 return -1;
403 * We'll ignore SIGTERM from now on, we have a
404 * good client.
406 signal(SIGTERM, SIG_IGN);
408 return service->fn();
411 static void copy_to_log(int fd)
413 struct strbuf line = STRBUF_INIT;
414 FILE *fp;
416 fp = fdopen(fd, "r");
417 if (fp == NULL) {
418 logerror("fdopen of error channel failed");
419 close(fd);
420 return;
423 while (strbuf_getline(&line, fp, '\n') != EOF) {
424 logerror("%s", line.buf);
425 strbuf_setlen(&line, 0);
428 strbuf_release(&line);
429 fclose(fp);
432 static int run_service_command(const char **argv)
434 struct child_process cld = CHILD_PROCESS_INIT;
436 cld.argv = argv;
437 cld.git_cmd = 1;
438 cld.err = -1;
439 if (start_command(&cld))
440 return -1;
442 close(0);
443 close(1);
445 copy_to_log(cld.err);
447 return finish_command(&cld);
450 static int upload_pack(void)
452 /* Timeout as string */
453 char timeout_buf[64];
454 const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
456 argv[2] = timeout_buf;
458 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
459 return run_service_command(argv);
462 static int upload_archive(void)
464 static const char *argv[] = { "upload-archive", ".", NULL };
465 return run_service_command(argv);
468 static int receive_pack(void)
470 static const char *argv[] = { "receive-pack", ".", NULL };
471 return run_service_command(argv);
474 static struct daemon_service daemon_service[] = {
475 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
476 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
477 { "receive-pack", "receivepack", receive_pack, 0, 1 },
480 static void enable_service(const char *name, int ena)
482 int i;
483 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
484 if (!strcmp(daemon_service[i].name, name)) {
485 daemon_service[i].enabled = ena;
486 return;
489 die("No such service %s", name);
492 static void make_service_overridable(const char *name, int ena)
494 int i;
495 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
496 if (!strcmp(daemon_service[i].name, name)) {
497 daemon_service[i].overridable = ena;
498 return;
501 die("No such service %s", name);
504 static void parse_host_and_port(char *hostport, char **host,
505 char **port)
507 if (*hostport == '[') {
508 char *end;
510 end = strchr(hostport, ']');
511 if (!end)
512 die("Invalid request ('[' without ']')");
513 *end = '\0';
514 *host = hostport + 1;
515 if (!end[1])
516 *port = NULL;
517 else if (end[1] == ':')
518 *port = end + 2;
519 else
520 die("Garbage after end of host part");
521 } else {
522 *host = hostport;
523 *port = strrchr(hostport, ':');
524 if (*port) {
525 **port = '\0';
526 ++*port;
532 * Sanitize a string from the client so that it's OK to be inserted into a
533 * filesystem path. Specifically, we disallow slashes, runs of "..", and
534 * trailing and leading dots, which means that the client cannot escape
535 * our base path via ".." traversal.
537 static void sanitize_client(struct strbuf *out, const char *in)
539 for (; *in; in++) {
540 if (*in == '/')
541 continue;
542 if (*in == '.' && (!out->len || out->buf[out->len - 1] == '.'))
543 continue;
544 strbuf_addch(out, *in);
547 while (out->len && out->buf[out->len - 1] == '.')
548 strbuf_setlen(out, out->len - 1);
552 * Like sanitize_client, but we also perform any canonicalization
553 * to make life easier on the admin.
555 static void canonicalize_client(struct strbuf *out, const char *in)
557 sanitize_client(out, in);
558 strbuf_tolower(out);
562 * Read the host as supplied by the client connection.
564 static void parse_host_arg(char *extra_args, int buflen)
566 char *val;
567 int vallen;
568 char *end = extra_args + buflen;
570 if (extra_args < end && *extra_args) {
571 saw_extended_args = 1;
572 if (strncasecmp("host=", extra_args, 5) == 0) {
573 val = extra_args + 5;
574 vallen = strlen(val) + 1;
575 if (*val) {
576 /* Split <host>:<port> at colon. */
577 char *host;
578 char *port;
579 parse_host_and_port(val, &host, &port);
580 if (port) {
581 strbuf_reset(&tcp_port);
582 sanitize_client(&tcp_port, port);
584 strbuf_reset(&hostname);
585 canonicalize_client(&hostname, host);
586 hostname_lookup_done = 0;
589 /* On to the next one */
590 extra_args = val + vallen;
592 if (extra_args < end && *extra_args)
593 die("Invalid request");
598 * Locate canonical hostname and its IP address.
600 static void lookup_hostname(void)
602 if (!hostname_lookup_done && hostname.len) {
603 #ifndef NO_IPV6
604 struct addrinfo hints;
605 struct addrinfo *ai;
606 int gai;
607 static char addrbuf[HOST_NAME_MAX + 1];
609 memset(&hints, 0, sizeof(hints));
610 hints.ai_flags = AI_CANONNAME;
612 gai = getaddrinfo(hostname.buf, NULL, &hints, &ai);
613 if (!gai) {
614 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
616 inet_ntop(AF_INET, &sin_addr->sin_addr,
617 addrbuf, sizeof(addrbuf));
618 strbuf_reset(&ip_address);
619 strbuf_addstr(&ip_address, addrbuf);
621 strbuf_reset(&canon_hostname);
622 if (ai->ai_canonname)
623 sanitize_client(&canon_hostname,
624 ai->ai_canonname);
625 else
626 strbuf_addbuf(&canon_hostname, &ip_address);
628 freeaddrinfo(ai);
630 #else
631 struct hostent *hent;
632 struct sockaddr_in sa;
633 char **ap;
634 static char addrbuf[HOST_NAME_MAX + 1];
636 hent = gethostbyname(hostname.buf);
637 if (hent) {
638 ap = hent->h_addr_list;
639 memset(&sa, 0, sizeof sa);
640 sa.sin_family = hent->h_addrtype;
641 sa.sin_port = htons(0);
642 memcpy(&sa.sin_addr, *ap, hent->h_length);
644 inet_ntop(hent->h_addrtype, &sa.sin_addr,
645 addrbuf, sizeof(addrbuf));
647 strbuf_reset(&canon_hostname);
648 sanitize_client(&canon_hostname, hent->h_name);
649 strbuf_reset(&ip_address);
650 strbuf_addstr(&ip_address, addrbuf);
652 #endif
653 hostname_lookup_done = 1;
658 static int execute(void)
660 char *line = packet_buffer;
661 int pktlen, len, i;
662 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
664 if (addr)
665 loginfo("Connection from %s:%s", addr, port);
667 alarm(init_timeout ? init_timeout : timeout);
668 pktlen = packet_read(0, NULL, NULL, packet_buffer, sizeof(packet_buffer), 0);
669 alarm(0);
671 len = strlen(line);
672 if (pktlen != len)
673 loginfo("Extended attributes (%d bytes) exist <%.*s>",
674 (int) pktlen - len,
675 (int) pktlen - len, line + len + 1);
676 if (len && line[len-1] == '\n') {
677 line[--len] = 0;
678 pktlen--;
681 strbuf_release(&hostname);
682 strbuf_release(&canon_hostname);
683 strbuf_release(&ip_address);
684 strbuf_release(&tcp_port);
686 if (len != pktlen)
687 parse_host_arg(line + len + 1, pktlen - len - 1);
689 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
690 struct daemon_service *s = &(daemon_service[i]);
691 const char *arg;
693 if (skip_prefix(line, "git-", &arg) &&
694 skip_prefix(arg, s->name, &arg) &&
695 *arg++ == ' ') {
697 * Note: The directory here is probably context sensitive,
698 * and might depend on the actual service being performed.
700 return run_service(arg, s);
704 logerror("Protocol error: '%s'", line);
705 return -1;
708 static int addrcmp(const struct sockaddr_storage *s1,
709 const struct sockaddr_storage *s2)
711 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
712 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
714 if (sa1->sa_family != sa2->sa_family)
715 return sa1->sa_family - sa2->sa_family;
716 if (sa1->sa_family == AF_INET)
717 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
718 &((struct sockaddr_in *)s2)->sin_addr,
719 sizeof(struct in_addr));
720 #ifndef NO_IPV6
721 if (sa1->sa_family == AF_INET6)
722 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
723 &((struct sockaddr_in6 *)s2)->sin6_addr,
724 sizeof(struct in6_addr));
725 #endif
726 return 0;
729 static int max_connections = 32;
731 static unsigned int live_children;
733 static struct child {
734 struct child *next;
735 struct child_process cld;
736 struct sockaddr_storage address;
737 } *firstborn;
739 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
741 struct child *newborn, **cradle;
743 newborn = xcalloc(1, sizeof(*newborn));
744 live_children++;
745 memcpy(&newborn->cld, cld, sizeof(*cld));
746 memcpy(&newborn->address, addr, addrlen);
747 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
748 if (!addrcmp(&(*cradle)->address, &newborn->address))
749 break;
750 newborn->next = *cradle;
751 *cradle = newborn;
755 * This gets called if the number of connections grows
756 * past "max_connections".
758 * We kill the newest connection from a duplicate IP.
760 static void kill_some_child(void)
762 const struct child *blanket, *next;
764 if (!(blanket = firstborn))
765 return;
767 for (; (next = blanket->next); blanket = next)
768 if (!addrcmp(&blanket->address, &next->address)) {
769 kill(blanket->cld.pid, SIGTERM);
770 break;
774 static void check_dead_children(void)
776 int status;
777 pid_t pid;
779 struct child **cradle, *blanket;
780 for (cradle = &firstborn; (blanket = *cradle);)
781 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
782 const char *dead = "";
783 if (status)
784 dead = " (with error)";
785 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
787 /* remove the child */
788 *cradle = blanket->next;
789 live_children--;
790 free(blanket);
791 } else
792 cradle = &blanket->next;
795 static char **cld_argv;
796 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
798 struct child_process cld = CHILD_PROCESS_INIT;
799 char addrbuf[300] = "REMOTE_ADDR=", portbuf[300];
800 char *env[] = { addrbuf, portbuf, NULL };
802 if (max_connections && live_children >= max_connections) {
803 kill_some_child();
804 sleep(1); /* give it some time to die */
805 check_dead_children();
806 if (live_children >= max_connections) {
807 close(incoming);
808 logerror("Too many children, dropping connection");
809 return;
813 if (addr->sa_family == AF_INET) {
814 struct sockaddr_in *sin_addr = (void *) addr;
815 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf + 12,
816 sizeof(addrbuf) - 12);
817 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
818 ntohs(sin_addr->sin_port));
819 #ifndef NO_IPV6
820 } else if (addr->sa_family == AF_INET6) {
821 struct sockaddr_in6 *sin6_addr = (void *) addr;
823 char *buf = addrbuf + 12;
824 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
825 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf,
826 sizeof(addrbuf) - 13);
827 strcat(buf, "]");
829 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
830 ntohs(sin6_addr->sin6_port));
831 #endif
834 cld.env = (const char **)env;
835 cld.argv = (const char **)cld_argv;
836 cld.in = incoming;
837 cld.out = dup(incoming);
839 if (start_command(&cld))
840 logerror("unable to fork");
841 else
842 add_child(&cld, addr, addrlen);
845 static void child_handler(int signo)
848 * Otherwise empty handler because systemcalls will get interrupted
849 * upon signal receipt
850 * SysV needs the handler to be rearmed
852 signal(SIGCHLD, child_handler);
855 static int set_reuse_addr(int sockfd)
857 int on = 1;
859 if (!reuseaddr)
860 return 0;
861 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
862 &on, sizeof(on));
865 struct socketlist {
866 int *list;
867 size_t nr;
868 size_t alloc;
871 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
873 #ifdef NO_IPV6
874 static char ip[INET_ADDRSTRLEN];
875 #else
876 static char ip[INET6_ADDRSTRLEN];
877 #endif
879 switch (family) {
880 #ifndef NO_IPV6
881 case AF_INET6:
882 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
883 break;
884 #endif
885 case AF_INET:
886 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
887 break;
888 default:
889 strcpy(ip, "<unknown>");
891 return ip;
894 #ifndef NO_IPV6
896 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
898 int socknum = 0;
899 char pbuf[NI_MAXSERV];
900 struct addrinfo hints, *ai0, *ai;
901 int gai;
902 long flags;
904 sprintf(pbuf, "%d", listen_port);
905 memset(&hints, 0, sizeof(hints));
906 hints.ai_family = AF_UNSPEC;
907 hints.ai_socktype = SOCK_STREAM;
908 hints.ai_protocol = IPPROTO_TCP;
909 hints.ai_flags = AI_PASSIVE;
911 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
912 if (gai) {
913 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
914 return 0;
917 for (ai = ai0; ai; ai = ai->ai_next) {
918 int sockfd;
920 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
921 if (sockfd < 0)
922 continue;
923 if (sockfd >= FD_SETSIZE) {
924 logerror("Socket descriptor too large");
925 close(sockfd);
926 continue;
929 #ifdef IPV6_V6ONLY
930 if (ai->ai_family == AF_INET6) {
931 int on = 1;
932 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
933 &on, sizeof(on));
934 /* Note: error is not fatal */
936 #endif
938 if (set_reuse_addr(sockfd)) {
939 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
940 close(sockfd);
941 continue;
944 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
945 logerror("Could not bind to %s: %s",
946 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
947 strerror(errno));
948 close(sockfd);
949 continue; /* not fatal */
951 if (listen(sockfd, 5) < 0) {
952 logerror("Could not listen to %s: %s",
953 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
954 strerror(errno));
955 close(sockfd);
956 continue; /* not fatal */
959 flags = fcntl(sockfd, F_GETFD, 0);
960 if (flags >= 0)
961 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
963 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
964 socklist->list[socklist->nr++] = sockfd;
965 socknum++;
968 freeaddrinfo(ai0);
970 return socknum;
973 #else /* NO_IPV6 */
975 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
977 struct sockaddr_in sin;
978 int sockfd;
979 long flags;
981 memset(&sin, 0, sizeof sin);
982 sin.sin_family = AF_INET;
983 sin.sin_port = htons(listen_port);
985 if (listen_addr) {
986 /* Well, host better be an IP address here. */
987 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
988 return 0;
989 } else {
990 sin.sin_addr.s_addr = htonl(INADDR_ANY);
993 sockfd = socket(AF_INET, SOCK_STREAM, 0);
994 if (sockfd < 0)
995 return 0;
997 if (set_reuse_addr(sockfd)) {
998 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
999 close(sockfd);
1000 return 0;
1003 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
1004 logerror("Could not bind to %s: %s",
1005 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1006 strerror(errno));
1007 close(sockfd);
1008 return 0;
1011 if (listen(sockfd, 5) < 0) {
1012 logerror("Could not listen to %s: %s",
1013 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1014 strerror(errno));
1015 close(sockfd);
1016 return 0;
1019 flags = fcntl(sockfd, F_GETFD, 0);
1020 if (flags >= 0)
1021 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1023 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1024 socklist->list[socklist->nr++] = sockfd;
1025 return 1;
1028 #endif
1030 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
1032 if (!listen_addr->nr)
1033 setup_named_sock(NULL, listen_port, socklist);
1034 else {
1035 int i, socknum;
1036 for (i = 0; i < listen_addr->nr; i++) {
1037 socknum = setup_named_sock(listen_addr->items[i].string,
1038 listen_port, socklist);
1040 if (socknum == 0)
1041 logerror("unable to allocate any listen sockets for host %s on port %u",
1042 listen_addr->items[i].string, listen_port);
1047 static int service_loop(struct socketlist *socklist)
1049 struct pollfd *pfd;
1050 int i;
1052 pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
1054 for (i = 0; i < socklist->nr; i++) {
1055 pfd[i].fd = socklist->list[i];
1056 pfd[i].events = POLLIN;
1059 signal(SIGCHLD, child_handler);
1061 for (;;) {
1062 int i;
1064 check_dead_children();
1066 if (poll(pfd, socklist->nr, -1) < 0) {
1067 if (errno != EINTR) {
1068 logerror("Poll failed, resuming: %s",
1069 strerror(errno));
1070 sleep(1);
1072 continue;
1075 for (i = 0; i < socklist->nr; i++) {
1076 if (pfd[i].revents & POLLIN) {
1077 union {
1078 struct sockaddr sa;
1079 struct sockaddr_in sai;
1080 #ifndef NO_IPV6
1081 struct sockaddr_in6 sai6;
1082 #endif
1083 } ss;
1084 socklen_t sslen = sizeof(ss);
1085 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1086 if (incoming < 0) {
1087 switch (errno) {
1088 case EAGAIN:
1089 case EINTR:
1090 case ECONNABORTED:
1091 continue;
1092 default:
1093 die_errno("accept returned");
1096 handle(incoming, &ss.sa, sslen);
1102 #ifdef NO_POSIX_GOODIES
1104 struct credentials;
1106 static void drop_privileges(struct credentials *cred)
1108 /* nothing */
1111 static struct credentials *prepare_credentials(const char *user_name,
1112 const char *group_name)
1114 die("--user not supported on this platform");
1117 #else
1119 struct credentials {
1120 struct passwd *pass;
1121 gid_t gid;
1124 static void drop_privileges(struct credentials *cred)
1126 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1127 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1128 die("cannot drop privileges");
1131 static struct credentials *prepare_credentials(const char *user_name,
1132 const char *group_name)
1134 static struct credentials c;
1136 c.pass = getpwnam(user_name);
1137 if (!c.pass)
1138 die("user not found - %s", user_name);
1140 if (!group_name)
1141 c.gid = c.pass->pw_gid;
1142 else {
1143 struct group *group = getgrnam(group_name);
1144 if (!group)
1145 die("group not found - %s", group_name);
1147 c.gid = group->gr_gid;
1150 return &c;
1152 #endif
1154 static void store_pid(const char *path)
1156 FILE *f = fopen(path, "w");
1157 if (!f)
1158 die_errno("cannot open pid file '%s'", path);
1159 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
1160 die_errno("failed to write pid file '%s'", path);
1163 static int serve(struct string_list *listen_addr, int listen_port,
1164 struct credentials *cred)
1166 struct socketlist socklist = { NULL, 0, 0 };
1168 socksetup(listen_addr, listen_port, &socklist);
1169 if (socklist.nr == 0)
1170 die("unable to allocate any listen sockets on port %u",
1171 listen_port);
1173 drop_privileges(cred);
1175 loginfo("Ready to rumble");
1177 return service_loop(&socklist);
1180 int main(int argc, char **argv)
1182 int listen_port = 0;
1183 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1184 int serve_mode = 0, inetd_mode = 0;
1185 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1186 int detach = 0;
1187 struct credentials *cred = NULL;
1188 int i;
1190 git_setup_gettext();
1192 git_extract_argv0_path(argv[0]);
1194 for (i = 1; i < argc; i++) {
1195 char *arg = argv[i];
1196 const char *v;
1198 if (skip_prefix(arg, "--listen=", &v)) {
1199 string_list_append(&listen_addr, xstrdup_tolower(v));
1200 continue;
1202 if (skip_prefix(arg, "--port=", &v)) {
1203 char *end;
1204 unsigned long n;
1205 n = strtoul(v, &end, 0);
1206 if (*v && !*end) {
1207 listen_port = n;
1208 continue;
1211 if (!strcmp(arg, "--serve")) {
1212 serve_mode = 1;
1213 continue;
1215 if (!strcmp(arg, "--inetd")) {
1216 inetd_mode = 1;
1217 log_syslog = 1;
1218 continue;
1220 if (!strcmp(arg, "--verbose")) {
1221 verbose = 1;
1222 continue;
1224 if (!strcmp(arg, "--syslog")) {
1225 log_syslog = 1;
1226 continue;
1228 if (!strcmp(arg, "--export-all")) {
1229 export_all_trees = 1;
1230 continue;
1232 if (skip_prefix(arg, "--access-hook=", &v)) {
1233 access_hook = v;
1234 continue;
1236 if (skip_prefix(arg, "--timeout=", &v)) {
1237 timeout = atoi(v);
1238 continue;
1240 if (skip_prefix(arg, "--init-timeout=", &v)) {
1241 init_timeout = atoi(v);
1242 continue;
1244 if (skip_prefix(arg, "--max-connections=", &v)) {
1245 max_connections = atoi(v);
1246 if (max_connections < 0)
1247 max_connections = 0; /* unlimited */
1248 continue;
1250 if (!strcmp(arg, "--strict-paths")) {
1251 strict_paths = 1;
1252 continue;
1254 if (skip_prefix(arg, "--base-path=", &v)) {
1255 base_path = v;
1256 continue;
1258 if (!strcmp(arg, "--base-path-relaxed")) {
1259 base_path_relaxed = 1;
1260 continue;
1262 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1263 interpolated_path = v;
1264 continue;
1266 if (!strcmp(arg, "--reuseaddr")) {
1267 reuseaddr = 1;
1268 continue;
1270 if (!strcmp(arg, "--user-path")) {
1271 user_path = "";
1272 continue;
1274 if (skip_prefix(arg, "--user-path=", &v)) {
1275 user_path = v;
1276 continue;
1278 if (skip_prefix(arg, "--pid-file=", &v)) {
1279 pid_file = v;
1280 continue;
1282 if (!strcmp(arg, "--detach")) {
1283 detach = 1;
1284 log_syslog = 1;
1285 continue;
1287 if (skip_prefix(arg, "--user=", &v)) {
1288 user_name = v;
1289 continue;
1291 if (skip_prefix(arg, "--group=", &v)) {
1292 group_name = v;
1293 continue;
1295 if (skip_prefix(arg, "--enable=", &v)) {
1296 enable_service(v, 1);
1297 continue;
1299 if (skip_prefix(arg, "--disable=", &v)) {
1300 enable_service(v, 0);
1301 continue;
1303 if (skip_prefix(arg, "--allow-override=", &v)) {
1304 make_service_overridable(v, 1);
1305 continue;
1307 if (skip_prefix(arg, "--forbid-override=", &v)) {
1308 make_service_overridable(v, 0);
1309 continue;
1311 if (!strcmp(arg, "--informative-errors")) {
1312 informative_errors = 1;
1313 continue;
1315 if (!strcmp(arg, "--no-informative-errors")) {
1316 informative_errors = 0;
1317 continue;
1319 if (!strcmp(arg, "--")) {
1320 ok_paths = &argv[i+1];
1321 break;
1322 } else if (arg[0] != '-') {
1323 ok_paths = &argv[i];
1324 break;
1327 usage(daemon_usage);
1330 if (log_syslog) {
1331 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1332 set_die_routine(daemon_die);
1333 } else
1334 /* avoid splitting a message in the middle */
1335 setvbuf(stderr, NULL, _IOFBF, 4096);
1337 if (inetd_mode && (detach || group_name || user_name))
1338 die("--detach, --user and --group are incompatible with --inetd");
1340 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1341 die("--listen= and --port= are incompatible with --inetd");
1342 else if (listen_port == 0)
1343 listen_port = DEFAULT_GIT_PORT;
1345 if (group_name && !user_name)
1346 die("--group supplied without --user");
1348 if (user_name)
1349 cred = prepare_credentials(user_name, group_name);
1351 if (strict_paths && (!ok_paths || !*ok_paths))
1352 die("option --strict-paths requires a whitelist");
1354 if (base_path && !is_directory(base_path))
1355 die("base-path '%s' does not exist or is not a directory",
1356 base_path);
1358 if (inetd_mode) {
1359 if (!freopen("/dev/null", "w", stderr))
1360 die_errno("failed to redirect stderr to /dev/null");
1363 if (inetd_mode || serve_mode)
1364 return execute();
1366 if (detach) {
1367 if (daemonize())
1368 die("--detach not supported on this platform");
1369 } else
1370 sanitize_stdfds();
1372 if (pid_file)
1373 store_pid(pid_file);
1375 /* prepare argv for serving-processes */
1376 cld_argv = xmalloc(sizeof (char *) * (argc + 2));
1377 cld_argv[0] = argv[0]; /* git-daemon */
1378 cld_argv[1] = "--serve";
1379 for (i = 1; i < argc; ++i)
1380 cld_argv[i+1] = argv[i];
1381 cld_argv[argc+1] = NULL;
1383 return serve(&listen_addr, listen_port, cred);