Merge branch 'en/name-rev-make-taggerdate-much-less-important'
[git.git] / daemon.c
blob0ae7d12b5c132883907192d16c3e2f04d56a80fb
1 #include "cache.h"
2 #include "config.h"
3 #include "pkt-line.h"
4 #include "run-command.h"
5 #include "strbuf.h"
6 #include "string-list.h"
8 #ifdef NO_INITGROUPS
9 #define initgroups(x, y) (0) /* nothing */
10 #endif
12 static enum log_destination {
13 LOG_DESTINATION_UNSET = -1,
14 LOG_DESTINATION_NONE = 0,
15 LOG_DESTINATION_STDERR = 1,
16 LOG_DESTINATION_SYSLOG = 2,
17 } log_destination = LOG_DESTINATION_UNSET;
18 static int verbose;
19 static int reuseaddr;
20 static int informative_errors;
22 static const char daemon_usage[] =
23 "git daemon [--verbose] [--syslog] [--export-all]\n"
24 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
25 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
26 " [--user-path | --user-path=<path>]\n"
27 " [--interpolated-path=<path>]\n"
28 " [--reuseaddr] [--pid-file=<file>]\n"
29 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
30 " [--access-hook=<path>]\n"
31 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
32 " [--detach] [--user=<user> [--group=<group>]]\n"
33 " [--log-destination=(stderr|syslog|none)]\n"
34 " [<directory>...]";
36 /* List of acceptable pathname prefixes */
37 static const char **ok_paths;
38 static int strict_paths;
40 /* If this is set, git-daemon-export-ok is not required */
41 static int export_all_trees;
43 /* Take all paths relative to this one if non-NULL */
44 static const char *base_path;
45 static const char *interpolated_path;
46 static int base_path_relaxed;
48 /* If defined, ~user notation is allowed and the string is inserted
49 * after ~user/. E.g. a request to git://host/~alice/frotz would
50 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
52 static const char *user_path;
54 /* Timeout, and initial timeout */
55 static unsigned int timeout;
56 static unsigned int init_timeout;
58 struct hostinfo {
59 struct strbuf hostname;
60 struct strbuf canon_hostname;
61 struct strbuf ip_address;
62 struct strbuf tcp_port;
63 unsigned int hostname_lookup_done:1;
64 unsigned int saw_extended_args:1;
66 #define HOSTINFO_INIT { \
67 .hostname = STRBUF_INIT, \
68 .canon_hostname = STRBUF_INIT, \
69 .ip_address = STRBUF_INIT, \
70 .tcp_port = STRBUF_INIT, \
73 static void lookup_hostname(struct hostinfo *hi);
75 static const char *get_canon_hostname(struct hostinfo *hi)
77 lookup_hostname(hi);
78 return hi->canon_hostname.buf;
81 static const char *get_ip_address(struct hostinfo *hi)
83 lookup_hostname(hi);
84 return hi->ip_address.buf;
87 static void logreport(int priority, const char *err, va_list params)
89 switch (log_destination) {
90 case LOG_DESTINATION_SYSLOG: {
91 char buf[1024];
92 vsnprintf(buf, sizeof(buf), err, params);
93 syslog(priority, "%s", buf);
94 break;
96 case LOG_DESTINATION_STDERR:
98 * Since stderr is set to buffered mode, the
99 * logging of different processes will not overlap
100 * unless they overflow the (rather big) buffers.
102 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
103 vfprintf(stderr, err, params);
104 fputc('\n', stderr);
105 fflush(stderr);
106 break;
107 case LOG_DESTINATION_NONE:
108 break;
109 case LOG_DESTINATION_UNSET:
110 BUG("log destination not initialized correctly");
114 __attribute__((format (printf, 1, 2)))
115 static void logerror(const char *err, ...)
117 va_list params;
118 va_start(params, err);
119 logreport(LOG_ERR, err, params);
120 va_end(params);
123 __attribute__((format (printf, 1, 2)))
124 static void loginfo(const char *err, ...)
126 va_list params;
127 if (!verbose)
128 return;
129 va_start(params, err);
130 logreport(LOG_INFO, err, params);
131 va_end(params);
134 static void NORETURN daemon_die(const char *err, va_list params)
136 logreport(LOG_ERR, err, params);
137 exit(1);
140 struct expand_path_context {
141 const char *directory;
142 struct hostinfo *hostinfo;
145 static size_t expand_path(struct strbuf *sb, const char *placeholder, void *ctx)
147 struct expand_path_context *context = ctx;
148 struct hostinfo *hi = context->hostinfo;
150 switch (placeholder[0]) {
151 case 'H':
152 strbuf_addbuf(sb, &hi->hostname);
153 return 1;
154 case 'C':
155 if (placeholder[1] == 'H') {
156 strbuf_addstr(sb, get_canon_hostname(hi));
157 return 2;
159 break;
160 case 'I':
161 if (placeholder[1] == 'P') {
162 strbuf_addstr(sb, get_ip_address(hi));
163 return 2;
165 break;
166 case 'P':
167 strbuf_addbuf(sb, &hi->tcp_port);
168 return 1;
169 case 'D':
170 strbuf_addstr(sb, context->directory);
171 return 1;
173 return 0;
176 static const char *path_ok(const char *directory, struct hostinfo *hi)
178 static char rpath[PATH_MAX];
179 static char interp_path[PATH_MAX];
180 size_t rlen;
181 const char *path;
182 const char *dir;
184 dir = directory;
186 if (daemon_avoid_alias(dir)) {
187 logerror("'%s': aliased", dir);
188 return NULL;
191 if (*dir == '~') {
192 if (!user_path) {
193 logerror("'%s': User-path not allowed", dir);
194 return NULL;
196 if (*user_path) {
197 /* Got either "~alice" or "~alice/foo";
198 * rewrite them to "~alice/%s" or
199 * "~alice/%s/foo".
201 int namlen, restlen = strlen(dir);
202 const char *slash = strchr(dir, '/');
203 if (!slash)
204 slash = dir + restlen;
205 namlen = slash - dir;
206 restlen -= namlen;
207 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
208 rlen = snprintf(rpath, sizeof(rpath), "%.*s/%s%.*s",
209 namlen, dir, user_path, restlen, slash);
210 if (rlen >= sizeof(rpath)) {
211 logerror("user-path too large: %s", rpath);
212 return NULL;
214 dir = rpath;
217 else if (interpolated_path && hi->saw_extended_args) {
218 struct strbuf expanded_path = STRBUF_INIT;
219 struct expand_path_context context;
221 context.directory = directory;
222 context.hostinfo = hi;
224 if (*dir != '/') {
225 /* Allow only absolute */
226 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
227 return NULL;
230 strbuf_expand(&expanded_path, interpolated_path,
231 expand_path, &context);
233 rlen = strlcpy(interp_path, expanded_path.buf,
234 sizeof(interp_path));
235 strbuf_release(&expanded_path);
236 if (rlen >= sizeof(interp_path)) {
237 logerror("interpolated path too large: %s",
238 interp_path);
239 return NULL;
242 loginfo("Interpolated dir '%s'", interp_path);
244 dir = interp_path;
246 else if (base_path) {
247 if (*dir != '/') {
248 /* Allow only absolute */
249 logerror("'%s': Non-absolute path denied (base-path active)", dir);
250 return NULL;
252 rlen = snprintf(rpath, sizeof(rpath), "%s%s", base_path, dir);
253 if (rlen >= sizeof(rpath)) {
254 logerror("base-path too large: %s", rpath);
255 return NULL;
257 dir = rpath;
260 path = enter_repo(dir, strict_paths);
261 if (!path && base_path && base_path_relaxed) {
263 * if we fail and base_path_relaxed is enabled, try without
264 * prefixing the base path
266 dir = directory;
267 path = enter_repo(dir, strict_paths);
270 if (!path) {
271 logerror("'%s' does not appear to be a git repository", dir);
272 return NULL;
275 if ( ok_paths && *ok_paths ) {
276 const char **pp;
277 int pathlen = strlen(path);
279 /* The validation is done on the paths after enter_repo
280 * appends optional {.git,.git/.git} and friends, but
281 * it does not use getcwd(). So if your /pub is
282 * a symlink to /mnt/pub, you can include /pub and
283 * do not have to say /mnt/pub.
284 * Do not say /pub/.
286 for ( pp = ok_paths ; *pp ; pp++ ) {
287 int len = strlen(*pp);
288 if (len <= pathlen &&
289 !memcmp(*pp, path, len) &&
290 (path[len] == '\0' ||
291 (!strict_paths && path[len] == '/')))
292 return path;
295 else {
296 /* be backwards compatible */
297 if (!strict_paths)
298 return path;
301 logerror("'%s': not in directory list", path);
302 return NULL; /* Fallthrough. Deny by default */
305 typedef int (*daemon_service_fn)(const struct strvec *env);
306 struct daemon_service {
307 const char *name;
308 const char *config_name;
309 daemon_service_fn fn;
310 int enabled;
311 int overridable;
314 static int daemon_error(const char *dir, const char *msg)
316 if (!informative_errors)
317 msg = "access denied or repository not exported";
318 packet_write_fmt(1, "ERR %s: %s", msg, dir);
319 return -1;
322 static const char *access_hook;
324 static int run_access_hook(struct daemon_service *service, const char *dir,
325 const char *path, struct hostinfo *hi)
327 struct child_process child = CHILD_PROCESS_INIT;
328 struct strbuf buf = STRBUF_INIT;
329 char *eol;
330 int seen_errors = 0;
332 strvec_push(&child.args, access_hook);
333 strvec_push(&child.args, service->name);
334 strvec_push(&child.args, path);
335 strvec_push(&child.args, hi->hostname.buf);
336 strvec_push(&child.args, get_canon_hostname(hi));
337 strvec_push(&child.args, get_ip_address(hi));
338 strvec_push(&child.args, hi->tcp_port.buf);
340 child.use_shell = 1;
341 child.no_stdin = 1;
342 child.no_stderr = 1;
343 child.out = -1;
344 if (start_command(&child)) {
345 logerror("daemon access hook '%s' failed to start",
346 access_hook);
347 goto error_return;
349 if (strbuf_read(&buf, child.out, 0) < 0) {
350 logerror("failed to read from pipe to daemon access hook '%s'",
351 access_hook);
352 strbuf_reset(&buf);
353 seen_errors = 1;
355 if (close(child.out) < 0) {
356 logerror("failed to close pipe to daemon access hook '%s'",
357 access_hook);
358 seen_errors = 1;
360 if (finish_command(&child))
361 seen_errors = 1;
363 if (!seen_errors) {
364 strbuf_release(&buf);
365 return 0;
368 error_return:
369 strbuf_ltrim(&buf);
370 if (!buf.len)
371 strbuf_addstr(&buf, "service rejected");
372 eol = strchr(buf.buf, '\n');
373 if (eol)
374 *eol = '\0';
375 errno = EACCES;
376 daemon_error(dir, buf.buf);
377 strbuf_release(&buf);
378 return -1;
381 static int run_service(const char *dir, struct daemon_service *service,
382 struct hostinfo *hi, const struct strvec *env)
384 const char *path;
385 int enabled = service->enabled;
386 struct strbuf var = STRBUF_INIT;
388 loginfo("Request %s for '%s'", service->name, dir);
390 if (!enabled && !service->overridable) {
391 logerror("'%s': service not enabled.", service->name);
392 errno = EACCES;
393 return daemon_error(dir, "service not enabled");
396 if (!(path = path_ok(dir, hi)))
397 return daemon_error(dir, "no such repository");
400 * Security on the cheap.
402 * We want a readable HEAD, usable "objects" directory, and
403 * a "git-daemon-export-ok" flag that says that the other side
404 * is ok with us doing this.
406 * path_ok() uses enter_repo() and checks for included directories.
407 * We only need to make sure the repository is exported.
410 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
411 logerror("'%s': repository not exported.", path);
412 errno = EACCES;
413 return daemon_error(dir, "repository not exported");
416 if (service->overridable) {
417 strbuf_addf(&var, "daemon.%s", service->config_name);
418 git_config_get_bool(var.buf, &enabled);
419 strbuf_release(&var);
421 if (!enabled) {
422 logerror("'%s': service not enabled for '%s'",
423 service->name, path);
424 errno = EACCES;
425 return daemon_error(dir, "service not enabled");
429 * Optionally, a hook can choose to deny access to the
430 * repository depending on the phase of the moon.
432 if (access_hook && run_access_hook(service, dir, path, hi))
433 return -1;
436 * We'll ignore SIGTERM from now on, we have a
437 * good client.
439 signal(SIGTERM, SIG_IGN);
441 return service->fn(env);
444 static void copy_to_log(int fd)
446 struct strbuf line = STRBUF_INIT;
447 FILE *fp;
449 fp = fdopen(fd, "r");
450 if (!fp) {
451 logerror("fdopen of error channel failed");
452 close(fd);
453 return;
456 while (strbuf_getline_lf(&line, fp) != EOF) {
457 logerror("%s", line.buf);
458 strbuf_setlen(&line, 0);
461 strbuf_release(&line);
462 fclose(fp);
465 static int run_service_command(struct child_process *cld)
467 strvec_push(&cld->args, ".");
468 cld->git_cmd = 1;
469 cld->err = -1;
470 if (start_command(cld))
471 return -1;
473 close(0);
474 close(1);
476 copy_to_log(cld->err);
478 return finish_command(cld);
481 static int upload_pack(const struct strvec *env)
483 struct child_process cld = CHILD_PROCESS_INIT;
484 strvec_pushl(&cld.args, "upload-pack", "--strict", NULL);
485 strvec_pushf(&cld.args, "--timeout=%u", timeout);
487 strvec_pushv(&cld.env, env->v);
489 return run_service_command(&cld);
492 static int upload_archive(const struct strvec *env)
494 struct child_process cld = CHILD_PROCESS_INIT;
495 strvec_push(&cld.args, "upload-archive");
497 strvec_pushv(&cld.env, env->v);
499 return run_service_command(&cld);
502 static int receive_pack(const struct strvec *env)
504 struct child_process cld = CHILD_PROCESS_INIT;
505 strvec_push(&cld.args, "receive-pack");
507 strvec_pushv(&cld.env, env->v);
509 return run_service_command(&cld);
512 static struct daemon_service daemon_service[] = {
513 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
514 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
515 { "receive-pack", "receivepack", receive_pack, 0, 1 },
518 static void enable_service(const char *name, int ena)
520 int i;
521 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
522 if (!strcmp(daemon_service[i].name, name)) {
523 daemon_service[i].enabled = ena;
524 return;
527 die("No such service %s", name);
530 static void make_service_overridable(const char *name, int ena)
532 int i;
533 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
534 if (!strcmp(daemon_service[i].name, name)) {
535 daemon_service[i].overridable = ena;
536 return;
539 die("No such service %s", name);
542 static void parse_host_and_port(char *hostport, char **host,
543 char **port)
545 if (*hostport == '[') {
546 char *end;
548 end = strchr(hostport, ']');
549 if (!end)
550 die("Invalid request ('[' without ']')");
551 *end = '\0';
552 *host = hostport + 1;
553 if (!end[1])
554 *port = NULL;
555 else if (end[1] == ':')
556 *port = end + 2;
557 else
558 die("Garbage after end of host part");
559 } else {
560 *host = hostport;
561 *port = strrchr(hostport, ':');
562 if (*port) {
563 **port = '\0';
564 ++*port;
570 * Sanitize a string from the client so that it's OK to be inserted into a
571 * filesystem path. Specifically, we disallow directory separators, runs
572 * of "..", and trailing and leading dots, which means that the client
573 * cannot escape our base path via ".." traversal.
575 static void sanitize_client(struct strbuf *out, const char *in)
577 for (; *in; in++) {
578 if (is_dir_sep(*in))
579 continue;
580 if (*in == '.' && (!out->len || out->buf[out->len - 1] == '.'))
581 continue;
582 strbuf_addch(out, *in);
585 while (out->len && out->buf[out->len - 1] == '.')
586 strbuf_setlen(out, out->len - 1);
590 * Like sanitize_client, but we also perform any canonicalization
591 * to make life easier on the admin.
593 static void canonicalize_client(struct strbuf *out, const char *in)
595 sanitize_client(out, in);
596 strbuf_tolower(out);
600 * Read the host as supplied by the client connection.
602 * Returns a pointer to the character after the NUL byte terminating the host
603 * argument, or 'extra_args' if there is no host argument.
605 static char *parse_host_arg(struct hostinfo *hi, char *extra_args, int buflen)
607 char *val;
608 int vallen;
609 char *end = extra_args + buflen;
611 if (extra_args < end && *extra_args) {
612 hi->saw_extended_args = 1;
613 if (strncasecmp("host=", extra_args, 5) == 0) {
614 val = extra_args + 5;
615 vallen = strlen(val) + 1;
616 loginfo("Extended attribute \"host\": %s", val);
617 if (*val) {
618 /* Split <host>:<port> at colon. */
619 char *host;
620 char *port;
621 parse_host_and_port(val, &host, &port);
622 if (port)
623 sanitize_client(&hi->tcp_port, port);
624 canonicalize_client(&hi->hostname, host);
625 hi->hostname_lookup_done = 0;
628 /* On to the next one */
629 extra_args = val + vallen;
631 if (extra_args < end && *extra_args)
632 die("Invalid request");
635 return extra_args;
638 static void parse_extra_args(struct hostinfo *hi, struct strvec *env,
639 char *extra_args, int buflen)
641 const char *end = extra_args + buflen;
642 struct strbuf git_protocol = STRBUF_INIT;
644 /* First look for the host argument */
645 extra_args = parse_host_arg(hi, extra_args, buflen);
647 /* Look for additional arguments places after a second NUL byte */
648 for (; extra_args < end; extra_args += strlen(extra_args) + 1) {
649 const char *arg = extra_args;
652 * Parse the extra arguments, adding most to 'git_protocol'
653 * which will be used to set the 'GIT_PROTOCOL' envvar in the
654 * service that will be run.
656 * If there ends up being a particular arg in the future that
657 * git-daemon needs to parse specifically (like the 'host' arg)
658 * then it can be parsed here and not added to 'git_protocol'.
660 if (*arg) {
661 if (git_protocol.len > 0)
662 strbuf_addch(&git_protocol, ':');
663 strbuf_addstr(&git_protocol, arg);
667 if (git_protocol.len > 0) {
668 loginfo("Extended attribute \"protocol\": %s", git_protocol.buf);
669 strvec_pushf(env, GIT_PROTOCOL_ENVIRONMENT "=%s",
670 git_protocol.buf);
672 strbuf_release(&git_protocol);
676 * Locate canonical hostname and its IP address.
678 static void lookup_hostname(struct hostinfo *hi)
680 if (!hi->hostname_lookup_done && hi->hostname.len) {
681 #ifndef NO_IPV6
682 struct addrinfo hints;
683 struct addrinfo *ai;
684 int gai;
685 static char addrbuf[HOST_NAME_MAX + 1];
687 memset(&hints, 0, sizeof(hints));
688 hints.ai_flags = AI_CANONNAME;
690 gai = getaddrinfo(hi->hostname.buf, NULL, &hints, &ai);
691 if (!gai) {
692 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
694 inet_ntop(AF_INET, &sin_addr->sin_addr,
695 addrbuf, sizeof(addrbuf));
696 strbuf_addstr(&hi->ip_address, addrbuf);
698 if (ai->ai_canonname)
699 sanitize_client(&hi->canon_hostname,
700 ai->ai_canonname);
701 else
702 strbuf_addbuf(&hi->canon_hostname,
703 &hi->ip_address);
705 freeaddrinfo(ai);
707 #else
708 struct hostent *hent;
709 struct sockaddr_in sa;
710 char **ap;
711 static char addrbuf[HOST_NAME_MAX + 1];
713 hent = gethostbyname(hi->hostname.buf);
714 if (hent) {
715 ap = hent->h_addr_list;
716 memset(&sa, 0, sizeof sa);
717 sa.sin_family = hent->h_addrtype;
718 sa.sin_port = htons(0);
719 memcpy(&sa.sin_addr, *ap, hent->h_length);
721 inet_ntop(hent->h_addrtype, &sa.sin_addr,
722 addrbuf, sizeof(addrbuf));
724 sanitize_client(&hi->canon_hostname, hent->h_name);
725 strbuf_addstr(&hi->ip_address, addrbuf);
727 #endif
728 hi->hostname_lookup_done = 1;
732 static void hostinfo_clear(struct hostinfo *hi)
734 strbuf_release(&hi->hostname);
735 strbuf_release(&hi->canon_hostname);
736 strbuf_release(&hi->ip_address);
737 strbuf_release(&hi->tcp_port);
740 static void set_keep_alive(int sockfd)
742 int ka = 1;
744 if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0) {
745 if (errno != ENOTSOCK)
746 logerror("unable to set SO_KEEPALIVE on socket: %s",
747 strerror(errno));
751 static int execute(void)
753 char *line = packet_buffer;
754 int pktlen, len, i;
755 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
756 struct hostinfo hi = HOSTINFO_INIT;
757 struct strvec env = STRVEC_INIT;
759 if (addr)
760 loginfo("Connection from %s:%s", addr, port);
762 set_keep_alive(0);
763 alarm(init_timeout ? init_timeout : timeout);
764 pktlen = packet_read(0, packet_buffer, sizeof(packet_buffer), 0);
765 alarm(0);
767 len = strlen(line);
768 if (len && line[len-1] == '\n')
769 line[len-1] = 0;
771 /* parse additional args hidden behind a NUL byte */
772 if (len != pktlen)
773 parse_extra_args(&hi, &env, line + len + 1, pktlen - len - 1);
775 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
776 struct daemon_service *s = &(daemon_service[i]);
777 const char *arg;
779 if (skip_prefix(line, "git-", &arg) &&
780 skip_prefix(arg, s->name, &arg) &&
781 *arg++ == ' ') {
783 * Note: The directory here is probably context sensitive,
784 * and might depend on the actual service being performed.
786 int rc = run_service(arg, s, &hi, &env);
787 hostinfo_clear(&hi);
788 strvec_clear(&env);
789 return rc;
793 hostinfo_clear(&hi);
794 strvec_clear(&env);
795 logerror("Protocol error: '%s'", line);
796 return -1;
799 static int addrcmp(const struct sockaddr_storage *s1,
800 const struct sockaddr_storage *s2)
802 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
803 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
805 if (sa1->sa_family != sa2->sa_family)
806 return sa1->sa_family - sa2->sa_family;
807 if (sa1->sa_family == AF_INET)
808 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
809 &((struct sockaddr_in *)s2)->sin_addr,
810 sizeof(struct in_addr));
811 #ifndef NO_IPV6
812 if (sa1->sa_family == AF_INET6)
813 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
814 &((struct sockaddr_in6 *)s2)->sin6_addr,
815 sizeof(struct in6_addr));
816 #endif
817 return 0;
820 static int max_connections = 32;
822 static unsigned int live_children;
824 static struct child {
825 struct child *next;
826 struct child_process cld;
827 struct sockaddr_storage address;
828 } *firstborn;
830 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
832 struct child *newborn, **cradle;
834 CALLOC_ARRAY(newborn, 1);
835 live_children++;
836 memcpy(&newborn->cld, cld, sizeof(*cld));
837 memcpy(&newborn->address, addr, addrlen);
838 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
839 if (!addrcmp(&(*cradle)->address, &newborn->address))
840 break;
841 newborn->next = *cradle;
842 *cradle = newborn;
846 * This gets called if the number of connections grows
847 * past "max_connections".
849 * We kill the newest connection from a duplicate IP.
851 static void kill_some_child(void)
853 const struct child *blanket, *next;
855 if (!(blanket = firstborn))
856 return;
858 for (; (next = blanket->next); blanket = next)
859 if (!addrcmp(&blanket->address, &next->address)) {
860 kill(blanket->cld.pid, SIGTERM);
861 break;
865 static void check_dead_children(void)
867 int status;
868 pid_t pid;
870 struct child **cradle, *blanket;
871 for (cradle = &firstborn; (blanket = *cradle);)
872 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
873 const char *dead = "";
874 if (status)
875 dead = " (with error)";
876 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
878 /* remove the child */
879 *cradle = blanket->next;
880 live_children--;
881 child_process_clear(&blanket->cld);
882 free(blanket);
883 } else
884 cradle = &blanket->next;
887 static struct strvec cld_argv = STRVEC_INIT;
888 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
890 struct child_process cld = CHILD_PROCESS_INIT;
892 if (max_connections && live_children >= max_connections) {
893 kill_some_child();
894 sleep(1); /* give it some time to die */
895 check_dead_children();
896 if (live_children >= max_connections) {
897 close(incoming);
898 logerror("Too many children, dropping connection");
899 return;
903 if (addr->sa_family == AF_INET) {
904 char buf[128] = "";
905 struct sockaddr_in *sin_addr = (void *) addr;
906 inet_ntop(addr->sa_family, &sin_addr->sin_addr, buf, sizeof(buf));
907 strvec_pushf(&cld.env, "REMOTE_ADDR=%s", buf);
908 strvec_pushf(&cld.env, "REMOTE_PORT=%d",
909 ntohs(sin_addr->sin_port));
910 #ifndef NO_IPV6
911 } else if (addr->sa_family == AF_INET6) {
912 char buf[128] = "";
913 struct sockaddr_in6 *sin6_addr = (void *) addr;
914 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(buf));
915 strvec_pushf(&cld.env, "REMOTE_ADDR=[%s]", buf);
916 strvec_pushf(&cld.env, "REMOTE_PORT=%d",
917 ntohs(sin6_addr->sin6_port));
918 #endif
921 strvec_pushv(&cld.args, cld_argv.v);
922 cld.in = incoming;
923 cld.out = dup(incoming);
925 if (start_command(&cld))
926 logerror("unable to fork");
927 else
928 add_child(&cld, addr, addrlen);
931 static void child_handler(int signo)
934 * Otherwise empty handler because systemcalls will get interrupted
935 * upon signal receipt
936 * SysV needs the handler to be rearmed
938 signal(SIGCHLD, child_handler);
941 static int set_reuse_addr(int sockfd)
943 int on = 1;
945 if (!reuseaddr)
946 return 0;
947 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
948 &on, sizeof(on));
951 struct socketlist {
952 int *list;
953 size_t nr;
954 size_t alloc;
957 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
959 #ifdef NO_IPV6
960 static char ip[INET_ADDRSTRLEN];
961 #else
962 static char ip[INET6_ADDRSTRLEN];
963 #endif
965 switch (family) {
966 #ifndef NO_IPV6
967 case AF_INET6:
968 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
969 break;
970 #endif
971 case AF_INET:
972 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
973 break;
974 default:
975 xsnprintf(ip, sizeof(ip), "<unknown>");
977 return ip;
980 #ifndef NO_IPV6
982 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
984 int socknum = 0;
985 char pbuf[NI_MAXSERV];
986 struct addrinfo hints, *ai0, *ai;
987 int gai;
988 long flags;
990 xsnprintf(pbuf, sizeof(pbuf), "%d", listen_port);
991 memset(&hints, 0, sizeof(hints));
992 hints.ai_family = AF_UNSPEC;
993 hints.ai_socktype = SOCK_STREAM;
994 hints.ai_protocol = IPPROTO_TCP;
995 hints.ai_flags = AI_PASSIVE;
997 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
998 if (gai) {
999 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
1000 return 0;
1003 for (ai = ai0; ai; ai = ai->ai_next) {
1004 int sockfd;
1006 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1007 if (sockfd < 0)
1008 continue;
1009 if (sockfd >= FD_SETSIZE) {
1010 logerror("Socket descriptor too large");
1011 close(sockfd);
1012 continue;
1015 #ifdef IPV6_V6ONLY
1016 if (ai->ai_family == AF_INET6) {
1017 int on = 1;
1018 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
1019 &on, sizeof(on));
1020 /* Note: error is not fatal */
1022 #endif
1024 if (set_reuse_addr(sockfd)) {
1025 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1026 close(sockfd);
1027 continue;
1030 set_keep_alive(sockfd);
1032 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
1033 logerror("Could not bind to %s: %s",
1034 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
1035 strerror(errno));
1036 close(sockfd);
1037 continue; /* not fatal */
1039 if (listen(sockfd, 5) < 0) {
1040 logerror("Could not listen to %s: %s",
1041 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
1042 strerror(errno));
1043 close(sockfd);
1044 continue; /* not fatal */
1047 flags = fcntl(sockfd, F_GETFD, 0);
1048 if (flags >= 0)
1049 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1051 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1052 socklist->list[socklist->nr++] = sockfd;
1053 socknum++;
1056 freeaddrinfo(ai0);
1058 return socknum;
1061 #else /* NO_IPV6 */
1063 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
1065 struct sockaddr_in sin;
1066 int sockfd;
1067 long flags;
1069 memset(&sin, 0, sizeof sin);
1070 sin.sin_family = AF_INET;
1071 sin.sin_port = htons(listen_port);
1073 if (listen_addr) {
1074 /* Well, host better be an IP address here. */
1075 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
1076 return 0;
1077 } else {
1078 sin.sin_addr.s_addr = htonl(INADDR_ANY);
1081 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1082 if (sockfd < 0)
1083 return 0;
1085 if (set_reuse_addr(sockfd)) {
1086 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1087 close(sockfd);
1088 return 0;
1091 set_keep_alive(sockfd);
1093 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
1094 logerror("Could not bind to %s: %s",
1095 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1096 strerror(errno));
1097 close(sockfd);
1098 return 0;
1101 if (listen(sockfd, 5) < 0) {
1102 logerror("Could not listen to %s: %s",
1103 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1104 strerror(errno));
1105 close(sockfd);
1106 return 0;
1109 flags = fcntl(sockfd, F_GETFD, 0);
1110 if (flags >= 0)
1111 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1113 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1114 socklist->list[socklist->nr++] = sockfd;
1115 return 1;
1118 #endif
1120 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
1122 if (!listen_addr->nr)
1123 setup_named_sock(NULL, listen_port, socklist);
1124 else {
1125 int i, socknum;
1126 for (i = 0; i < listen_addr->nr; i++) {
1127 socknum = setup_named_sock(listen_addr->items[i].string,
1128 listen_port, socklist);
1130 if (socknum == 0)
1131 logerror("unable to allocate any listen sockets for host %s on port %u",
1132 listen_addr->items[i].string, listen_port);
1137 static int service_loop(struct socketlist *socklist)
1139 struct pollfd *pfd;
1140 int i;
1142 CALLOC_ARRAY(pfd, socklist->nr);
1144 for (i = 0; i < socklist->nr; i++) {
1145 pfd[i].fd = socklist->list[i];
1146 pfd[i].events = POLLIN;
1149 signal(SIGCHLD, child_handler);
1151 for (;;) {
1152 int i;
1154 check_dead_children();
1156 if (poll(pfd, socklist->nr, -1) < 0) {
1157 if (errno != EINTR) {
1158 logerror("Poll failed, resuming: %s",
1159 strerror(errno));
1160 sleep(1);
1162 continue;
1165 for (i = 0; i < socklist->nr; i++) {
1166 if (pfd[i].revents & POLLIN) {
1167 union {
1168 struct sockaddr sa;
1169 struct sockaddr_in sai;
1170 #ifndef NO_IPV6
1171 struct sockaddr_in6 sai6;
1172 #endif
1173 } ss;
1174 socklen_t sslen = sizeof(ss);
1175 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1176 if (incoming < 0) {
1177 switch (errno) {
1178 case EAGAIN:
1179 case EINTR:
1180 case ECONNABORTED:
1181 continue;
1182 default:
1183 die_errno("accept returned");
1186 handle(incoming, &ss.sa, sslen);
1192 #ifdef NO_POSIX_GOODIES
1194 struct credentials;
1196 static void drop_privileges(struct credentials *cred)
1198 /* nothing */
1201 static struct credentials *prepare_credentials(const char *user_name,
1202 const char *group_name)
1204 die("--user not supported on this platform");
1207 #else
1209 struct credentials {
1210 struct passwd *pass;
1211 gid_t gid;
1214 static void drop_privileges(struct credentials *cred)
1216 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1217 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1218 die("cannot drop privileges");
1221 static struct credentials *prepare_credentials(const char *user_name,
1222 const char *group_name)
1224 static struct credentials c;
1226 c.pass = getpwnam(user_name);
1227 if (!c.pass)
1228 die("user not found - %s", user_name);
1230 if (!group_name)
1231 c.gid = c.pass->pw_gid;
1232 else {
1233 struct group *group = getgrnam(group_name);
1234 if (!group)
1235 die("group not found - %s", group_name);
1237 c.gid = group->gr_gid;
1240 return &c;
1242 #endif
1244 static int serve(struct string_list *listen_addr, int listen_port,
1245 struct credentials *cred)
1247 struct socketlist socklist = { NULL, 0, 0 };
1249 socksetup(listen_addr, listen_port, &socklist);
1250 if (socklist.nr == 0)
1251 die("unable to allocate any listen sockets on port %u",
1252 listen_port);
1254 drop_privileges(cred);
1256 loginfo("Ready to rumble");
1258 return service_loop(&socklist);
1261 int cmd_main(int argc, const char **argv)
1263 int listen_port = 0;
1264 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1265 int serve_mode = 0, inetd_mode = 0;
1266 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1267 int detach = 0;
1268 struct credentials *cred = NULL;
1269 int i;
1271 for (i = 1; i < argc; i++) {
1272 const char *arg = argv[i];
1273 const char *v;
1275 if (skip_prefix(arg, "--listen=", &v)) {
1276 string_list_append(&listen_addr, xstrdup_tolower(v));
1277 continue;
1279 if (skip_prefix(arg, "--port=", &v)) {
1280 char *end;
1281 unsigned long n;
1282 n = strtoul(v, &end, 0);
1283 if (*v && !*end) {
1284 listen_port = n;
1285 continue;
1288 if (!strcmp(arg, "--serve")) {
1289 serve_mode = 1;
1290 continue;
1292 if (!strcmp(arg, "--inetd")) {
1293 inetd_mode = 1;
1294 continue;
1296 if (!strcmp(arg, "--verbose")) {
1297 verbose = 1;
1298 continue;
1300 if (!strcmp(arg, "--syslog")) {
1301 log_destination = LOG_DESTINATION_SYSLOG;
1302 continue;
1304 if (skip_prefix(arg, "--log-destination=", &v)) {
1305 if (!strcmp(v, "syslog")) {
1306 log_destination = LOG_DESTINATION_SYSLOG;
1307 continue;
1308 } else if (!strcmp(v, "stderr")) {
1309 log_destination = LOG_DESTINATION_STDERR;
1310 continue;
1311 } else if (!strcmp(v, "none")) {
1312 log_destination = LOG_DESTINATION_NONE;
1313 continue;
1314 } else
1315 die("unknown log destination '%s'", v);
1317 if (!strcmp(arg, "--export-all")) {
1318 export_all_trees = 1;
1319 continue;
1321 if (skip_prefix(arg, "--access-hook=", &v)) {
1322 access_hook = v;
1323 continue;
1325 if (skip_prefix(arg, "--timeout=", &v)) {
1326 timeout = atoi(v);
1327 continue;
1329 if (skip_prefix(arg, "--init-timeout=", &v)) {
1330 init_timeout = atoi(v);
1331 continue;
1333 if (skip_prefix(arg, "--max-connections=", &v)) {
1334 max_connections = atoi(v);
1335 if (max_connections < 0)
1336 max_connections = 0; /* unlimited */
1337 continue;
1339 if (!strcmp(arg, "--strict-paths")) {
1340 strict_paths = 1;
1341 continue;
1343 if (skip_prefix(arg, "--base-path=", &v)) {
1344 base_path = v;
1345 continue;
1347 if (!strcmp(arg, "--base-path-relaxed")) {
1348 base_path_relaxed = 1;
1349 continue;
1351 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1352 interpolated_path = v;
1353 continue;
1355 if (!strcmp(arg, "--reuseaddr")) {
1356 reuseaddr = 1;
1357 continue;
1359 if (!strcmp(arg, "--user-path")) {
1360 user_path = "";
1361 continue;
1363 if (skip_prefix(arg, "--user-path=", &v)) {
1364 user_path = v;
1365 continue;
1367 if (skip_prefix(arg, "--pid-file=", &v)) {
1368 pid_file = v;
1369 continue;
1371 if (!strcmp(arg, "--detach")) {
1372 detach = 1;
1373 continue;
1375 if (skip_prefix(arg, "--user=", &v)) {
1376 user_name = v;
1377 continue;
1379 if (skip_prefix(arg, "--group=", &v)) {
1380 group_name = v;
1381 continue;
1383 if (skip_prefix(arg, "--enable=", &v)) {
1384 enable_service(v, 1);
1385 continue;
1387 if (skip_prefix(arg, "--disable=", &v)) {
1388 enable_service(v, 0);
1389 continue;
1391 if (skip_prefix(arg, "--allow-override=", &v)) {
1392 make_service_overridable(v, 1);
1393 continue;
1395 if (skip_prefix(arg, "--forbid-override=", &v)) {
1396 make_service_overridable(v, 0);
1397 continue;
1399 if (!strcmp(arg, "--informative-errors")) {
1400 informative_errors = 1;
1401 continue;
1403 if (!strcmp(arg, "--no-informative-errors")) {
1404 informative_errors = 0;
1405 continue;
1407 if (!strcmp(arg, "--")) {
1408 ok_paths = &argv[i+1];
1409 break;
1410 } else if (arg[0] != '-') {
1411 ok_paths = &argv[i];
1412 break;
1415 usage(daemon_usage);
1418 if (log_destination == LOG_DESTINATION_UNSET) {
1419 if (inetd_mode || detach)
1420 log_destination = LOG_DESTINATION_SYSLOG;
1421 else
1422 log_destination = LOG_DESTINATION_STDERR;
1425 if (log_destination == LOG_DESTINATION_SYSLOG) {
1426 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1427 set_die_routine(daemon_die);
1428 } else
1429 /* avoid splitting a message in the middle */
1430 setvbuf(stderr, NULL, _IOFBF, 4096);
1432 if (inetd_mode && (detach || group_name || user_name))
1433 die("--detach, --user and --group are incompatible with --inetd");
1435 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1436 die("--listen= and --port= are incompatible with --inetd");
1437 else if (listen_port == 0)
1438 listen_port = DEFAULT_GIT_PORT;
1440 if (group_name && !user_name)
1441 die("--group supplied without --user");
1443 if (user_name)
1444 cred = prepare_credentials(user_name, group_name);
1446 if (strict_paths && (!ok_paths || !*ok_paths))
1447 die("option --strict-paths requires '<directory>' arguments");
1449 if (base_path && !is_directory(base_path))
1450 die("base-path '%s' does not exist or is not a directory",
1451 base_path);
1453 if (log_destination != LOG_DESTINATION_STDERR) {
1454 if (!freopen("/dev/null", "w", stderr))
1455 die_errno("failed to redirect stderr to /dev/null");
1458 if (inetd_mode || serve_mode)
1459 return execute();
1461 if (detach) {
1462 if (daemonize())
1463 die("--detach not supported on this platform");
1466 if (pid_file)
1467 write_file(pid_file, "%"PRIuMAX, (uintmax_t) getpid());
1469 /* prepare argv for serving-processes */
1470 strvec_push(&cld_argv, argv[0]); /* git-daemon */
1471 strvec_push(&cld_argv, "--serve");
1472 for (i = 1; i < argc; ++i)
1473 strvec_push(&cld_argv, argv[i]);
1475 return serve(&listen_addr, listen_port, cred);