cache.h: remove expand_user_path()
[git/debian.git] / daemon.c
blobbb795ca3ca9726c61fb75b7a275bb8c442cfc371
1 #include "cache.h"
2 #include "abspath.h"
3 #include "alloc.h"
4 #include "config.h"
5 #include "pkt-line.h"
6 #include "run-command.h"
7 #include "strbuf.h"
8 #include "string-list.h"
10 #ifdef NO_INITGROUPS
11 #define initgroups(x, y) (0) /* nothing */
12 #endif
14 static enum log_destination {
15 LOG_DESTINATION_UNSET = -1,
16 LOG_DESTINATION_NONE = 0,
17 LOG_DESTINATION_STDERR = 1,
18 LOG_DESTINATION_SYSLOG = 2,
19 } log_destination = LOG_DESTINATION_UNSET;
20 static int verbose;
21 static int reuseaddr;
22 static int informative_errors;
24 static const char daemon_usage[] =
25 "git daemon [--verbose] [--syslog] [--export-all]\n"
26 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
27 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
28 " [--user-path | --user-path=<path>]\n"
29 " [--interpolated-path=<path>]\n"
30 " [--reuseaddr] [--pid-file=<file>]\n"
31 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
32 " [--access-hook=<path>]\n"
33 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
34 " [--detach] [--user=<user> [--group=<group>]]\n"
35 " [--log-destination=(stderr|syslog|none)]\n"
36 " [<directory>...]";
38 /* List of acceptable pathname prefixes */
39 static const char **ok_paths;
40 static int strict_paths;
42 /* If this is set, git-daemon-export-ok is not required */
43 static int export_all_trees;
45 /* Take all paths relative to this one if non-NULL */
46 static const char *base_path;
47 static const char *interpolated_path;
48 static int base_path_relaxed;
50 /* If defined, ~user notation is allowed and the string is inserted
51 * after ~user/. E.g. a request to git://host/~alice/frotz would
52 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
54 static const char *user_path;
56 /* Timeout, and initial timeout */
57 static unsigned int timeout;
58 static unsigned int init_timeout;
60 struct hostinfo {
61 struct strbuf hostname;
62 struct strbuf canon_hostname;
63 struct strbuf ip_address;
64 struct strbuf tcp_port;
65 unsigned int hostname_lookup_done:1;
66 unsigned int saw_extended_args:1;
68 #define HOSTINFO_INIT { \
69 .hostname = STRBUF_INIT, \
70 .canon_hostname = STRBUF_INIT, \
71 .ip_address = STRBUF_INIT, \
72 .tcp_port = STRBUF_INIT, \
75 static void lookup_hostname(struct hostinfo *hi);
77 static const char *get_canon_hostname(struct hostinfo *hi)
79 lookup_hostname(hi);
80 return hi->canon_hostname.buf;
83 static const char *get_ip_address(struct hostinfo *hi)
85 lookup_hostname(hi);
86 return hi->ip_address.buf;
89 static void logreport(int priority, const char *err, va_list params)
91 switch (log_destination) {
92 case LOG_DESTINATION_SYSLOG: {
93 char buf[1024];
94 vsnprintf(buf, sizeof(buf), err, params);
95 syslog(priority, "%s", buf);
96 break;
98 case LOG_DESTINATION_STDERR:
100 * Since stderr is set to buffered mode, the
101 * logging of different processes will not overlap
102 * unless they overflow the (rather big) buffers.
104 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
105 vfprintf(stderr, err, params);
106 fputc('\n', stderr);
107 fflush(stderr);
108 break;
109 case LOG_DESTINATION_NONE:
110 break;
111 case LOG_DESTINATION_UNSET:
112 BUG("log destination not initialized correctly");
116 __attribute__((format (printf, 1, 2)))
117 static void logerror(const char *err, ...)
119 va_list params;
120 va_start(params, err);
121 logreport(LOG_ERR, err, params);
122 va_end(params);
125 __attribute__((format (printf, 1, 2)))
126 static void loginfo(const char *err, ...)
128 va_list params;
129 if (!verbose)
130 return;
131 va_start(params, err);
132 logreport(LOG_INFO, err, params);
133 va_end(params);
136 static void NORETURN daemon_die(const char *err, va_list params)
138 logreport(LOG_ERR, err, params);
139 exit(1);
142 struct expand_path_context {
143 const char *directory;
144 struct hostinfo *hostinfo;
147 static size_t expand_path(struct strbuf *sb, const char *placeholder, void *ctx)
149 struct expand_path_context *context = ctx;
150 struct hostinfo *hi = context->hostinfo;
152 switch (placeholder[0]) {
153 case 'H':
154 strbuf_addbuf(sb, &hi->hostname);
155 return 1;
156 case 'C':
157 if (placeholder[1] == 'H') {
158 strbuf_addstr(sb, get_canon_hostname(hi));
159 return 2;
161 break;
162 case 'I':
163 if (placeholder[1] == 'P') {
164 strbuf_addstr(sb, get_ip_address(hi));
165 return 2;
167 break;
168 case 'P':
169 strbuf_addbuf(sb, &hi->tcp_port);
170 return 1;
171 case 'D':
172 strbuf_addstr(sb, context->directory);
173 return 1;
175 return 0;
178 static const char *path_ok(const char *directory, struct hostinfo *hi)
180 static char rpath[PATH_MAX];
181 static char interp_path[PATH_MAX];
182 size_t rlen;
183 const char *path;
184 const char *dir;
186 dir = directory;
188 if (daemon_avoid_alias(dir)) {
189 logerror("'%s': aliased", dir);
190 return NULL;
193 if (*dir == '~') {
194 if (!user_path) {
195 logerror("'%s': User-path not allowed", dir);
196 return NULL;
198 if (*user_path) {
199 /* Got either "~alice" or "~alice/foo";
200 * rewrite them to "~alice/%s" or
201 * "~alice/%s/foo".
203 int namlen, restlen = strlen(dir);
204 const char *slash = strchr(dir, '/');
205 if (!slash)
206 slash = dir + restlen;
207 namlen = slash - dir;
208 restlen -= namlen;
209 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
210 rlen = snprintf(rpath, sizeof(rpath), "%.*s/%s%.*s",
211 namlen, dir, user_path, restlen, slash);
212 if (rlen >= sizeof(rpath)) {
213 logerror("user-path too large: %s", rpath);
214 return NULL;
216 dir = rpath;
219 else if (interpolated_path && hi->saw_extended_args) {
220 struct strbuf expanded_path = STRBUF_INIT;
221 struct expand_path_context context;
223 context.directory = directory;
224 context.hostinfo = hi;
226 if (*dir != '/') {
227 /* Allow only absolute */
228 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
229 return NULL;
232 strbuf_expand(&expanded_path, interpolated_path,
233 expand_path, &context);
235 rlen = strlcpy(interp_path, expanded_path.buf,
236 sizeof(interp_path));
237 strbuf_release(&expanded_path);
238 if (rlen >= sizeof(interp_path)) {
239 logerror("interpolated path too large: %s",
240 interp_path);
241 return NULL;
244 loginfo("Interpolated dir '%s'", interp_path);
246 dir = interp_path;
248 else if (base_path) {
249 if (*dir != '/') {
250 /* Allow only absolute */
251 logerror("'%s': Non-absolute path denied (base-path active)", dir);
252 return NULL;
254 rlen = snprintf(rpath, sizeof(rpath), "%s%s", base_path, dir);
255 if (rlen >= sizeof(rpath)) {
256 logerror("base-path too large: %s", rpath);
257 return NULL;
259 dir = rpath;
262 path = enter_repo(dir, strict_paths);
263 if (!path && base_path && base_path_relaxed) {
265 * if we fail and base_path_relaxed is enabled, try without
266 * prefixing the base path
268 dir = directory;
269 path = enter_repo(dir, strict_paths);
272 if (!path) {
273 logerror("'%s' does not appear to be a git repository", dir);
274 return NULL;
277 if ( ok_paths && *ok_paths ) {
278 const char **pp;
279 int pathlen = strlen(path);
281 /* The validation is done on the paths after enter_repo
282 * appends optional {.git,.git/.git} and friends, but
283 * it does not use getcwd(). So if your /pub is
284 * a symlink to /mnt/pub, you can include /pub and
285 * do not have to say /mnt/pub.
286 * Do not say /pub/.
288 for ( pp = ok_paths ; *pp ; pp++ ) {
289 int len = strlen(*pp);
290 if (len <= pathlen &&
291 !memcmp(*pp, path, len) &&
292 (path[len] == '\0' ||
293 (!strict_paths && path[len] == '/')))
294 return path;
297 else {
298 /* be backwards compatible */
299 if (!strict_paths)
300 return path;
303 logerror("'%s': not in directory list", path);
304 return NULL; /* Fallthrough. Deny by default */
307 typedef int (*daemon_service_fn)(const struct strvec *env);
308 struct daemon_service {
309 const char *name;
310 const char *config_name;
311 daemon_service_fn fn;
312 int enabled;
313 int overridable;
316 static int daemon_error(const char *dir, const char *msg)
318 if (!informative_errors)
319 msg = "access denied or repository not exported";
320 packet_write_fmt(1, "ERR %s: %s", msg, dir);
321 return -1;
324 static const char *access_hook;
326 static int run_access_hook(struct daemon_service *service, const char *dir,
327 const char *path, struct hostinfo *hi)
329 struct child_process child = CHILD_PROCESS_INIT;
330 struct strbuf buf = STRBUF_INIT;
331 char *eol;
332 int seen_errors = 0;
334 strvec_push(&child.args, access_hook);
335 strvec_push(&child.args, service->name);
336 strvec_push(&child.args, path);
337 strvec_push(&child.args, hi->hostname.buf);
338 strvec_push(&child.args, get_canon_hostname(hi));
339 strvec_push(&child.args, get_ip_address(hi));
340 strvec_push(&child.args, hi->tcp_port.buf);
342 child.use_shell = 1;
343 child.no_stdin = 1;
344 child.no_stderr = 1;
345 child.out = -1;
346 if (start_command(&child)) {
347 logerror("daemon access hook '%s' failed to start",
348 access_hook);
349 goto error_return;
351 if (strbuf_read(&buf, child.out, 0) < 0) {
352 logerror("failed to read from pipe to daemon access hook '%s'",
353 access_hook);
354 strbuf_reset(&buf);
355 seen_errors = 1;
357 if (close(child.out) < 0) {
358 logerror("failed to close pipe to daemon access hook '%s'",
359 access_hook);
360 seen_errors = 1;
362 if (finish_command(&child))
363 seen_errors = 1;
365 if (!seen_errors) {
366 strbuf_release(&buf);
367 return 0;
370 error_return:
371 strbuf_ltrim(&buf);
372 if (!buf.len)
373 strbuf_addstr(&buf, "service rejected");
374 eol = strchr(buf.buf, '\n');
375 if (eol)
376 *eol = '\0';
377 errno = EACCES;
378 daemon_error(dir, buf.buf);
379 strbuf_release(&buf);
380 return -1;
383 static int run_service(const char *dir, struct daemon_service *service,
384 struct hostinfo *hi, const struct strvec *env)
386 const char *path;
387 int enabled = service->enabled;
388 struct strbuf var = STRBUF_INIT;
390 loginfo("Request %s for '%s'", service->name, dir);
392 if (!enabled && !service->overridable) {
393 logerror("'%s': service not enabled.", service->name);
394 errno = EACCES;
395 return daemon_error(dir, "service not enabled");
398 if (!(path = path_ok(dir, hi)))
399 return daemon_error(dir, "no such repository");
402 * Security on the cheap.
404 * We want a readable HEAD, usable "objects" directory, and
405 * a "git-daemon-export-ok" flag that says that the other side
406 * is ok with us doing this.
408 * path_ok() uses enter_repo() and checks for included directories.
409 * We only need to make sure the repository is exported.
412 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
413 logerror("'%s': repository not exported.", path);
414 errno = EACCES;
415 return daemon_error(dir, "repository not exported");
418 if (service->overridable) {
419 strbuf_addf(&var, "daemon.%s", service->config_name);
420 git_config_get_bool(var.buf, &enabled);
421 strbuf_release(&var);
423 if (!enabled) {
424 logerror("'%s': service not enabled for '%s'",
425 service->name, path);
426 errno = EACCES;
427 return daemon_error(dir, "service not enabled");
431 * Optionally, a hook can choose to deny access to the
432 * repository depending on the phase of the moon.
434 if (access_hook && run_access_hook(service, dir, path, hi))
435 return -1;
438 * We'll ignore SIGTERM from now on, we have a
439 * good client.
441 signal(SIGTERM, SIG_IGN);
443 return service->fn(env);
446 static void copy_to_log(int fd)
448 struct strbuf line = STRBUF_INIT;
449 FILE *fp;
451 fp = fdopen(fd, "r");
452 if (!fp) {
453 logerror("fdopen of error channel failed");
454 close(fd);
455 return;
458 while (strbuf_getline_lf(&line, fp) != EOF) {
459 logerror("%s", line.buf);
460 strbuf_setlen(&line, 0);
463 strbuf_release(&line);
464 fclose(fp);
467 static int run_service_command(struct child_process *cld)
469 strvec_push(&cld->args, ".");
470 cld->git_cmd = 1;
471 cld->err = -1;
472 if (start_command(cld))
473 return -1;
475 close(0);
476 close(1);
478 copy_to_log(cld->err);
480 return finish_command(cld);
483 static int upload_pack(const struct strvec *env)
485 struct child_process cld = CHILD_PROCESS_INIT;
486 strvec_pushl(&cld.args, "upload-pack", "--strict", NULL);
487 strvec_pushf(&cld.args, "--timeout=%u", timeout);
489 strvec_pushv(&cld.env, env->v);
491 return run_service_command(&cld);
494 static int upload_archive(const struct strvec *env)
496 struct child_process cld = CHILD_PROCESS_INIT;
497 strvec_push(&cld.args, "upload-archive");
499 strvec_pushv(&cld.env, env->v);
501 return run_service_command(&cld);
504 static int receive_pack(const struct strvec *env)
506 struct child_process cld = CHILD_PROCESS_INIT;
507 strvec_push(&cld.args, "receive-pack");
509 strvec_pushv(&cld.env, env->v);
511 return run_service_command(&cld);
514 static struct daemon_service daemon_service[] = {
515 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
516 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
517 { "receive-pack", "receivepack", receive_pack, 0, 1 },
520 static void enable_service(const char *name, int ena)
522 int i;
523 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
524 if (!strcmp(daemon_service[i].name, name)) {
525 daemon_service[i].enabled = ena;
526 return;
529 die("No such service %s", name);
532 static void make_service_overridable(const char *name, int ena)
534 int i;
535 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
536 if (!strcmp(daemon_service[i].name, name)) {
537 daemon_service[i].overridable = ena;
538 return;
541 die("No such service %s", name);
544 static void parse_host_and_port(char *hostport, char **host,
545 char **port)
547 if (*hostport == '[') {
548 char *end;
550 end = strchr(hostport, ']');
551 if (!end)
552 die("Invalid request ('[' without ']')");
553 *end = '\0';
554 *host = hostport + 1;
555 if (!end[1])
556 *port = NULL;
557 else if (end[1] == ':')
558 *port = end + 2;
559 else
560 die("Garbage after end of host part");
561 } else {
562 *host = hostport;
563 *port = strrchr(hostport, ':');
564 if (*port) {
565 **port = '\0';
566 ++*port;
572 * Sanitize a string from the client so that it's OK to be inserted into a
573 * filesystem path. Specifically, we disallow directory separators, runs
574 * of "..", and trailing and leading dots, which means that the client
575 * cannot escape our base path via ".." traversal.
577 static void sanitize_client(struct strbuf *out, const char *in)
579 for (; *in; in++) {
580 if (is_dir_sep(*in))
581 continue;
582 if (*in == '.' && (!out->len || out->buf[out->len - 1] == '.'))
583 continue;
584 strbuf_addch(out, *in);
587 while (out->len && out->buf[out->len - 1] == '.')
588 strbuf_setlen(out, out->len - 1);
592 * Like sanitize_client, but we also perform any canonicalization
593 * to make life easier on the admin.
595 static void canonicalize_client(struct strbuf *out, const char *in)
597 sanitize_client(out, in);
598 strbuf_tolower(out);
602 * Read the host as supplied by the client connection.
604 * Returns a pointer to the character after the NUL byte terminating the host
605 * argument, or 'extra_args' if there is no host argument.
607 static char *parse_host_arg(struct hostinfo *hi, char *extra_args, int buflen)
609 char *val;
610 int vallen;
611 char *end = extra_args + buflen;
613 if (extra_args < end && *extra_args) {
614 hi->saw_extended_args = 1;
615 if (strncasecmp("host=", extra_args, 5) == 0) {
616 val = extra_args + 5;
617 vallen = strlen(val) + 1;
618 loginfo("Extended attribute \"host\": %s", val);
619 if (*val) {
620 /* Split <host>:<port> at colon. */
621 char *host;
622 char *port;
623 parse_host_and_port(val, &host, &port);
624 if (port)
625 sanitize_client(&hi->tcp_port, port);
626 canonicalize_client(&hi->hostname, host);
627 hi->hostname_lookup_done = 0;
630 /* On to the next one */
631 extra_args = val + vallen;
633 if (extra_args < end && *extra_args)
634 die("Invalid request");
637 return extra_args;
640 static void parse_extra_args(struct hostinfo *hi, struct strvec *env,
641 char *extra_args, int buflen)
643 const char *end = extra_args + buflen;
644 struct strbuf git_protocol = STRBUF_INIT;
646 /* First look for the host argument */
647 extra_args = parse_host_arg(hi, extra_args, buflen);
649 /* Look for additional arguments places after a second NUL byte */
650 for (; extra_args < end; extra_args += strlen(extra_args) + 1) {
651 const char *arg = extra_args;
654 * Parse the extra arguments, adding most to 'git_protocol'
655 * which will be used to set the 'GIT_PROTOCOL' envvar in the
656 * service that will be run.
658 * If there ends up being a particular arg in the future that
659 * git-daemon needs to parse specifically (like the 'host' arg)
660 * then it can be parsed here and not added to 'git_protocol'.
662 if (*arg) {
663 if (git_protocol.len > 0)
664 strbuf_addch(&git_protocol, ':');
665 strbuf_addstr(&git_protocol, arg);
669 if (git_protocol.len > 0) {
670 loginfo("Extended attribute \"protocol\": %s", git_protocol.buf);
671 strvec_pushf(env, GIT_PROTOCOL_ENVIRONMENT "=%s",
672 git_protocol.buf);
674 strbuf_release(&git_protocol);
678 * Locate canonical hostname and its IP address.
680 static void lookup_hostname(struct hostinfo *hi)
682 if (!hi->hostname_lookup_done && hi->hostname.len) {
683 #ifndef NO_IPV6
684 struct addrinfo hints;
685 struct addrinfo *ai;
686 int gai;
687 static char addrbuf[HOST_NAME_MAX + 1];
689 memset(&hints, 0, sizeof(hints));
690 hints.ai_flags = AI_CANONNAME;
692 gai = getaddrinfo(hi->hostname.buf, NULL, &hints, &ai);
693 if (!gai) {
694 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
696 inet_ntop(AF_INET, &sin_addr->sin_addr,
697 addrbuf, sizeof(addrbuf));
698 strbuf_addstr(&hi->ip_address, addrbuf);
700 if (ai->ai_canonname)
701 sanitize_client(&hi->canon_hostname,
702 ai->ai_canonname);
703 else
704 strbuf_addbuf(&hi->canon_hostname,
705 &hi->ip_address);
707 freeaddrinfo(ai);
709 #else
710 struct hostent *hent;
711 struct sockaddr_in sa;
712 char **ap;
713 static char addrbuf[HOST_NAME_MAX + 1];
715 hent = gethostbyname(hi->hostname.buf);
716 if (hent) {
717 ap = hent->h_addr_list;
718 memset(&sa, 0, sizeof sa);
719 sa.sin_family = hent->h_addrtype;
720 sa.sin_port = htons(0);
721 memcpy(&sa.sin_addr, *ap, hent->h_length);
723 inet_ntop(hent->h_addrtype, &sa.sin_addr,
724 addrbuf, sizeof(addrbuf));
726 sanitize_client(&hi->canon_hostname, hent->h_name);
727 strbuf_addstr(&hi->ip_address, addrbuf);
729 #endif
730 hi->hostname_lookup_done = 1;
734 static void hostinfo_clear(struct hostinfo *hi)
736 strbuf_release(&hi->hostname);
737 strbuf_release(&hi->canon_hostname);
738 strbuf_release(&hi->ip_address);
739 strbuf_release(&hi->tcp_port);
742 static void set_keep_alive(int sockfd)
744 int ka = 1;
746 if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0) {
747 if (errno != ENOTSOCK)
748 logerror("unable to set SO_KEEPALIVE on socket: %s",
749 strerror(errno));
753 static int execute(void)
755 char *line = packet_buffer;
756 int pktlen, len, i;
757 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
758 struct hostinfo hi = HOSTINFO_INIT;
759 struct strvec env = STRVEC_INIT;
761 if (addr)
762 loginfo("Connection from %s:%s", addr, port);
764 set_keep_alive(0);
765 alarm(init_timeout ? init_timeout : timeout);
766 pktlen = packet_read(0, packet_buffer, sizeof(packet_buffer), 0);
767 alarm(0);
769 len = strlen(line);
770 if (len && line[len-1] == '\n')
771 line[len-1] = 0;
773 /* parse additional args hidden behind a NUL byte */
774 if (len != pktlen)
775 parse_extra_args(&hi, &env, line + len + 1, pktlen - len - 1);
777 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
778 struct daemon_service *s = &(daemon_service[i]);
779 const char *arg;
781 if (skip_prefix(line, "git-", &arg) &&
782 skip_prefix(arg, s->name, &arg) &&
783 *arg++ == ' ') {
785 * Note: The directory here is probably context sensitive,
786 * and might depend on the actual service being performed.
788 int rc = run_service(arg, s, &hi, &env);
789 hostinfo_clear(&hi);
790 strvec_clear(&env);
791 return rc;
795 hostinfo_clear(&hi);
796 strvec_clear(&env);
797 logerror("Protocol error: '%s'", line);
798 return -1;
801 static int addrcmp(const struct sockaddr_storage *s1,
802 const struct sockaddr_storage *s2)
804 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
805 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
807 if (sa1->sa_family != sa2->sa_family)
808 return sa1->sa_family - sa2->sa_family;
809 if (sa1->sa_family == AF_INET)
810 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
811 &((struct sockaddr_in *)s2)->sin_addr,
812 sizeof(struct in_addr));
813 #ifndef NO_IPV6
814 if (sa1->sa_family == AF_INET6)
815 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
816 &((struct sockaddr_in6 *)s2)->sin6_addr,
817 sizeof(struct in6_addr));
818 #endif
819 return 0;
822 static int max_connections = 32;
824 static unsigned int live_children;
826 static struct child {
827 struct child *next;
828 struct child_process cld;
829 struct sockaddr_storage address;
830 } *firstborn;
832 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
834 struct child *newborn, **cradle;
836 CALLOC_ARRAY(newborn, 1);
837 live_children++;
838 memcpy(&newborn->cld, cld, sizeof(*cld));
839 memcpy(&newborn->address, addr, addrlen);
840 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
841 if (!addrcmp(&(*cradle)->address, &newborn->address))
842 break;
843 newborn->next = *cradle;
844 *cradle = newborn;
848 * This gets called if the number of connections grows
849 * past "max_connections".
851 * We kill the newest connection from a duplicate IP.
853 static void kill_some_child(void)
855 const struct child *blanket, *next;
857 if (!(blanket = firstborn))
858 return;
860 for (; (next = blanket->next); blanket = next)
861 if (!addrcmp(&blanket->address, &next->address)) {
862 kill(blanket->cld.pid, SIGTERM);
863 break;
867 static void check_dead_children(void)
869 int status;
870 pid_t pid;
872 struct child **cradle, *blanket;
873 for (cradle = &firstborn; (blanket = *cradle);)
874 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
875 const char *dead = "";
876 if (status)
877 dead = " (with error)";
878 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
880 /* remove the child */
881 *cradle = blanket->next;
882 live_children--;
883 child_process_clear(&blanket->cld);
884 free(blanket);
885 } else
886 cradle = &blanket->next;
889 static struct strvec cld_argv = STRVEC_INIT;
890 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
892 struct child_process cld = CHILD_PROCESS_INIT;
894 if (max_connections && live_children >= max_connections) {
895 kill_some_child();
896 sleep(1); /* give it some time to die */
897 check_dead_children();
898 if (live_children >= max_connections) {
899 close(incoming);
900 logerror("Too many children, dropping connection");
901 return;
905 if (addr->sa_family == AF_INET) {
906 char buf[128] = "";
907 struct sockaddr_in *sin_addr = (void *) addr;
908 inet_ntop(addr->sa_family, &sin_addr->sin_addr, buf, sizeof(buf));
909 strvec_pushf(&cld.env, "REMOTE_ADDR=%s", buf);
910 strvec_pushf(&cld.env, "REMOTE_PORT=%d",
911 ntohs(sin_addr->sin_port));
912 #ifndef NO_IPV6
913 } else if (addr->sa_family == AF_INET6) {
914 char buf[128] = "";
915 struct sockaddr_in6 *sin6_addr = (void *) addr;
916 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(buf));
917 strvec_pushf(&cld.env, "REMOTE_ADDR=[%s]", buf);
918 strvec_pushf(&cld.env, "REMOTE_PORT=%d",
919 ntohs(sin6_addr->sin6_port));
920 #endif
923 strvec_pushv(&cld.args, cld_argv.v);
924 cld.in = incoming;
925 cld.out = dup(incoming);
927 if (start_command(&cld))
928 logerror("unable to fork");
929 else
930 add_child(&cld, addr, addrlen);
933 static void child_handler(int signo UNUSED)
936 * Otherwise empty handler because systemcalls will get interrupted
937 * upon signal receipt
938 * SysV needs the handler to be rearmed
940 signal(SIGCHLD, child_handler);
943 static int set_reuse_addr(int sockfd)
945 int on = 1;
947 if (!reuseaddr)
948 return 0;
949 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
950 &on, sizeof(on));
953 struct socketlist {
954 int *list;
955 size_t nr;
956 size_t alloc;
959 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
961 #ifdef NO_IPV6
962 static char ip[INET_ADDRSTRLEN];
963 #else
964 static char ip[INET6_ADDRSTRLEN];
965 #endif
967 switch (family) {
968 #ifndef NO_IPV6
969 case AF_INET6:
970 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
971 break;
972 #endif
973 case AF_INET:
974 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
975 break;
976 default:
977 xsnprintf(ip, sizeof(ip), "<unknown>");
979 return ip;
982 #ifndef NO_IPV6
984 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
986 int socknum = 0;
987 char pbuf[NI_MAXSERV];
988 struct addrinfo hints, *ai0, *ai;
989 int gai;
990 long flags;
992 xsnprintf(pbuf, sizeof(pbuf), "%d", listen_port);
993 memset(&hints, 0, sizeof(hints));
994 hints.ai_family = AF_UNSPEC;
995 hints.ai_socktype = SOCK_STREAM;
996 hints.ai_protocol = IPPROTO_TCP;
997 hints.ai_flags = AI_PASSIVE;
999 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
1000 if (gai) {
1001 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
1002 return 0;
1005 for (ai = ai0; ai; ai = ai->ai_next) {
1006 int sockfd;
1008 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1009 if (sockfd < 0)
1010 continue;
1011 if (sockfd >= FD_SETSIZE) {
1012 logerror("Socket descriptor too large");
1013 close(sockfd);
1014 continue;
1017 #ifdef IPV6_V6ONLY
1018 if (ai->ai_family == AF_INET6) {
1019 int on = 1;
1020 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
1021 &on, sizeof(on));
1022 /* Note: error is not fatal */
1024 #endif
1026 if (set_reuse_addr(sockfd)) {
1027 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1028 close(sockfd);
1029 continue;
1032 set_keep_alive(sockfd);
1034 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
1035 logerror("Could not bind to %s: %s",
1036 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
1037 strerror(errno));
1038 close(sockfd);
1039 continue; /* not fatal */
1041 if (listen(sockfd, 5) < 0) {
1042 logerror("Could not listen to %s: %s",
1043 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
1044 strerror(errno));
1045 close(sockfd);
1046 continue; /* not fatal */
1049 flags = fcntl(sockfd, F_GETFD, 0);
1050 if (flags >= 0)
1051 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1053 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1054 socklist->list[socklist->nr++] = sockfd;
1055 socknum++;
1058 freeaddrinfo(ai0);
1060 return socknum;
1063 #else /* NO_IPV6 */
1065 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
1067 struct sockaddr_in sin;
1068 int sockfd;
1069 long flags;
1071 memset(&sin, 0, sizeof sin);
1072 sin.sin_family = AF_INET;
1073 sin.sin_port = htons(listen_port);
1075 if (listen_addr) {
1076 /* Well, host better be an IP address here. */
1077 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
1078 return 0;
1079 } else {
1080 sin.sin_addr.s_addr = htonl(INADDR_ANY);
1083 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1084 if (sockfd < 0)
1085 return 0;
1087 if (set_reuse_addr(sockfd)) {
1088 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1089 close(sockfd);
1090 return 0;
1093 set_keep_alive(sockfd);
1095 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
1096 logerror("Could not bind to %s: %s",
1097 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1098 strerror(errno));
1099 close(sockfd);
1100 return 0;
1103 if (listen(sockfd, 5) < 0) {
1104 logerror("Could not listen to %s: %s",
1105 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1106 strerror(errno));
1107 close(sockfd);
1108 return 0;
1111 flags = fcntl(sockfd, F_GETFD, 0);
1112 if (flags >= 0)
1113 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1115 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1116 socklist->list[socklist->nr++] = sockfd;
1117 return 1;
1120 #endif
1122 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
1124 if (!listen_addr->nr)
1125 setup_named_sock(NULL, listen_port, socklist);
1126 else {
1127 int i, socknum;
1128 for (i = 0; i < listen_addr->nr; i++) {
1129 socknum = setup_named_sock(listen_addr->items[i].string,
1130 listen_port, socklist);
1132 if (socknum == 0)
1133 logerror("unable to allocate any listen sockets for host %s on port %u",
1134 listen_addr->items[i].string, listen_port);
1139 static int service_loop(struct socketlist *socklist)
1141 struct pollfd *pfd;
1142 int i;
1144 CALLOC_ARRAY(pfd, socklist->nr);
1146 for (i = 0; i < socklist->nr; i++) {
1147 pfd[i].fd = socklist->list[i];
1148 pfd[i].events = POLLIN;
1151 signal(SIGCHLD, child_handler);
1153 for (;;) {
1154 int i;
1156 check_dead_children();
1158 if (poll(pfd, socklist->nr, -1) < 0) {
1159 if (errno != EINTR) {
1160 logerror("Poll failed, resuming: %s",
1161 strerror(errno));
1162 sleep(1);
1164 continue;
1167 for (i = 0; i < socklist->nr; i++) {
1168 if (pfd[i].revents & POLLIN) {
1169 union {
1170 struct sockaddr sa;
1171 struct sockaddr_in sai;
1172 #ifndef NO_IPV6
1173 struct sockaddr_in6 sai6;
1174 #endif
1175 } ss;
1176 socklen_t sslen = sizeof(ss);
1177 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1178 if (incoming < 0) {
1179 switch (errno) {
1180 case EAGAIN:
1181 case EINTR:
1182 case ECONNABORTED:
1183 continue;
1184 default:
1185 die_errno("accept returned");
1188 handle(incoming, &ss.sa, sslen);
1194 #ifdef NO_POSIX_GOODIES
1196 struct credentials;
1198 static void drop_privileges(struct credentials *cred)
1200 /* nothing */
1203 static struct credentials *prepare_credentials(const char *user_name,
1204 const char *group_name)
1206 die("--user not supported on this platform");
1209 #else
1211 struct credentials {
1212 struct passwd *pass;
1213 gid_t gid;
1216 static void drop_privileges(struct credentials *cred)
1218 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1219 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1220 die("cannot drop privileges");
1223 static struct credentials *prepare_credentials(const char *user_name,
1224 const char *group_name)
1226 static struct credentials c;
1228 c.pass = getpwnam(user_name);
1229 if (!c.pass)
1230 die("user not found - %s", user_name);
1232 if (!group_name)
1233 c.gid = c.pass->pw_gid;
1234 else {
1235 struct group *group = getgrnam(group_name);
1236 if (!group)
1237 die("group not found - %s", group_name);
1239 c.gid = group->gr_gid;
1242 return &c;
1244 #endif
1246 static int serve(struct string_list *listen_addr, int listen_port,
1247 struct credentials *cred)
1249 struct socketlist socklist = { NULL, 0, 0 };
1251 socksetup(listen_addr, listen_port, &socklist);
1252 if (socklist.nr == 0)
1253 die("unable to allocate any listen sockets on port %u",
1254 listen_port);
1256 drop_privileges(cred);
1258 loginfo("Ready to rumble");
1260 return service_loop(&socklist);
1263 int cmd_main(int argc, const char **argv)
1265 int listen_port = 0;
1266 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1267 int serve_mode = 0, inetd_mode = 0;
1268 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1269 int detach = 0;
1270 struct credentials *cred = NULL;
1271 int i;
1273 for (i = 1; i < argc; i++) {
1274 const char *arg = argv[i];
1275 const char *v;
1277 if (skip_prefix(arg, "--listen=", &v)) {
1278 string_list_append(&listen_addr, xstrdup_tolower(v));
1279 continue;
1281 if (skip_prefix(arg, "--port=", &v)) {
1282 char *end;
1283 unsigned long n;
1284 n = strtoul(v, &end, 0);
1285 if (*v && !*end) {
1286 listen_port = n;
1287 continue;
1290 if (!strcmp(arg, "--serve")) {
1291 serve_mode = 1;
1292 continue;
1294 if (!strcmp(arg, "--inetd")) {
1295 inetd_mode = 1;
1296 continue;
1298 if (!strcmp(arg, "--verbose")) {
1299 verbose = 1;
1300 continue;
1302 if (!strcmp(arg, "--syslog")) {
1303 log_destination = LOG_DESTINATION_SYSLOG;
1304 continue;
1306 if (skip_prefix(arg, "--log-destination=", &v)) {
1307 if (!strcmp(v, "syslog")) {
1308 log_destination = LOG_DESTINATION_SYSLOG;
1309 continue;
1310 } else if (!strcmp(v, "stderr")) {
1311 log_destination = LOG_DESTINATION_STDERR;
1312 continue;
1313 } else if (!strcmp(v, "none")) {
1314 log_destination = LOG_DESTINATION_NONE;
1315 continue;
1316 } else
1317 die("unknown log destination '%s'", v);
1319 if (!strcmp(arg, "--export-all")) {
1320 export_all_trees = 1;
1321 continue;
1323 if (skip_prefix(arg, "--access-hook=", &v)) {
1324 access_hook = v;
1325 continue;
1327 if (skip_prefix(arg, "--timeout=", &v)) {
1328 timeout = atoi(v);
1329 continue;
1331 if (skip_prefix(arg, "--init-timeout=", &v)) {
1332 init_timeout = atoi(v);
1333 continue;
1335 if (skip_prefix(arg, "--max-connections=", &v)) {
1336 max_connections = atoi(v);
1337 if (max_connections < 0)
1338 max_connections = 0; /* unlimited */
1339 continue;
1341 if (!strcmp(arg, "--strict-paths")) {
1342 strict_paths = 1;
1343 continue;
1345 if (skip_prefix(arg, "--base-path=", &v)) {
1346 base_path = v;
1347 continue;
1349 if (!strcmp(arg, "--base-path-relaxed")) {
1350 base_path_relaxed = 1;
1351 continue;
1353 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1354 interpolated_path = v;
1355 continue;
1357 if (!strcmp(arg, "--reuseaddr")) {
1358 reuseaddr = 1;
1359 continue;
1361 if (!strcmp(arg, "--user-path")) {
1362 user_path = "";
1363 continue;
1365 if (skip_prefix(arg, "--user-path=", &v)) {
1366 user_path = v;
1367 continue;
1369 if (skip_prefix(arg, "--pid-file=", &v)) {
1370 pid_file = v;
1371 continue;
1373 if (!strcmp(arg, "--detach")) {
1374 detach = 1;
1375 continue;
1377 if (skip_prefix(arg, "--user=", &v)) {
1378 user_name = v;
1379 continue;
1381 if (skip_prefix(arg, "--group=", &v)) {
1382 group_name = v;
1383 continue;
1385 if (skip_prefix(arg, "--enable=", &v)) {
1386 enable_service(v, 1);
1387 continue;
1389 if (skip_prefix(arg, "--disable=", &v)) {
1390 enable_service(v, 0);
1391 continue;
1393 if (skip_prefix(arg, "--allow-override=", &v)) {
1394 make_service_overridable(v, 1);
1395 continue;
1397 if (skip_prefix(arg, "--forbid-override=", &v)) {
1398 make_service_overridable(v, 0);
1399 continue;
1401 if (!strcmp(arg, "--informative-errors")) {
1402 informative_errors = 1;
1403 continue;
1405 if (!strcmp(arg, "--no-informative-errors")) {
1406 informative_errors = 0;
1407 continue;
1409 if (!strcmp(arg, "--")) {
1410 ok_paths = &argv[i+1];
1411 break;
1412 } else if (arg[0] != '-') {
1413 ok_paths = &argv[i];
1414 break;
1417 usage(daemon_usage);
1420 if (log_destination == LOG_DESTINATION_UNSET) {
1421 if (inetd_mode || detach)
1422 log_destination = LOG_DESTINATION_SYSLOG;
1423 else
1424 log_destination = LOG_DESTINATION_STDERR;
1427 if (log_destination == LOG_DESTINATION_SYSLOG) {
1428 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1429 set_die_routine(daemon_die);
1430 } else
1431 /* avoid splitting a message in the middle */
1432 setvbuf(stderr, NULL, _IOFBF, 4096);
1434 if (inetd_mode && (detach || group_name || user_name))
1435 die("--detach, --user and --group are incompatible with --inetd");
1437 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1438 die("--listen= and --port= are incompatible with --inetd");
1439 else if (listen_port == 0)
1440 listen_port = DEFAULT_GIT_PORT;
1442 if (group_name && !user_name)
1443 die("--group supplied without --user");
1445 if (user_name)
1446 cred = prepare_credentials(user_name, group_name);
1448 if (strict_paths && (!ok_paths || !*ok_paths))
1449 die("option --strict-paths requires '<directory>' arguments");
1451 if (base_path && !is_directory(base_path))
1452 die("base-path '%s' does not exist or is not a directory",
1453 base_path);
1455 if (log_destination != LOG_DESTINATION_STDERR) {
1456 if (!freopen("/dev/null", "w", stderr))
1457 die_errno("failed to redirect stderr to /dev/null");
1460 if (inetd_mode || serve_mode)
1461 return execute();
1463 if (detach) {
1464 if (daemonize())
1465 die("--detach not supported on this platform");
1468 if (pid_file)
1469 write_file(pid_file, "%"PRIuMAX, (uintmax_t) getpid());
1471 /* prepare argv for serving-processes */
1472 strvec_push(&cld_argv, argv[0]); /* git-daemon */
1473 strvec_push(&cld_argv, "--serve");
1474 for (i = 1; i < argc; ++i)
1475 strvec_push(&cld_argv, argv[i]);
1477 return serve(&listen_addr, listen_port, cred);