The eleventh batch
[git/gitster.git] / daemon.c
bloba40e435c6370cf1cfd2cef082184445f31748643
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "abspath.h"
5 #include "config.h"
6 #include "environment.h"
7 #include "gettext.h"
8 #include "path.h"
9 #include "pkt-line.h"
10 #include "protocol.h"
11 #include "run-command.h"
12 #include "setup.h"
13 #include "strbuf.h"
14 #include "string-list.h"
16 #ifdef NO_INITGROUPS
17 #define initgroups(x, y) (0) /* nothing */
18 #endif
20 static enum log_destination {
21 LOG_DESTINATION_UNSET = -1,
22 LOG_DESTINATION_NONE = 0,
23 LOG_DESTINATION_STDERR = 1,
24 LOG_DESTINATION_SYSLOG = 2,
25 } log_destination = LOG_DESTINATION_UNSET;
26 static int verbose;
27 static int reuseaddr;
28 static int informative_errors;
30 static const char daemon_usage[] =
31 "git daemon [--verbose] [--syslog] [--export-all]\n"
32 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
33 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
34 " [--user-path | --user-path=<path>]\n"
35 " [--interpolated-path=<path>]\n"
36 " [--reuseaddr] [--pid-file=<file>]\n"
37 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
38 " [--access-hook=<path>]\n"
39 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
40 " [--detach] [--user=<user> [--group=<group>]]\n"
41 " [--log-destination=(stderr|syslog|none)]\n"
42 " [<directory>...]";
44 /* List of acceptable pathname prefixes */
45 static const char **ok_paths;
46 static int strict_paths;
48 /* If this is set, git-daemon-export-ok is not required */
49 static int export_all_trees;
51 /* Take all paths relative to this one if non-NULL */
52 static const char *base_path;
53 static const char *interpolated_path;
54 static int base_path_relaxed;
56 /* If defined, ~user notation is allowed and the string is inserted
57 * after ~user/. E.g. a request to git://host/~alice/frotz would
58 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
60 static const char *user_path;
62 /* Timeout, and initial timeout */
63 static unsigned int timeout;
64 static unsigned int init_timeout;
66 struct hostinfo {
67 struct strbuf hostname;
68 struct strbuf canon_hostname;
69 struct strbuf ip_address;
70 struct strbuf tcp_port;
71 unsigned int hostname_lookup_done:1;
72 unsigned int saw_extended_args:1;
74 #define HOSTINFO_INIT { \
75 .hostname = STRBUF_INIT, \
76 .canon_hostname = STRBUF_INIT, \
77 .ip_address = STRBUF_INIT, \
78 .tcp_port = STRBUF_INIT, \
81 static void lookup_hostname(struct hostinfo *hi);
83 static const char *get_canon_hostname(struct hostinfo *hi)
85 lookup_hostname(hi);
86 return hi->canon_hostname.buf;
89 static const char *get_ip_address(struct hostinfo *hi)
91 lookup_hostname(hi);
92 return hi->ip_address.buf;
95 static void logreport(int priority, const char *err, va_list params)
97 switch (log_destination) {
98 case LOG_DESTINATION_SYSLOG: {
99 char buf[1024];
100 vsnprintf(buf, sizeof(buf), err, params);
101 syslog(priority, "%s", buf);
102 break;
104 case LOG_DESTINATION_STDERR:
106 * Since stderr is set to buffered mode, the
107 * logging of different processes will not overlap
108 * unless they overflow the (rather big) buffers.
110 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
111 vfprintf(stderr, err, params);
112 fputc('\n', stderr);
113 fflush(stderr);
114 break;
115 case LOG_DESTINATION_NONE:
116 break;
117 case LOG_DESTINATION_UNSET:
118 BUG("log destination not initialized correctly");
122 __attribute__((format (printf, 1, 2)))
123 static void logerror(const char *err, ...)
125 va_list params;
126 va_start(params, err);
127 logreport(LOG_ERR, err, params);
128 va_end(params);
131 __attribute__((format (printf, 1, 2)))
132 static void loginfo(const char *err, ...)
134 va_list params;
135 if (!verbose)
136 return;
137 va_start(params, err);
138 logreport(LOG_INFO, err, params);
139 va_end(params);
142 static void NORETURN daemon_die(const char *err, va_list params)
144 logreport(LOG_ERR, err, params);
145 exit(1);
148 static const char *path_ok(const char *directory, struct hostinfo *hi)
150 static char rpath[PATH_MAX];
151 static char interp_path[PATH_MAX];
152 size_t rlen;
153 const char *path;
154 const char *dir;
156 dir = directory;
158 if (daemon_avoid_alias(dir)) {
159 logerror("'%s': aliased", dir);
160 return NULL;
163 if (*dir == '~') {
164 if (!user_path) {
165 logerror("'%s': User-path not allowed", dir);
166 return NULL;
168 if (*user_path) {
169 /* Got either "~alice" or "~alice/foo";
170 * rewrite them to "~alice/%s" or
171 * "~alice/%s/foo".
173 int namlen, restlen = strlen(dir);
174 const char *slash = strchr(dir, '/');
175 if (!slash)
176 slash = dir + restlen;
177 namlen = slash - dir;
178 restlen -= namlen;
179 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
180 rlen = snprintf(rpath, sizeof(rpath), "%.*s/%s%.*s",
181 namlen, dir, user_path, restlen, slash);
182 if (rlen >= sizeof(rpath)) {
183 logerror("user-path too large: %s", rpath);
184 return NULL;
186 dir = rpath;
189 else if (interpolated_path && hi->saw_extended_args) {
190 struct strbuf expanded_path = STRBUF_INIT;
191 const char *format = interpolated_path;
193 if (*dir != '/') {
194 /* Allow only absolute */
195 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
196 return NULL;
199 while (strbuf_expand_step(&expanded_path, &format)) {
200 if (skip_prefix(format, "%", &format))
201 strbuf_addch(&expanded_path, '%');
202 else if (skip_prefix(format, "H", &format))
203 strbuf_addbuf(&expanded_path, &hi->hostname);
204 else if (skip_prefix(format, "CH", &format))
205 strbuf_addstr(&expanded_path,
206 get_canon_hostname(hi));
207 else if (skip_prefix(format, "IP", &format))
208 strbuf_addstr(&expanded_path,
209 get_ip_address(hi));
210 else if (skip_prefix(format, "P", &format))
211 strbuf_addbuf(&expanded_path, &hi->tcp_port);
212 else if (skip_prefix(format, "D", &format))
213 strbuf_addstr(&expanded_path, directory);
214 else
215 strbuf_addch(&expanded_path, '%');
218 rlen = strlcpy(interp_path, expanded_path.buf,
219 sizeof(interp_path));
220 strbuf_release(&expanded_path);
221 if (rlen >= sizeof(interp_path)) {
222 logerror("interpolated path too large: %s",
223 interp_path);
224 return NULL;
227 loginfo("Interpolated dir '%s'", interp_path);
229 dir = interp_path;
231 else if (base_path) {
232 if (*dir != '/') {
233 /* Allow only absolute */
234 logerror("'%s': Non-absolute path denied (base-path active)", dir);
235 return NULL;
237 rlen = snprintf(rpath, sizeof(rpath), "%s%s", base_path, dir);
238 if (rlen >= sizeof(rpath)) {
239 logerror("base-path too large: %s", rpath);
240 return NULL;
242 dir = rpath;
245 path = enter_repo(dir, strict_paths);
246 if (!path && base_path && base_path_relaxed) {
248 * if we fail and base_path_relaxed is enabled, try without
249 * prefixing the base path
251 dir = directory;
252 path = enter_repo(dir, strict_paths);
255 if (!path) {
256 logerror("'%s' does not appear to be a git repository", dir);
257 return NULL;
260 if ( ok_paths && *ok_paths ) {
261 const char **pp;
262 int pathlen = strlen(path);
264 /* The validation is done on the paths after enter_repo
265 * appends optional {.git,.git/.git} and friends, but
266 * it does not use getcwd(). So if your /pub is
267 * a symlink to /mnt/pub, you can include /pub and
268 * do not have to say /mnt/pub.
269 * Do not say /pub/.
271 for ( pp = ok_paths ; *pp ; pp++ ) {
272 int len = strlen(*pp);
273 if (len <= pathlen &&
274 !memcmp(*pp, path, len) &&
275 (path[len] == '\0' ||
276 (!strict_paths && path[len] == '/')))
277 return path;
280 else {
281 /* be backwards compatible */
282 if (!strict_paths)
283 return path;
286 logerror("'%s': not in directory list", path);
287 return NULL; /* Fallthrough. Deny by default */
290 typedef int (*daemon_service_fn)(const struct strvec *env);
291 struct daemon_service {
292 const char *name;
293 const char *config_name;
294 daemon_service_fn fn;
295 int enabled;
296 int overridable;
299 static int daemon_error(const char *dir, const char *msg)
301 if (!informative_errors)
302 msg = "access denied or repository not exported";
303 packet_write_fmt(1, "ERR %s: %s", msg, dir);
304 return -1;
307 static const char *access_hook;
309 static int run_access_hook(struct daemon_service *service, const char *dir,
310 const char *path, struct hostinfo *hi)
312 struct child_process child = CHILD_PROCESS_INIT;
313 struct strbuf buf = STRBUF_INIT;
314 char *eol;
315 int seen_errors = 0;
317 strvec_push(&child.args, access_hook);
318 strvec_push(&child.args, service->name);
319 strvec_push(&child.args, path);
320 strvec_push(&child.args, hi->hostname.buf);
321 strvec_push(&child.args, get_canon_hostname(hi));
322 strvec_push(&child.args, get_ip_address(hi));
323 strvec_push(&child.args, hi->tcp_port.buf);
325 child.use_shell = 1;
326 child.no_stdin = 1;
327 child.no_stderr = 1;
328 child.out = -1;
329 if (start_command(&child)) {
330 logerror("daemon access hook '%s' failed to start",
331 access_hook);
332 goto error_return;
334 if (strbuf_read(&buf, child.out, 0) < 0) {
335 logerror("failed to read from pipe to daemon access hook '%s'",
336 access_hook);
337 strbuf_reset(&buf);
338 seen_errors = 1;
340 if (close(child.out) < 0) {
341 logerror("failed to close pipe to daemon access hook '%s'",
342 access_hook);
343 seen_errors = 1;
345 if (finish_command(&child))
346 seen_errors = 1;
348 if (!seen_errors) {
349 strbuf_release(&buf);
350 return 0;
353 error_return:
354 strbuf_ltrim(&buf);
355 if (!buf.len)
356 strbuf_addstr(&buf, "service rejected");
357 eol = strchr(buf.buf, '\n');
358 if (eol)
359 *eol = '\0';
360 errno = EACCES;
361 daemon_error(dir, buf.buf);
362 strbuf_release(&buf);
363 return -1;
366 static int run_service(const char *dir, struct daemon_service *service,
367 struct hostinfo *hi, const struct strvec *env)
369 const char *path;
370 int enabled = service->enabled;
371 struct strbuf var = STRBUF_INIT;
373 loginfo("Request %s for '%s'", service->name, dir);
375 if (!enabled && !service->overridable) {
376 logerror("'%s': service not enabled.", service->name);
377 errno = EACCES;
378 return daemon_error(dir, "service not enabled");
381 if (!(path = path_ok(dir, hi)))
382 return daemon_error(dir, "no such repository");
385 * Security on the cheap.
387 * We want a readable HEAD, usable "objects" directory, and
388 * a "git-daemon-export-ok" flag that says that the other side
389 * is ok with us doing this.
391 * path_ok() uses enter_repo() and checks for included directories.
392 * We only need to make sure the repository is exported.
395 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
396 logerror("'%s': repository not exported.", path);
397 errno = EACCES;
398 return daemon_error(dir, "repository not exported");
401 if (service->overridable) {
402 strbuf_addf(&var, "daemon.%s", service->config_name);
403 git_config_get_bool(var.buf, &enabled);
404 strbuf_release(&var);
406 if (!enabled) {
407 logerror("'%s': service not enabled for '%s'",
408 service->name, path);
409 errno = EACCES;
410 return daemon_error(dir, "service not enabled");
414 * Optionally, a hook can choose to deny access to the
415 * repository depending on the phase of the moon.
417 if (access_hook && run_access_hook(service, dir, path, hi))
418 return -1;
421 * We'll ignore SIGTERM from now on, we have a
422 * good client.
424 signal(SIGTERM, SIG_IGN);
426 return service->fn(env);
429 static void copy_to_log(int fd)
431 struct strbuf line = STRBUF_INIT;
432 FILE *fp;
434 fp = fdopen(fd, "r");
435 if (!fp) {
436 logerror("fdopen of error channel failed");
437 close(fd);
438 return;
441 while (strbuf_getline_lf(&line, fp) != EOF) {
442 logerror("%s", line.buf);
443 strbuf_setlen(&line, 0);
446 strbuf_release(&line);
447 fclose(fp);
450 static int run_service_command(struct child_process *cld)
452 strvec_push(&cld->args, ".");
453 cld->git_cmd = 1;
454 cld->err = -1;
455 if (start_command(cld))
456 return -1;
458 close(0);
459 close(1);
461 copy_to_log(cld->err);
463 return finish_command(cld);
466 static int upload_pack(const struct strvec *env)
468 struct child_process cld = CHILD_PROCESS_INIT;
469 strvec_pushl(&cld.args, "upload-pack", "--strict", NULL);
470 strvec_pushf(&cld.args, "--timeout=%u", timeout);
472 strvec_pushv(&cld.env, env->v);
474 return run_service_command(&cld);
477 static int upload_archive(const struct strvec *env)
479 struct child_process cld = CHILD_PROCESS_INIT;
480 strvec_push(&cld.args, "upload-archive");
482 strvec_pushv(&cld.env, env->v);
484 return run_service_command(&cld);
487 static int receive_pack(const struct strvec *env)
489 struct child_process cld = CHILD_PROCESS_INIT;
490 strvec_push(&cld.args, "receive-pack");
492 strvec_pushv(&cld.env, env->v);
494 return run_service_command(&cld);
497 static struct daemon_service daemon_service[] = {
498 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
499 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
500 { "receive-pack", "receivepack", receive_pack, 0, 1 },
503 static void enable_service(const char *name, int ena)
505 int i;
506 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
507 if (!strcmp(daemon_service[i].name, name)) {
508 daemon_service[i].enabled = ena;
509 return;
512 die("No such service %s", name);
515 static void make_service_overridable(const char *name, int ena)
517 int i;
518 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
519 if (!strcmp(daemon_service[i].name, name)) {
520 daemon_service[i].overridable = ena;
521 return;
524 die("No such service %s", name);
527 static void parse_host_and_port(char *hostport, char **host,
528 char **port)
530 if (*hostport == '[') {
531 char *end;
533 end = strchr(hostport, ']');
534 if (!end)
535 die("Invalid request ('[' without ']')");
536 *end = '\0';
537 *host = hostport + 1;
538 if (!end[1])
539 *port = NULL;
540 else if (end[1] == ':')
541 *port = end + 2;
542 else
543 die("Garbage after end of host part");
544 } else {
545 *host = hostport;
546 *port = strrchr(hostport, ':');
547 if (*port) {
548 **port = '\0';
549 ++*port;
555 * Sanitize a string from the client so that it's OK to be inserted into a
556 * filesystem path. Specifically, we disallow directory separators, runs
557 * of "..", and trailing and leading dots, which means that the client
558 * cannot escape our base path via ".." traversal.
560 static void sanitize_client(struct strbuf *out, const char *in)
562 for (; *in; in++) {
563 if (is_dir_sep(*in))
564 continue;
565 if (*in == '.' && (!out->len || out->buf[out->len - 1] == '.'))
566 continue;
567 strbuf_addch(out, *in);
570 while (out->len && out->buf[out->len - 1] == '.')
571 strbuf_setlen(out, out->len - 1);
575 * Like sanitize_client, but we also perform any canonicalization
576 * to make life easier on the admin.
578 static void canonicalize_client(struct strbuf *out, const char *in)
580 sanitize_client(out, in);
581 strbuf_tolower(out);
585 * Read the host as supplied by the client connection.
587 * Returns a pointer to the character after the NUL byte terminating the host
588 * argument, or 'extra_args' if there is no host argument.
590 static char *parse_host_arg(struct hostinfo *hi, char *extra_args, int buflen)
592 char *val;
593 int vallen;
594 char *end = extra_args + buflen;
596 if (extra_args < end && *extra_args) {
597 hi->saw_extended_args = 1;
598 if (strncasecmp("host=", extra_args, 5) == 0) {
599 val = extra_args + 5;
600 vallen = strlen(val) + 1;
601 loginfo("Extended attribute \"host\": %s", val);
602 if (*val) {
603 /* Split <host>:<port> at colon. */
604 char *host;
605 char *port;
606 parse_host_and_port(val, &host, &port);
607 if (port)
608 sanitize_client(&hi->tcp_port, port);
609 canonicalize_client(&hi->hostname, host);
610 hi->hostname_lookup_done = 0;
613 /* On to the next one */
614 extra_args = val + vallen;
616 if (extra_args < end && *extra_args)
617 die("Invalid request");
620 return extra_args;
623 static void parse_extra_args(struct hostinfo *hi, struct strvec *env,
624 char *extra_args, int buflen)
626 const char *end = extra_args + buflen;
627 struct strbuf git_protocol = STRBUF_INIT;
629 /* First look for the host argument */
630 extra_args = parse_host_arg(hi, extra_args, buflen);
632 /* Look for additional arguments places after a second NUL byte */
633 for (; extra_args < end; extra_args += strlen(extra_args) + 1) {
634 const char *arg = extra_args;
637 * Parse the extra arguments, adding most to 'git_protocol'
638 * which will be used to set the 'GIT_PROTOCOL' envvar in the
639 * service that will be run.
641 * If there ends up being a particular arg in the future that
642 * git-daemon needs to parse specifically (like the 'host' arg)
643 * then it can be parsed here and not added to 'git_protocol'.
645 if (*arg) {
646 if (git_protocol.len > 0)
647 strbuf_addch(&git_protocol, ':');
648 strbuf_addstr(&git_protocol, arg);
652 if (git_protocol.len > 0) {
653 loginfo("Extended attribute \"protocol\": %s", git_protocol.buf);
654 strvec_pushf(env, GIT_PROTOCOL_ENVIRONMENT "=%s",
655 git_protocol.buf);
657 strbuf_release(&git_protocol);
661 * Locate canonical hostname and its IP address.
663 static void lookup_hostname(struct hostinfo *hi)
665 if (!hi->hostname_lookup_done && hi->hostname.len) {
666 #ifndef NO_IPV6
667 struct addrinfo hints;
668 struct addrinfo *ai;
669 int gai;
670 static char addrbuf[HOST_NAME_MAX + 1];
672 memset(&hints, 0, sizeof(hints));
673 hints.ai_flags = AI_CANONNAME;
675 gai = getaddrinfo(hi->hostname.buf, NULL, &hints, &ai);
676 if (!gai) {
677 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
679 inet_ntop(AF_INET, &sin_addr->sin_addr,
680 addrbuf, sizeof(addrbuf));
681 strbuf_addstr(&hi->ip_address, addrbuf);
683 if (ai->ai_canonname)
684 sanitize_client(&hi->canon_hostname,
685 ai->ai_canonname);
686 else
687 strbuf_addbuf(&hi->canon_hostname,
688 &hi->ip_address);
690 freeaddrinfo(ai);
692 #else
693 struct hostent *hent;
694 struct sockaddr_in sa;
695 char **ap;
696 static char addrbuf[HOST_NAME_MAX + 1];
698 hent = gethostbyname(hi->hostname.buf);
699 if (hent) {
700 ap = hent->h_addr_list;
701 memset(&sa, 0, sizeof sa);
702 sa.sin_family = hent->h_addrtype;
703 sa.sin_port = htons(0);
704 memcpy(&sa.sin_addr, *ap, hent->h_length);
706 inet_ntop(hent->h_addrtype, &sa.sin_addr,
707 addrbuf, sizeof(addrbuf));
709 sanitize_client(&hi->canon_hostname, hent->h_name);
710 strbuf_addstr(&hi->ip_address, addrbuf);
712 #endif
713 hi->hostname_lookup_done = 1;
717 static void hostinfo_clear(struct hostinfo *hi)
719 strbuf_release(&hi->hostname);
720 strbuf_release(&hi->canon_hostname);
721 strbuf_release(&hi->ip_address);
722 strbuf_release(&hi->tcp_port);
725 static void set_keep_alive(int sockfd)
727 int ka = 1;
729 if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0) {
730 if (errno != ENOTSOCK)
731 logerror("unable to set SO_KEEPALIVE on socket: %s",
732 strerror(errno));
736 static int execute(void)
738 char *line = packet_buffer;
739 int pktlen, len, i;
740 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
741 struct hostinfo hi = HOSTINFO_INIT;
742 struct strvec env = STRVEC_INIT;
744 if (addr)
745 loginfo("Connection from %s:%s", addr, port);
747 set_keep_alive(0);
748 alarm(init_timeout ? init_timeout : timeout);
749 pktlen = packet_read(0, packet_buffer, sizeof(packet_buffer), 0);
750 alarm(0);
752 len = strlen(line);
753 if (len && line[len-1] == '\n')
754 line[len-1] = 0;
756 /* parse additional args hidden behind a NUL byte */
757 if (len != pktlen)
758 parse_extra_args(&hi, &env, line + len + 1, pktlen - len - 1);
760 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
761 struct daemon_service *s = &(daemon_service[i]);
762 const char *arg;
764 if (skip_prefix(line, "git-", &arg) &&
765 skip_prefix(arg, s->name, &arg) &&
766 *arg++ == ' ') {
768 * Note: The directory here is probably context sensitive,
769 * and might depend on the actual service being performed.
771 int rc = run_service(arg, s, &hi, &env);
772 hostinfo_clear(&hi);
773 strvec_clear(&env);
774 return rc;
778 hostinfo_clear(&hi);
779 strvec_clear(&env);
780 logerror("Protocol error: '%s'", line);
781 return -1;
784 static int addrcmp(const struct sockaddr_storage *s1,
785 const struct sockaddr_storage *s2)
787 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
788 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
790 if (sa1->sa_family != sa2->sa_family)
791 return sa1->sa_family - sa2->sa_family;
792 if (sa1->sa_family == AF_INET)
793 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
794 &((struct sockaddr_in *)s2)->sin_addr,
795 sizeof(struct in_addr));
796 #ifndef NO_IPV6
797 if (sa1->sa_family == AF_INET6)
798 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
799 &((struct sockaddr_in6 *)s2)->sin6_addr,
800 sizeof(struct in6_addr));
801 #endif
802 return 0;
805 static int max_connections = 32;
807 static unsigned int live_children;
809 static struct child {
810 struct child *next;
811 struct child_process cld;
812 struct sockaddr_storage address;
813 } *firstborn;
815 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
817 struct child *newborn, **cradle;
819 CALLOC_ARRAY(newborn, 1);
820 live_children++;
821 memcpy(&newborn->cld, cld, sizeof(*cld));
822 memcpy(&newborn->address, addr, addrlen);
823 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
824 if (!addrcmp(&(*cradle)->address, &newborn->address))
825 break;
826 newborn->next = *cradle;
827 *cradle = newborn;
831 * This gets called if the number of connections grows
832 * past "max_connections".
834 * We kill the newest connection from a duplicate IP.
836 static void kill_some_child(void)
838 const struct child *blanket, *next;
840 if (!(blanket = firstborn))
841 return;
843 for (; (next = blanket->next); blanket = next)
844 if (!addrcmp(&blanket->address, &next->address)) {
845 kill(blanket->cld.pid, SIGTERM);
846 break;
850 static void check_dead_children(void)
852 int status;
853 pid_t pid;
855 struct child **cradle, *blanket;
856 for (cradle = &firstborn; (blanket = *cradle);)
857 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
858 const char *dead = "";
859 if (status)
860 dead = " (with error)";
861 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
863 /* remove the child */
864 *cradle = blanket->next;
865 live_children--;
866 child_process_clear(&blanket->cld);
867 free(blanket);
868 } else
869 cradle = &blanket->next;
872 static struct strvec cld_argv = STRVEC_INIT;
873 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
875 struct child_process cld = CHILD_PROCESS_INIT;
877 if (max_connections && live_children >= max_connections) {
878 kill_some_child();
879 sleep(1); /* give it some time to die */
880 check_dead_children();
881 if (live_children >= max_connections) {
882 close(incoming);
883 logerror("Too many children, dropping connection");
884 return;
888 if (addr->sa_family == AF_INET) {
889 char buf[128] = "";
890 struct sockaddr_in *sin_addr = (void *) addr;
891 inet_ntop(addr->sa_family, &sin_addr->sin_addr, buf, sizeof(buf));
892 strvec_pushf(&cld.env, "REMOTE_ADDR=%s", buf);
893 strvec_pushf(&cld.env, "REMOTE_PORT=%d",
894 ntohs(sin_addr->sin_port));
895 #ifndef NO_IPV6
896 } else if (addr->sa_family == AF_INET6) {
897 char buf[128] = "";
898 struct sockaddr_in6 *sin6_addr = (void *) addr;
899 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(buf));
900 strvec_pushf(&cld.env, "REMOTE_ADDR=[%s]", buf);
901 strvec_pushf(&cld.env, "REMOTE_PORT=%d",
902 ntohs(sin6_addr->sin6_port));
903 #endif
906 strvec_pushv(&cld.args, cld_argv.v);
907 cld.in = incoming;
908 cld.out = dup(incoming);
910 if (start_command(&cld))
911 logerror("unable to fork");
912 else
913 add_child(&cld, addr, addrlen);
916 static void child_handler(int signo UNUSED)
919 * Otherwise empty handler because systemcalls will get interrupted
920 * upon signal receipt
921 * SysV needs the handler to be rearmed
923 signal(SIGCHLD, child_handler);
926 static int set_reuse_addr(int sockfd)
928 int on = 1;
930 if (!reuseaddr)
931 return 0;
932 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
933 &on, sizeof(on));
936 struct socketlist {
937 int *list;
938 size_t nr;
939 size_t alloc;
942 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
944 #ifdef NO_IPV6
945 static char ip[INET_ADDRSTRLEN];
946 #else
947 static char ip[INET6_ADDRSTRLEN];
948 #endif
950 switch (family) {
951 #ifndef NO_IPV6
952 case AF_INET6:
953 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
954 break;
955 #endif
956 case AF_INET:
957 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
958 break;
959 default:
960 xsnprintf(ip, sizeof(ip), "<unknown>");
962 return ip;
965 #ifndef NO_IPV6
967 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
969 int socknum = 0;
970 char pbuf[NI_MAXSERV];
971 struct addrinfo hints, *ai0, *ai;
972 int gai;
973 long flags;
975 xsnprintf(pbuf, sizeof(pbuf), "%d", listen_port);
976 memset(&hints, 0, sizeof(hints));
977 hints.ai_family = AF_UNSPEC;
978 hints.ai_socktype = SOCK_STREAM;
979 hints.ai_protocol = IPPROTO_TCP;
980 hints.ai_flags = AI_PASSIVE;
982 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
983 if (gai) {
984 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
985 return 0;
988 for (ai = ai0; ai; ai = ai->ai_next) {
989 int sockfd;
991 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
992 if (sockfd < 0)
993 continue;
994 if (sockfd >= FD_SETSIZE) {
995 logerror("Socket descriptor too large");
996 close(sockfd);
997 continue;
1000 #ifdef IPV6_V6ONLY
1001 if (ai->ai_family == AF_INET6) {
1002 int on = 1;
1003 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
1004 &on, sizeof(on));
1005 /* Note: error is not fatal */
1007 #endif
1009 if (set_reuse_addr(sockfd)) {
1010 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1011 close(sockfd);
1012 continue;
1015 set_keep_alive(sockfd);
1017 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
1018 logerror("Could not bind to %s: %s",
1019 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
1020 strerror(errno));
1021 close(sockfd);
1022 continue; /* not fatal */
1024 if (listen(sockfd, 5) < 0) {
1025 logerror("Could not listen to %s: %s",
1026 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
1027 strerror(errno));
1028 close(sockfd);
1029 continue; /* not fatal */
1032 flags = fcntl(sockfd, F_GETFD, 0);
1033 if (flags >= 0)
1034 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1036 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1037 socklist->list[socklist->nr++] = sockfd;
1038 socknum++;
1041 freeaddrinfo(ai0);
1043 return socknum;
1046 #else /* NO_IPV6 */
1048 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
1050 struct sockaddr_in sin;
1051 int sockfd;
1052 long flags;
1054 memset(&sin, 0, sizeof sin);
1055 sin.sin_family = AF_INET;
1056 sin.sin_port = htons(listen_port);
1058 if (listen_addr) {
1059 /* Well, host better be an IP address here. */
1060 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
1061 return 0;
1062 } else {
1063 sin.sin_addr.s_addr = htonl(INADDR_ANY);
1066 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1067 if (sockfd < 0)
1068 return 0;
1070 if (set_reuse_addr(sockfd)) {
1071 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1072 close(sockfd);
1073 return 0;
1076 set_keep_alive(sockfd);
1078 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
1079 logerror("Could not bind to %s: %s",
1080 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1081 strerror(errno));
1082 close(sockfd);
1083 return 0;
1086 if (listen(sockfd, 5) < 0) {
1087 logerror("Could not listen to %s: %s",
1088 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1089 strerror(errno));
1090 close(sockfd);
1091 return 0;
1094 flags = fcntl(sockfd, F_GETFD, 0);
1095 if (flags >= 0)
1096 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1098 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1099 socklist->list[socklist->nr++] = sockfd;
1100 return 1;
1103 #endif
1105 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
1107 if (!listen_addr->nr)
1108 setup_named_sock(NULL, listen_port, socklist);
1109 else {
1110 int i, socknum;
1111 for (i = 0; i < listen_addr->nr; i++) {
1112 socknum = setup_named_sock(listen_addr->items[i].string,
1113 listen_port, socklist);
1115 if (socknum == 0)
1116 logerror("unable to allocate any listen sockets for host %s on port %u",
1117 listen_addr->items[i].string, listen_port);
1122 static int service_loop(struct socketlist *socklist)
1124 struct pollfd *pfd;
1125 int i;
1127 CALLOC_ARRAY(pfd, socklist->nr);
1129 for (i = 0; i < socklist->nr; i++) {
1130 pfd[i].fd = socklist->list[i];
1131 pfd[i].events = POLLIN;
1134 signal(SIGCHLD, child_handler);
1136 for (;;) {
1137 int i;
1139 check_dead_children();
1141 if (poll(pfd, socklist->nr, -1) < 0) {
1142 if (errno != EINTR) {
1143 logerror("Poll failed, resuming: %s",
1144 strerror(errno));
1145 sleep(1);
1147 continue;
1150 for (i = 0; i < socklist->nr; i++) {
1151 if (pfd[i].revents & POLLIN) {
1152 union {
1153 struct sockaddr sa;
1154 struct sockaddr_in sai;
1155 #ifndef NO_IPV6
1156 struct sockaddr_in6 sai6;
1157 #endif
1158 } ss;
1159 socklen_t sslen = sizeof(ss);
1160 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1161 if (incoming < 0) {
1162 switch (errno) {
1163 case EAGAIN:
1164 case EINTR:
1165 case ECONNABORTED:
1166 continue;
1167 default:
1168 die_errno("accept returned");
1171 handle(incoming, &ss.sa, sslen);
1177 #ifdef NO_POSIX_GOODIES
1179 struct credentials;
1181 static void drop_privileges(struct credentials *cred UNUSED)
1183 /* nothing */
1186 static struct credentials *prepare_credentials(const char *user_name UNUSED,
1187 const char *group_name UNUSED)
1189 die("--user not supported on this platform");
1192 #else
1194 struct credentials {
1195 struct passwd *pass;
1196 gid_t gid;
1199 static void drop_privileges(struct credentials *cred)
1201 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1202 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1203 die("cannot drop privileges");
1206 static struct credentials *prepare_credentials(const char *user_name,
1207 const char *group_name)
1209 static struct credentials c;
1211 c.pass = getpwnam(user_name);
1212 if (!c.pass)
1213 die("user not found - %s", user_name);
1215 if (!group_name)
1216 c.gid = c.pass->pw_gid;
1217 else {
1218 struct group *group = getgrnam(group_name);
1219 if (!group)
1220 die("group not found - %s", group_name);
1222 c.gid = group->gr_gid;
1225 return &c;
1227 #endif
1229 static int serve(struct string_list *listen_addr, int listen_port,
1230 struct credentials *cred)
1232 struct socketlist socklist = { NULL, 0, 0 };
1234 socksetup(listen_addr, listen_port, &socklist);
1235 if (socklist.nr == 0)
1236 die("unable to allocate any listen sockets on port %u",
1237 listen_port);
1239 drop_privileges(cred);
1241 loginfo("Ready to rumble");
1243 return service_loop(&socklist);
1246 int cmd_main(int argc, const char **argv)
1248 int listen_port = 0;
1249 struct string_list listen_addr = STRING_LIST_INIT_DUP;
1250 int serve_mode = 0, inetd_mode = 0;
1251 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1252 int detach = 0;
1253 struct credentials *cred = NULL;
1254 int i;
1255 int ret;
1257 for (i = 1; i < argc; i++) {
1258 const char *arg = argv[i];
1259 const char *v;
1261 if (skip_prefix(arg, "--listen=", &v)) {
1262 string_list_append_nodup(&listen_addr, xstrdup_tolower(v));
1263 continue;
1265 if (skip_prefix(arg, "--port=", &v)) {
1266 char *end;
1267 unsigned long n;
1268 n = strtoul(v, &end, 0);
1269 if (*v && !*end) {
1270 listen_port = n;
1271 continue;
1274 if (!strcmp(arg, "--serve")) {
1275 serve_mode = 1;
1276 continue;
1278 if (!strcmp(arg, "--inetd")) {
1279 inetd_mode = 1;
1280 continue;
1282 if (!strcmp(arg, "--verbose")) {
1283 verbose = 1;
1284 continue;
1286 if (!strcmp(arg, "--syslog")) {
1287 log_destination = LOG_DESTINATION_SYSLOG;
1288 continue;
1290 if (skip_prefix(arg, "--log-destination=", &v)) {
1291 if (!strcmp(v, "syslog")) {
1292 log_destination = LOG_DESTINATION_SYSLOG;
1293 continue;
1294 } else if (!strcmp(v, "stderr")) {
1295 log_destination = LOG_DESTINATION_STDERR;
1296 continue;
1297 } else if (!strcmp(v, "none")) {
1298 log_destination = LOG_DESTINATION_NONE;
1299 continue;
1300 } else
1301 die("unknown log destination '%s'", v);
1303 if (!strcmp(arg, "--export-all")) {
1304 export_all_trees = 1;
1305 continue;
1307 if (skip_prefix(arg, "--access-hook=", &v)) {
1308 access_hook = v;
1309 continue;
1311 if (skip_prefix(arg, "--timeout=", &v)) {
1312 if (strtoul_ui(v, 10, &timeout))
1313 die(_("invalid timeout '%s', expecting a non-negative integer"), v);
1314 continue;
1316 if (skip_prefix(arg, "--init-timeout=", &v)) {
1317 if (strtoul_ui(v, 10, &init_timeout))
1318 die(_("invalid init-timeout '%s', expecting a non-negative integer"), v);
1319 continue;
1321 if (skip_prefix(arg, "--max-connections=", &v)) {
1322 if (strtol_i(v, 10, &max_connections))
1323 die(_("invalid max-connections '%s', expecting an integer"), v);
1324 if (max_connections < 0)
1325 max_connections = 0; /* unlimited */
1326 continue;
1328 if (!strcmp(arg, "--strict-paths")) {
1329 strict_paths = 1;
1330 continue;
1332 if (skip_prefix(arg, "--base-path=", &v)) {
1333 base_path = v;
1334 continue;
1336 if (!strcmp(arg, "--base-path-relaxed")) {
1337 base_path_relaxed = 1;
1338 continue;
1340 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1341 interpolated_path = v;
1342 continue;
1344 if (!strcmp(arg, "--reuseaddr")) {
1345 reuseaddr = 1;
1346 continue;
1348 if (!strcmp(arg, "--user-path")) {
1349 user_path = "";
1350 continue;
1352 if (skip_prefix(arg, "--user-path=", &v)) {
1353 user_path = v;
1354 continue;
1356 if (skip_prefix(arg, "--pid-file=", &v)) {
1357 pid_file = v;
1358 continue;
1360 if (!strcmp(arg, "--detach")) {
1361 detach = 1;
1362 continue;
1364 if (skip_prefix(arg, "--user=", &v)) {
1365 user_name = v;
1366 continue;
1368 if (skip_prefix(arg, "--group=", &v)) {
1369 group_name = v;
1370 continue;
1372 if (skip_prefix(arg, "--enable=", &v)) {
1373 enable_service(v, 1);
1374 continue;
1376 if (skip_prefix(arg, "--disable=", &v)) {
1377 enable_service(v, 0);
1378 continue;
1380 if (skip_prefix(arg, "--allow-override=", &v)) {
1381 make_service_overridable(v, 1);
1382 continue;
1384 if (skip_prefix(arg, "--forbid-override=", &v)) {
1385 make_service_overridable(v, 0);
1386 continue;
1388 if (!strcmp(arg, "--informative-errors")) {
1389 informative_errors = 1;
1390 continue;
1392 if (!strcmp(arg, "--no-informative-errors")) {
1393 informative_errors = 0;
1394 continue;
1396 if (!strcmp(arg, "--")) {
1397 ok_paths = &argv[i+1];
1398 break;
1399 } else if (arg[0] != '-') {
1400 ok_paths = &argv[i];
1401 break;
1404 usage(daemon_usage);
1407 if (log_destination == LOG_DESTINATION_UNSET) {
1408 if (inetd_mode || detach)
1409 log_destination = LOG_DESTINATION_SYSLOG;
1410 else
1411 log_destination = LOG_DESTINATION_STDERR;
1414 if (log_destination == LOG_DESTINATION_SYSLOG) {
1415 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1416 set_die_routine(daemon_die);
1417 } else
1418 /* avoid splitting a message in the middle */
1419 setvbuf(stderr, NULL, _IOFBF, 4096);
1421 if (inetd_mode && (detach || group_name || user_name))
1422 die("--detach, --user and --group are incompatible with --inetd");
1424 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1425 die("--listen= and --port= are incompatible with --inetd");
1426 else if (listen_port == 0)
1427 listen_port = DEFAULT_GIT_PORT;
1429 if (group_name && !user_name)
1430 die("--group supplied without --user");
1432 if (user_name)
1433 cred = prepare_credentials(user_name, group_name);
1435 if (strict_paths && (!ok_paths || !*ok_paths))
1436 die("option --strict-paths requires '<directory>' arguments");
1438 if (base_path && !is_directory(base_path))
1439 die("base-path '%s' does not exist or is not a directory",
1440 base_path);
1442 if (log_destination != LOG_DESTINATION_STDERR) {
1443 if (!freopen("/dev/null", "w", stderr))
1444 die_errno("failed to redirect stderr to /dev/null");
1447 if (inetd_mode || serve_mode) {
1448 ret = execute();
1449 } else {
1450 if (detach) {
1451 if (daemonize())
1452 die("--detach not supported on this platform");
1455 if (pid_file)
1456 write_file(pid_file, "%"PRIuMAX, (uintmax_t) getpid());
1458 /* prepare argv for serving-processes */
1459 strvec_push(&cld_argv, argv[0]); /* git-daemon */
1460 strvec_push(&cld_argv, "--serve");
1461 for (i = 1; i < argc; ++i)
1462 strvec_push(&cld_argv, argv[i]);
1464 ret = serve(&listen_addr, listen_port, cred);
1467 string_list_clear(&listen_addr, 0);
1468 return ret;