daemon: detect and reject too-long paths
[git/debian.git] / daemon.c
blob72f6ad3c0d5faccfb845f7181331e621454376da
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 /* If defined, ~user notation is allowed and the string is inserted
47 * after ~user/. E.g. a request to git://host/~alice/frotz would
48 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
50 static const char *user_path;
52 /* Timeout, and initial timeout */
53 static unsigned int timeout;
54 static unsigned int init_timeout;
56 struct hostinfo {
57 struct strbuf hostname;
58 struct strbuf canon_hostname;
59 struct strbuf ip_address;
60 struct strbuf tcp_port;
61 unsigned int hostname_lookup_done:1;
62 unsigned int saw_extended_args:1;
65 static void lookup_hostname(struct hostinfo *hi);
67 static const char *get_canon_hostname(struct hostinfo *hi)
69 lookup_hostname(hi);
70 return hi->canon_hostname.buf;
73 static const char *get_ip_address(struct hostinfo *hi)
75 lookup_hostname(hi);
76 return hi->ip_address.buf;
79 static void logreport(int priority, const char *err, va_list params)
81 if (log_syslog) {
82 char buf[1024];
83 vsnprintf(buf, sizeof(buf), err, params);
84 syslog(priority, "%s", buf);
85 } else {
87 * Since stderr is set to buffered mode, the
88 * logging of different processes will not overlap
89 * unless they overflow the (rather big) buffers.
91 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
92 vfprintf(stderr, err, params);
93 fputc('\n', stderr);
94 fflush(stderr);
98 __attribute__((format (printf, 1, 2)))
99 static void logerror(const char *err, ...)
101 va_list params;
102 va_start(params, err);
103 logreport(LOG_ERR, err, params);
104 va_end(params);
107 __attribute__((format (printf, 1, 2)))
108 static void loginfo(const char *err, ...)
110 va_list params;
111 if (!verbose)
112 return;
113 va_start(params, err);
114 logreport(LOG_INFO, err, params);
115 va_end(params);
118 static void NORETURN daemon_die(const char *err, va_list params)
120 logreport(LOG_ERR, err, params);
121 exit(1);
124 struct expand_path_context {
125 const char *directory;
126 struct hostinfo *hostinfo;
129 static size_t expand_path(struct strbuf *sb, const char *placeholder, void *ctx)
131 struct expand_path_context *context = ctx;
132 struct hostinfo *hi = context->hostinfo;
134 switch (placeholder[0]) {
135 case 'H':
136 strbuf_addbuf(sb, &hi->hostname);
137 return 1;
138 case 'C':
139 if (placeholder[1] == 'H') {
140 strbuf_addstr(sb, get_canon_hostname(hi));
141 return 2;
143 break;
144 case 'I':
145 if (placeholder[1] == 'P') {
146 strbuf_addstr(sb, get_ip_address(hi));
147 return 2;
149 break;
150 case 'P':
151 strbuf_addbuf(sb, &hi->tcp_port);
152 return 1;
153 case 'D':
154 strbuf_addstr(sb, context->directory);
155 return 1;
157 return 0;
160 static const char *path_ok(const char *directory, struct hostinfo *hi)
162 static char rpath[PATH_MAX];
163 static char interp_path[PATH_MAX];
164 size_t rlen;
165 const char *path;
166 const char *dir;
168 dir = directory;
170 if (daemon_avoid_alias(dir)) {
171 logerror("'%s': aliased", dir);
172 return NULL;
175 if (*dir == '~') {
176 if (!user_path) {
177 logerror("'%s': User-path not allowed", dir);
178 return NULL;
180 if (*user_path) {
181 /* Got either "~alice" or "~alice/foo";
182 * rewrite them to "~alice/%s" or
183 * "~alice/%s/foo".
185 int namlen, restlen = strlen(dir);
186 const char *slash = strchr(dir, '/');
187 if (!slash)
188 slash = dir + restlen;
189 namlen = slash - dir;
190 restlen -= namlen;
191 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
192 rlen = snprintf(rpath, sizeof(rpath), "%.*s/%s%.*s",
193 namlen, dir, user_path, restlen, slash);
194 if (rlen >= sizeof(rpath)) {
195 logerror("user-path too large: %s", rpath);
196 return NULL;
198 dir = rpath;
201 else if (interpolated_path && hi->saw_extended_args) {
202 struct strbuf expanded_path = STRBUF_INIT;
203 struct expand_path_context context;
205 context.directory = directory;
206 context.hostinfo = hi;
208 if (*dir != '/') {
209 /* Allow only absolute */
210 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
211 return NULL;
214 strbuf_expand(&expanded_path, interpolated_path,
215 expand_path, &context);
217 rlen = strlcpy(interp_path, expanded_path.buf,
218 sizeof(interp_path));
219 if (rlen >= sizeof(interp_path)) {
220 logerror("interpolated path too large: %s",
221 interp_path);
222 return NULL;
225 strbuf_release(&expanded_path);
226 loginfo("Interpolated dir '%s'", interp_path);
228 dir = interp_path;
230 else if (base_path) {
231 if (*dir != '/') {
232 /* Allow only absolute */
233 logerror("'%s': Non-absolute path denied (base-path active)", dir);
234 return NULL;
236 rlen = snprintf(rpath, sizeof(rpath), "%s%s", base_path, dir);
237 if (rlen >= sizeof(rpath)) {
238 logerror("base-path too large: %s", rpath);
239 return NULL;
241 dir = rpath;
244 path = enter_repo(dir, strict_paths);
245 if (!path && base_path && base_path_relaxed) {
247 * if we fail and base_path_relaxed is enabled, try without
248 * prefixing the base path
250 dir = directory;
251 path = enter_repo(dir, strict_paths);
254 if (!path) {
255 logerror("'%s' does not appear to be a git repository", dir);
256 return NULL;
259 if ( ok_paths && *ok_paths ) {
260 char **pp;
261 int pathlen = strlen(path);
263 /* The validation is done on the paths after enter_repo
264 * appends optional {.git,.git/.git} and friends, but
265 * it does not use getcwd(). So if your /pub is
266 * a symlink to /mnt/pub, you can whitelist /pub and
267 * do not have to say /mnt/pub.
268 * Do not say /pub/.
270 for ( pp = ok_paths ; *pp ; pp++ ) {
271 int len = strlen(*pp);
272 if (len <= pathlen &&
273 !memcmp(*pp, path, len) &&
274 (path[len] == '\0' ||
275 (!strict_paths && path[len] == '/')))
276 return path;
279 else {
280 /* be backwards compatible */
281 if (!strict_paths)
282 return path;
285 logerror("'%s': not in whitelist", path);
286 return NULL; /* Fallthrough. Deny by default */
289 typedef int (*daemon_service_fn)(void);
290 struct daemon_service {
291 const char *name;
292 const char *config_name;
293 daemon_service_fn fn;
294 int enabled;
295 int overridable;
298 static int daemon_error(const char *dir, const char *msg)
300 if (!informative_errors)
301 msg = "access denied or repository not exported";
302 packet_write(1, "ERR %s: %s", msg, dir);
303 return -1;
306 static const char *access_hook;
308 static int run_access_hook(struct daemon_service *service, const char *dir,
309 const char *path, struct hostinfo *hi)
311 struct child_process child = CHILD_PROCESS_INIT;
312 struct strbuf buf = STRBUF_INIT;
313 const char *argv[8];
314 const char **arg = argv;
315 char *eol;
316 int seen_errors = 0;
318 *arg++ = access_hook;
319 *arg++ = service->name;
320 *arg++ = path;
321 *arg++ = hi->hostname.buf;
322 *arg++ = get_canon_hostname(hi);
323 *arg++ = get_ip_address(hi);
324 *arg++ = hi->tcp_port.buf;
325 *arg = NULL;
327 child.use_shell = 1;
328 child.argv = argv;
329 child.no_stdin = 1;
330 child.no_stderr = 1;
331 child.out = -1;
332 if (start_command(&child)) {
333 logerror("daemon access hook '%s' failed to start",
334 access_hook);
335 goto error_return;
337 if (strbuf_read(&buf, child.out, 0) < 0) {
338 logerror("failed to read from pipe to daemon access hook '%s'",
339 access_hook);
340 strbuf_reset(&buf);
341 seen_errors = 1;
343 if (close(child.out) < 0) {
344 logerror("failed to close pipe to daemon access hook '%s'",
345 access_hook);
346 seen_errors = 1;
348 if (finish_command(&child))
349 seen_errors = 1;
351 if (!seen_errors) {
352 strbuf_release(&buf);
353 return 0;
356 error_return:
357 strbuf_ltrim(&buf);
358 if (!buf.len)
359 strbuf_addstr(&buf, "service rejected");
360 eol = strchr(buf.buf, '\n');
361 if (eol)
362 *eol = '\0';
363 errno = EACCES;
364 daemon_error(dir, buf.buf);
365 strbuf_release(&buf);
366 return -1;
369 static int run_service(const char *dir, struct daemon_service *service,
370 struct hostinfo *hi)
372 const char *path;
373 int enabled = service->enabled;
374 struct strbuf var = STRBUF_INIT;
376 loginfo("Request %s for '%s'", service->name, dir);
378 if (!enabled && !service->overridable) {
379 logerror("'%s': service not enabled.", service->name);
380 errno = EACCES;
381 return daemon_error(dir, "service not enabled");
384 if (!(path = path_ok(dir, hi)))
385 return daemon_error(dir, "no such repository");
388 * Security on the cheap.
390 * We want a readable HEAD, usable "objects" directory, and
391 * a "git-daemon-export-ok" flag that says that the other side
392 * is ok with us doing this.
394 * path_ok() uses enter_repo() and does whitelist checking.
395 * We only need to make sure the repository is exported.
398 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
399 logerror("'%s': repository not exported.", path);
400 errno = EACCES;
401 return daemon_error(dir, "repository not exported");
404 if (service->overridable) {
405 strbuf_addf(&var, "daemon.%s", service->config_name);
406 git_config_get_bool(var.buf, &enabled);
407 strbuf_release(&var);
409 if (!enabled) {
410 logerror("'%s': service not enabled for '%s'",
411 service->name, path);
412 errno = EACCES;
413 return daemon_error(dir, "service not enabled");
417 * Optionally, a hook can choose to deny access to the
418 * repository depending on the phase of the moon.
420 if (access_hook && run_access_hook(service, dir, path, hi))
421 return -1;
424 * We'll ignore SIGTERM from now on, we have a
425 * good client.
427 signal(SIGTERM, SIG_IGN);
429 return service->fn();
432 static void copy_to_log(int fd)
434 struct strbuf line = STRBUF_INIT;
435 FILE *fp;
437 fp = fdopen(fd, "r");
438 if (fp == NULL) {
439 logerror("fdopen of error channel failed");
440 close(fd);
441 return;
444 while (strbuf_getline_lf(&line, fp) != EOF) {
445 logerror("%s", line.buf);
446 strbuf_setlen(&line, 0);
449 strbuf_release(&line);
450 fclose(fp);
453 static int run_service_command(const char **argv)
455 struct child_process cld = CHILD_PROCESS_INIT;
457 cld.argv = argv;
458 cld.git_cmd = 1;
459 cld.err = -1;
460 if (start_command(&cld))
461 return -1;
463 close(0);
464 close(1);
466 copy_to_log(cld.err);
468 return finish_command(&cld);
471 static int upload_pack(void)
473 /* Timeout as string */
474 char timeout_buf[64];
475 const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
477 argv[2] = timeout_buf;
479 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
480 return run_service_command(argv);
483 static int upload_archive(void)
485 static const char *argv[] = { "upload-archive", ".", NULL };
486 return run_service_command(argv);
489 static int receive_pack(void)
491 static const char *argv[] = { "receive-pack", ".", NULL };
492 return run_service_command(argv);
495 static struct daemon_service daemon_service[] = {
496 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
497 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
498 { "receive-pack", "receivepack", receive_pack, 0, 1 },
501 static void enable_service(const char *name, int ena)
503 int i;
504 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
505 if (!strcmp(daemon_service[i].name, name)) {
506 daemon_service[i].enabled = ena;
507 return;
510 die("No such service %s", name);
513 static void make_service_overridable(const char *name, int ena)
515 int i;
516 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
517 if (!strcmp(daemon_service[i].name, name)) {
518 daemon_service[i].overridable = ena;
519 return;
522 die("No such service %s", name);
525 static void parse_host_and_port(char *hostport, char **host,
526 char **port)
528 if (*hostport == '[') {
529 char *end;
531 end = strchr(hostport, ']');
532 if (!end)
533 die("Invalid request ('[' without ']')");
534 *end = '\0';
535 *host = hostport + 1;
536 if (!end[1])
537 *port = NULL;
538 else if (end[1] == ':')
539 *port = end + 2;
540 else
541 die("Garbage after end of host part");
542 } else {
543 *host = hostport;
544 *port = strrchr(hostport, ':');
545 if (*port) {
546 **port = '\0';
547 ++*port;
553 * Sanitize a string from the client so that it's OK to be inserted into a
554 * filesystem path. Specifically, we disallow slashes, runs of "..", and
555 * trailing and leading dots, which means that the client cannot escape
556 * our base path via ".." traversal.
558 static void sanitize_client(struct strbuf *out, const char *in)
560 for (; *in; in++) {
561 if (*in == '/')
562 continue;
563 if (*in == '.' && (!out->len || out->buf[out->len - 1] == '.'))
564 continue;
565 strbuf_addch(out, *in);
568 while (out->len && out->buf[out->len - 1] == '.')
569 strbuf_setlen(out, out->len - 1);
573 * Like sanitize_client, but we also perform any canonicalization
574 * to make life easier on the admin.
576 static void canonicalize_client(struct strbuf *out, const char *in)
578 sanitize_client(out, in);
579 strbuf_tolower(out);
583 * Read the host as supplied by the client connection.
585 static void parse_host_arg(struct hostinfo *hi, char *extra_args, int buflen)
587 char *val;
588 int vallen;
589 char *end = extra_args + buflen;
591 if (extra_args < end && *extra_args) {
592 hi->saw_extended_args = 1;
593 if (strncasecmp("host=", extra_args, 5) == 0) {
594 val = extra_args + 5;
595 vallen = strlen(val) + 1;
596 if (*val) {
597 /* Split <host>:<port> at colon. */
598 char *host;
599 char *port;
600 parse_host_and_port(val, &host, &port);
601 if (port)
602 sanitize_client(&hi->tcp_port, port);
603 canonicalize_client(&hi->hostname, host);
604 hi->hostname_lookup_done = 0;
607 /* On to the next one */
608 extra_args = val + vallen;
610 if (extra_args < end && *extra_args)
611 die("Invalid request");
616 * Locate canonical hostname and its IP address.
618 static void lookup_hostname(struct hostinfo *hi)
620 if (!hi->hostname_lookup_done && hi->hostname.len) {
621 #ifndef NO_IPV6
622 struct addrinfo hints;
623 struct addrinfo *ai;
624 int gai;
625 static char addrbuf[HOST_NAME_MAX + 1];
627 memset(&hints, 0, sizeof(hints));
628 hints.ai_flags = AI_CANONNAME;
630 gai = getaddrinfo(hi->hostname.buf, NULL, &hints, &ai);
631 if (!gai) {
632 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
634 inet_ntop(AF_INET, &sin_addr->sin_addr,
635 addrbuf, sizeof(addrbuf));
636 strbuf_addstr(&hi->ip_address, addrbuf);
638 if (ai->ai_canonname)
639 sanitize_client(&hi->canon_hostname,
640 ai->ai_canonname);
641 else
642 strbuf_addbuf(&hi->canon_hostname,
643 &hi->ip_address);
645 freeaddrinfo(ai);
647 #else
648 struct hostent *hent;
649 struct sockaddr_in sa;
650 char **ap;
651 static char addrbuf[HOST_NAME_MAX + 1];
653 hent = gethostbyname(hi->hostname.buf);
654 if (hent) {
655 ap = hent->h_addr_list;
656 memset(&sa, 0, sizeof sa);
657 sa.sin_family = hent->h_addrtype;
658 sa.sin_port = htons(0);
659 memcpy(&sa.sin_addr, *ap, hent->h_length);
661 inet_ntop(hent->h_addrtype, &sa.sin_addr,
662 addrbuf, sizeof(addrbuf));
664 sanitize_client(&hi->canon_hostname, hent->h_name);
665 strbuf_addstr(&hi->ip_address, addrbuf);
667 #endif
668 hi->hostname_lookup_done = 1;
672 static void hostinfo_init(struct hostinfo *hi)
674 memset(hi, 0, sizeof(*hi));
675 strbuf_init(&hi->hostname, 0);
676 strbuf_init(&hi->canon_hostname, 0);
677 strbuf_init(&hi->ip_address, 0);
678 strbuf_init(&hi->tcp_port, 0);
681 static void hostinfo_clear(struct hostinfo *hi)
683 strbuf_release(&hi->hostname);
684 strbuf_release(&hi->canon_hostname);
685 strbuf_release(&hi->ip_address);
686 strbuf_release(&hi->tcp_port);
689 static int execute(void)
691 char *line = packet_buffer;
692 int pktlen, len, i;
693 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
694 struct hostinfo hi;
696 hostinfo_init(&hi);
698 if (addr)
699 loginfo("Connection from %s:%s", addr, port);
701 alarm(init_timeout ? init_timeout : timeout);
702 pktlen = packet_read(0, NULL, NULL, packet_buffer, sizeof(packet_buffer), 0);
703 alarm(0);
705 len = strlen(line);
706 if (pktlen != len)
707 loginfo("Extended attributes (%d bytes) exist <%.*s>",
708 (int) pktlen - len,
709 (int) pktlen - len, line + len + 1);
710 if (len && line[len-1] == '\n') {
711 line[--len] = 0;
712 pktlen--;
715 if (len != pktlen)
716 parse_host_arg(&hi, line + len + 1, pktlen - len - 1);
718 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
719 struct daemon_service *s = &(daemon_service[i]);
720 const char *arg;
722 if (skip_prefix(line, "git-", &arg) &&
723 skip_prefix(arg, s->name, &arg) &&
724 *arg++ == ' ') {
726 * Note: The directory here is probably context sensitive,
727 * and might depend on the actual service being performed.
729 int rc = run_service(arg, s, &hi);
730 hostinfo_clear(&hi);
731 return rc;
735 hostinfo_clear(&hi);
736 logerror("Protocol error: '%s'", line);
737 return -1;
740 static int addrcmp(const struct sockaddr_storage *s1,
741 const struct sockaddr_storage *s2)
743 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
744 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
746 if (sa1->sa_family != sa2->sa_family)
747 return sa1->sa_family - sa2->sa_family;
748 if (sa1->sa_family == AF_INET)
749 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
750 &((struct sockaddr_in *)s2)->sin_addr,
751 sizeof(struct in_addr));
752 #ifndef NO_IPV6
753 if (sa1->sa_family == AF_INET6)
754 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
755 &((struct sockaddr_in6 *)s2)->sin6_addr,
756 sizeof(struct in6_addr));
757 #endif
758 return 0;
761 static int max_connections = 32;
763 static unsigned int live_children;
765 static struct child {
766 struct child *next;
767 struct child_process cld;
768 struct sockaddr_storage address;
769 } *firstborn;
771 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
773 struct child *newborn, **cradle;
775 newborn = xcalloc(1, sizeof(*newborn));
776 live_children++;
777 memcpy(&newborn->cld, cld, sizeof(*cld));
778 memcpy(&newborn->address, addr, addrlen);
779 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
780 if (!addrcmp(&(*cradle)->address, &newborn->address))
781 break;
782 newborn->next = *cradle;
783 *cradle = newborn;
787 * This gets called if the number of connections grows
788 * past "max_connections".
790 * We kill the newest connection from a duplicate IP.
792 static void kill_some_child(void)
794 const struct child *blanket, *next;
796 if (!(blanket = firstborn))
797 return;
799 for (; (next = blanket->next); blanket = next)
800 if (!addrcmp(&blanket->address, &next->address)) {
801 kill(blanket->cld.pid, SIGTERM);
802 break;
806 static void check_dead_children(void)
808 int status;
809 pid_t pid;
811 struct child **cradle, *blanket;
812 for (cradle = &firstborn; (blanket = *cradle);)
813 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
814 const char *dead = "";
815 if (status)
816 dead = " (with error)";
817 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
819 /* remove the child */
820 *cradle = blanket->next;
821 live_children--;
822 child_process_clear(&blanket->cld);
823 free(blanket);
824 } else
825 cradle = &blanket->next;
828 static struct argv_array cld_argv = ARGV_ARRAY_INIT;
829 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
831 struct child_process cld = CHILD_PROCESS_INIT;
833 if (max_connections && live_children >= max_connections) {
834 kill_some_child();
835 sleep(1); /* give it some time to die */
836 check_dead_children();
837 if (live_children >= max_connections) {
838 close(incoming);
839 logerror("Too many children, dropping connection");
840 return;
844 if (addr->sa_family == AF_INET) {
845 char buf[128] = "";
846 struct sockaddr_in *sin_addr = (void *) addr;
847 inet_ntop(addr->sa_family, &sin_addr->sin_addr, buf, sizeof(buf));
848 argv_array_pushf(&cld.env_array, "REMOTE_ADDR=%s", buf);
849 argv_array_pushf(&cld.env_array, "REMOTE_PORT=%d",
850 ntohs(sin_addr->sin_port));
851 #ifndef NO_IPV6
852 } else if (addr->sa_family == AF_INET6) {
853 char buf[128] = "";
854 struct sockaddr_in6 *sin6_addr = (void *) addr;
855 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(buf));
856 argv_array_pushf(&cld.env_array, "REMOTE_ADDR=[%s]", buf);
857 argv_array_pushf(&cld.env_array, "REMOTE_PORT=%d",
858 ntohs(sin6_addr->sin6_port));
859 #endif
862 cld.argv = cld_argv.argv;
863 cld.in = incoming;
864 cld.out = dup(incoming);
866 if (start_command(&cld))
867 logerror("unable to fork");
868 else
869 add_child(&cld, addr, addrlen);
872 static void child_handler(int signo)
875 * Otherwise empty handler because systemcalls will get interrupted
876 * upon signal receipt
877 * SysV needs the handler to be rearmed
879 signal(SIGCHLD, child_handler);
882 static int set_reuse_addr(int sockfd)
884 int on = 1;
886 if (!reuseaddr)
887 return 0;
888 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
889 &on, sizeof(on));
892 struct socketlist {
893 int *list;
894 size_t nr;
895 size_t alloc;
898 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
900 #ifdef NO_IPV6
901 static char ip[INET_ADDRSTRLEN];
902 #else
903 static char ip[INET6_ADDRSTRLEN];
904 #endif
906 switch (family) {
907 #ifndef NO_IPV6
908 case AF_INET6:
909 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
910 break;
911 #endif
912 case AF_INET:
913 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
914 break;
915 default:
916 xsnprintf(ip, sizeof(ip), "<unknown>");
918 return ip;
921 #ifndef NO_IPV6
923 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
925 int socknum = 0;
926 char pbuf[NI_MAXSERV];
927 struct addrinfo hints, *ai0, *ai;
928 int gai;
929 long flags;
931 xsnprintf(pbuf, sizeof(pbuf), "%d", listen_port);
932 memset(&hints, 0, sizeof(hints));
933 hints.ai_family = AF_UNSPEC;
934 hints.ai_socktype = SOCK_STREAM;
935 hints.ai_protocol = IPPROTO_TCP;
936 hints.ai_flags = AI_PASSIVE;
938 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
939 if (gai) {
940 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
941 return 0;
944 for (ai = ai0; ai; ai = ai->ai_next) {
945 int sockfd;
947 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
948 if (sockfd < 0)
949 continue;
950 if (sockfd >= FD_SETSIZE) {
951 logerror("Socket descriptor too large");
952 close(sockfd);
953 continue;
956 #ifdef IPV6_V6ONLY
957 if (ai->ai_family == AF_INET6) {
958 int on = 1;
959 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
960 &on, sizeof(on));
961 /* Note: error is not fatal */
963 #endif
965 if (set_reuse_addr(sockfd)) {
966 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
967 close(sockfd);
968 continue;
971 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
972 logerror("Could not bind to %s: %s",
973 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
974 strerror(errno));
975 close(sockfd);
976 continue; /* not fatal */
978 if (listen(sockfd, 5) < 0) {
979 logerror("Could not listen to %s: %s",
980 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
981 strerror(errno));
982 close(sockfd);
983 continue; /* not fatal */
986 flags = fcntl(sockfd, F_GETFD, 0);
987 if (flags >= 0)
988 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
990 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
991 socklist->list[socklist->nr++] = sockfd;
992 socknum++;
995 freeaddrinfo(ai0);
997 return socknum;
1000 #else /* NO_IPV6 */
1002 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
1004 struct sockaddr_in sin;
1005 int sockfd;
1006 long flags;
1008 memset(&sin, 0, sizeof sin);
1009 sin.sin_family = AF_INET;
1010 sin.sin_port = htons(listen_port);
1012 if (listen_addr) {
1013 /* Well, host better be an IP address here. */
1014 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
1015 return 0;
1016 } else {
1017 sin.sin_addr.s_addr = htonl(INADDR_ANY);
1020 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1021 if (sockfd < 0)
1022 return 0;
1024 if (set_reuse_addr(sockfd)) {
1025 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1026 close(sockfd);
1027 return 0;
1030 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
1031 logerror("Could not bind to %s: %s",
1032 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1033 strerror(errno));
1034 close(sockfd);
1035 return 0;
1038 if (listen(sockfd, 5) < 0) {
1039 logerror("Could not listen to %s: %s",
1040 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1041 strerror(errno));
1042 close(sockfd);
1043 return 0;
1046 flags = fcntl(sockfd, F_GETFD, 0);
1047 if (flags >= 0)
1048 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1050 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1051 socklist->list[socklist->nr++] = sockfd;
1052 return 1;
1055 #endif
1057 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
1059 if (!listen_addr->nr)
1060 setup_named_sock(NULL, listen_port, socklist);
1061 else {
1062 int i, socknum;
1063 for (i = 0; i < listen_addr->nr; i++) {
1064 socknum = setup_named_sock(listen_addr->items[i].string,
1065 listen_port, socklist);
1067 if (socknum == 0)
1068 logerror("unable to allocate any listen sockets for host %s on port %u",
1069 listen_addr->items[i].string, listen_port);
1074 static int service_loop(struct socketlist *socklist)
1076 struct pollfd *pfd;
1077 int i;
1079 pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
1081 for (i = 0; i < socklist->nr; i++) {
1082 pfd[i].fd = socklist->list[i];
1083 pfd[i].events = POLLIN;
1086 signal(SIGCHLD, child_handler);
1088 for (;;) {
1089 int i;
1091 check_dead_children();
1093 if (poll(pfd, socklist->nr, -1) < 0) {
1094 if (errno != EINTR) {
1095 logerror("Poll failed, resuming: %s",
1096 strerror(errno));
1097 sleep(1);
1099 continue;
1102 for (i = 0; i < socklist->nr; i++) {
1103 if (pfd[i].revents & POLLIN) {
1104 union {
1105 struct sockaddr sa;
1106 struct sockaddr_in sai;
1107 #ifndef NO_IPV6
1108 struct sockaddr_in6 sai6;
1109 #endif
1110 } ss;
1111 socklen_t sslen = sizeof(ss);
1112 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1113 if (incoming < 0) {
1114 switch (errno) {
1115 case EAGAIN:
1116 case EINTR:
1117 case ECONNABORTED:
1118 continue;
1119 default:
1120 die_errno("accept returned");
1123 handle(incoming, &ss.sa, sslen);
1129 #ifdef NO_POSIX_GOODIES
1131 struct credentials;
1133 static void drop_privileges(struct credentials *cred)
1135 /* nothing */
1138 static struct credentials *prepare_credentials(const char *user_name,
1139 const char *group_name)
1141 die("--user not supported on this platform");
1144 #else
1146 struct credentials {
1147 struct passwd *pass;
1148 gid_t gid;
1151 static void drop_privileges(struct credentials *cred)
1153 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1154 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1155 die("cannot drop privileges");
1158 static struct credentials *prepare_credentials(const char *user_name,
1159 const char *group_name)
1161 static struct credentials c;
1163 c.pass = getpwnam(user_name);
1164 if (!c.pass)
1165 die("user not found - %s", user_name);
1167 if (!group_name)
1168 c.gid = c.pass->pw_gid;
1169 else {
1170 struct group *group = getgrnam(group_name);
1171 if (!group)
1172 die("group not found - %s", group_name);
1174 c.gid = group->gr_gid;
1177 return &c;
1179 #endif
1181 static int serve(struct string_list *listen_addr, int listen_port,
1182 struct credentials *cred)
1184 struct socketlist socklist = { NULL, 0, 0 };
1186 socksetup(listen_addr, listen_port, &socklist);
1187 if (socklist.nr == 0)
1188 die("unable to allocate any listen sockets on port %u",
1189 listen_port);
1191 drop_privileges(cred);
1193 loginfo("Ready to rumble");
1195 return service_loop(&socklist);
1198 int main(int argc, char **argv)
1200 int listen_port = 0;
1201 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1202 int serve_mode = 0, inetd_mode = 0;
1203 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1204 int detach = 0;
1205 struct credentials *cred = NULL;
1206 int i;
1208 git_setup_gettext();
1210 git_extract_argv0_path(argv[0]);
1212 for (i = 1; i < argc; i++) {
1213 char *arg = argv[i];
1214 const char *v;
1216 if (skip_prefix(arg, "--listen=", &v)) {
1217 string_list_append(&listen_addr, xstrdup_tolower(v));
1218 continue;
1220 if (skip_prefix(arg, "--port=", &v)) {
1221 char *end;
1222 unsigned long n;
1223 n = strtoul(v, &end, 0);
1224 if (*v && !*end) {
1225 listen_port = n;
1226 continue;
1229 if (!strcmp(arg, "--serve")) {
1230 serve_mode = 1;
1231 continue;
1233 if (!strcmp(arg, "--inetd")) {
1234 inetd_mode = 1;
1235 log_syslog = 1;
1236 continue;
1238 if (!strcmp(arg, "--verbose")) {
1239 verbose = 1;
1240 continue;
1242 if (!strcmp(arg, "--syslog")) {
1243 log_syslog = 1;
1244 continue;
1246 if (!strcmp(arg, "--export-all")) {
1247 export_all_trees = 1;
1248 continue;
1250 if (skip_prefix(arg, "--access-hook=", &v)) {
1251 access_hook = v;
1252 continue;
1254 if (skip_prefix(arg, "--timeout=", &v)) {
1255 timeout = atoi(v);
1256 continue;
1258 if (skip_prefix(arg, "--init-timeout=", &v)) {
1259 init_timeout = atoi(v);
1260 continue;
1262 if (skip_prefix(arg, "--max-connections=", &v)) {
1263 max_connections = atoi(v);
1264 if (max_connections < 0)
1265 max_connections = 0; /* unlimited */
1266 continue;
1268 if (!strcmp(arg, "--strict-paths")) {
1269 strict_paths = 1;
1270 continue;
1272 if (skip_prefix(arg, "--base-path=", &v)) {
1273 base_path = v;
1274 continue;
1276 if (!strcmp(arg, "--base-path-relaxed")) {
1277 base_path_relaxed = 1;
1278 continue;
1280 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1281 interpolated_path = v;
1282 continue;
1284 if (!strcmp(arg, "--reuseaddr")) {
1285 reuseaddr = 1;
1286 continue;
1288 if (!strcmp(arg, "--user-path")) {
1289 user_path = "";
1290 continue;
1292 if (skip_prefix(arg, "--user-path=", &v)) {
1293 user_path = v;
1294 continue;
1296 if (skip_prefix(arg, "--pid-file=", &v)) {
1297 pid_file = v;
1298 continue;
1300 if (!strcmp(arg, "--detach")) {
1301 detach = 1;
1302 log_syslog = 1;
1303 continue;
1305 if (skip_prefix(arg, "--user=", &v)) {
1306 user_name = v;
1307 continue;
1309 if (skip_prefix(arg, "--group=", &v)) {
1310 group_name = v;
1311 continue;
1313 if (skip_prefix(arg, "--enable=", &v)) {
1314 enable_service(v, 1);
1315 continue;
1317 if (skip_prefix(arg, "--disable=", &v)) {
1318 enable_service(v, 0);
1319 continue;
1321 if (skip_prefix(arg, "--allow-override=", &v)) {
1322 make_service_overridable(v, 1);
1323 continue;
1325 if (skip_prefix(arg, "--forbid-override=", &v)) {
1326 make_service_overridable(v, 0);
1327 continue;
1329 if (!strcmp(arg, "--informative-errors")) {
1330 informative_errors = 1;
1331 continue;
1333 if (!strcmp(arg, "--no-informative-errors")) {
1334 informative_errors = 0;
1335 continue;
1337 if (!strcmp(arg, "--")) {
1338 ok_paths = &argv[i+1];
1339 break;
1340 } else if (arg[0] != '-') {
1341 ok_paths = &argv[i];
1342 break;
1345 usage(daemon_usage);
1348 if (log_syslog) {
1349 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1350 set_die_routine(daemon_die);
1351 } else
1352 /* avoid splitting a message in the middle */
1353 setvbuf(stderr, NULL, _IOFBF, 4096);
1355 if (inetd_mode && (detach || group_name || user_name))
1356 die("--detach, --user and --group are incompatible with --inetd");
1358 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1359 die("--listen= and --port= are incompatible with --inetd");
1360 else if (listen_port == 0)
1361 listen_port = DEFAULT_GIT_PORT;
1363 if (group_name && !user_name)
1364 die("--group supplied without --user");
1366 if (user_name)
1367 cred = prepare_credentials(user_name, group_name);
1369 if (strict_paths && (!ok_paths || !*ok_paths))
1370 die("option --strict-paths requires a whitelist");
1372 if (base_path && !is_directory(base_path))
1373 die("base-path '%s' does not exist or is not a directory",
1374 base_path);
1376 if (inetd_mode) {
1377 if (!freopen("/dev/null", "w", stderr))
1378 die_errno("failed to redirect stderr to /dev/null");
1381 if (inetd_mode || serve_mode)
1382 return execute();
1384 if (detach) {
1385 if (daemonize())
1386 die("--detach not supported on this platform");
1387 } else
1388 sanitize_stdfds();
1390 if (pid_file)
1391 write_file(pid_file, "%"PRIuMAX, (uintmax_t) getpid());
1393 /* prepare argv for serving-processes */
1394 argv_array_push(&cld_argv, argv[0]); /* git-daemon */
1395 argv_array_push(&cld_argv, "--serve");
1396 for (i = 1; i < argc; ++i)
1397 argv_array_push(&cld_argv, argv[i]);
1399 return serve(&listen_addr, listen_port, cred);