Merge branch 'rj/bisect-already-used-branch'
[git/debian.git] / daemon.c
blob8908e7f8d2a27c4e81225f69c4a4401e0698c363
1 #include "cache.h"
2 #include "alloc.h"
3 #include "config.h"
4 #include "pkt-line.h"
5 #include "run-command.h"
6 #include "strbuf.h"
7 #include "string-list.h"
9 #ifdef NO_INITGROUPS
10 #define initgroups(x, y) (0) /* nothing */
11 #endif
13 static enum log_destination {
14 LOG_DESTINATION_UNSET = -1,
15 LOG_DESTINATION_NONE = 0,
16 LOG_DESTINATION_STDERR = 1,
17 LOG_DESTINATION_SYSLOG = 2,
18 } log_destination = LOG_DESTINATION_UNSET;
19 static int verbose;
20 static int reuseaddr;
21 static int informative_errors;
23 static const char daemon_usage[] =
24 "git daemon [--verbose] [--syslog] [--export-all]\n"
25 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
26 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
27 " [--user-path | --user-path=<path>]\n"
28 " [--interpolated-path=<path>]\n"
29 " [--reuseaddr] [--pid-file=<file>]\n"
30 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
31 " [--access-hook=<path>]\n"
32 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
33 " [--detach] [--user=<user> [--group=<group>]]\n"
34 " [--log-destination=(stderr|syslog|none)]\n"
35 " [<directory>...]";
37 /* List of acceptable pathname prefixes */
38 static const char **ok_paths;
39 static int strict_paths;
41 /* If this is set, git-daemon-export-ok is not required */
42 static int export_all_trees;
44 /* Take all paths relative to this one if non-NULL */
45 static const char *base_path;
46 static const char *interpolated_path;
47 static int base_path_relaxed;
49 /* If defined, ~user notation is allowed and the string is inserted
50 * after ~user/. E.g. a request to git://host/~alice/frotz would
51 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
53 static const char *user_path;
55 /* Timeout, and initial timeout */
56 static unsigned int timeout;
57 static unsigned int init_timeout;
59 struct hostinfo {
60 struct strbuf hostname;
61 struct strbuf canon_hostname;
62 struct strbuf ip_address;
63 struct strbuf tcp_port;
64 unsigned int hostname_lookup_done:1;
65 unsigned int saw_extended_args:1;
67 #define HOSTINFO_INIT { \
68 .hostname = STRBUF_INIT, \
69 .canon_hostname = STRBUF_INIT, \
70 .ip_address = STRBUF_INIT, \
71 .tcp_port = STRBUF_INIT, \
74 static void lookup_hostname(struct hostinfo *hi);
76 static const char *get_canon_hostname(struct hostinfo *hi)
78 lookup_hostname(hi);
79 return hi->canon_hostname.buf;
82 static const char *get_ip_address(struct hostinfo *hi)
84 lookup_hostname(hi);
85 return hi->ip_address.buf;
88 static void logreport(int priority, const char *err, va_list params)
90 switch (log_destination) {
91 case LOG_DESTINATION_SYSLOG: {
92 char buf[1024];
93 vsnprintf(buf, sizeof(buf), err, params);
94 syslog(priority, "%s", buf);
95 break;
97 case LOG_DESTINATION_STDERR:
99 * Since stderr is set to buffered mode, the
100 * logging of different processes will not overlap
101 * unless they overflow the (rather big) buffers.
103 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
104 vfprintf(stderr, err, params);
105 fputc('\n', stderr);
106 fflush(stderr);
107 break;
108 case LOG_DESTINATION_NONE:
109 break;
110 case LOG_DESTINATION_UNSET:
111 BUG("log destination not initialized correctly");
115 __attribute__((format (printf, 1, 2)))
116 static void logerror(const char *err, ...)
118 va_list params;
119 va_start(params, err);
120 logreport(LOG_ERR, err, params);
121 va_end(params);
124 __attribute__((format (printf, 1, 2)))
125 static void loginfo(const char *err, ...)
127 va_list params;
128 if (!verbose)
129 return;
130 va_start(params, err);
131 logreport(LOG_INFO, err, params);
132 va_end(params);
135 static void NORETURN daemon_die(const char *err, va_list params)
137 logreport(LOG_ERR, err, params);
138 exit(1);
141 struct expand_path_context {
142 const char *directory;
143 struct hostinfo *hostinfo;
146 static size_t expand_path(struct strbuf *sb, const char *placeholder, void *ctx)
148 struct expand_path_context *context = ctx;
149 struct hostinfo *hi = context->hostinfo;
151 switch (placeholder[0]) {
152 case 'H':
153 strbuf_addbuf(sb, &hi->hostname);
154 return 1;
155 case 'C':
156 if (placeholder[1] == 'H') {
157 strbuf_addstr(sb, get_canon_hostname(hi));
158 return 2;
160 break;
161 case 'I':
162 if (placeholder[1] == 'P') {
163 strbuf_addstr(sb, get_ip_address(hi));
164 return 2;
166 break;
167 case 'P':
168 strbuf_addbuf(sb, &hi->tcp_port);
169 return 1;
170 case 'D':
171 strbuf_addstr(sb, context->directory);
172 return 1;
174 return 0;
177 static const char *path_ok(const char *directory, struct hostinfo *hi)
179 static char rpath[PATH_MAX];
180 static char interp_path[PATH_MAX];
181 size_t rlen;
182 const char *path;
183 const char *dir;
185 dir = directory;
187 if (daemon_avoid_alias(dir)) {
188 logerror("'%s': aliased", dir);
189 return NULL;
192 if (*dir == '~') {
193 if (!user_path) {
194 logerror("'%s': User-path not allowed", dir);
195 return NULL;
197 if (*user_path) {
198 /* Got either "~alice" or "~alice/foo";
199 * rewrite them to "~alice/%s" or
200 * "~alice/%s/foo".
202 int namlen, restlen = strlen(dir);
203 const char *slash = strchr(dir, '/');
204 if (!slash)
205 slash = dir + restlen;
206 namlen = slash - dir;
207 restlen -= namlen;
208 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
209 rlen = snprintf(rpath, sizeof(rpath), "%.*s/%s%.*s",
210 namlen, dir, user_path, restlen, slash);
211 if (rlen >= sizeof(rpath)) {
212 logerror("user-path too large: %s", rpath);
213 return NULL;
215 dir = rpath;
218 else if (interpolated_path && hi->saw_extended_args) {
219 struct strbuf expanded_path = STRBUF_INIT;
220 struct expand_path_context context;
222 context.directory = directory;
223 context.hostinfo = hi;
225 if (*dir != '/') {
226 /* Allow only absolute */
227 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
228 return NULL;
231 strbuf_expand(&expanded_path, interpolated_path,
232 expand_path, &context);
234 rlen = strlcpy(interp_path, expanded_path.buf,
235 sizeof(interp_path));
236 strbuf_release(&expanded_path);
237 if (rlen >= sizeof(interp_path)) {
238 logerror("interpolated path too large: %s",
239 interp_path);
240 return NULL;
243 loginfo("Interpolated dir '%s'", interp_path);
245 dir = interp_path;
247 else if (base_path) {
248 if (*dir != '/') {
249 /* Allow only absolute */
250 logerror("'%s': Non-absolute path denied (base-path active)", dir);
251 return NULL;
253 rlen = snprintf(rpath, sizeof(rpath), "%s%s", base_path, dir);
254 if (rlen >= sizeof(rpath)) {
255 logerror("base-path too large: %s", rpath);
256 return NULL;
258 dir = rpath;
261 path = enter_repo(dir, strict_paths);
262 if (!path && base_path && base_path_relaxed) {
264 * if we fail and base_path_relaxed is enabled, try without
265 * prefixing the base path
267 dir = directory;
268 path = enter_repo(dir, strict_paths);
271 if (!path) {
272 logerror("'%s' does not appear to be a git repository", dir);
273 return NULL;
276 if ( ok_paths && *ok_paths ) {
277 const char **pp;
278 int pathlen = strlen(path);
280 /* The validation is done on the paths after enter_repo
281 * appends optional {.git,.git/.git} and friends, but
282 * it does not use getcwd(). So if your /pub is
283 * a symlink to /mnt/pub, you can include /pub and
284 * do not have to say /mnt/pub.
285 * Do not say /pub/.
287 for ( pp = ok_paths ; *pp ; pp++ ) {
288 int len = strlen(*pp);
289 if (len <= pathlen &&
290 !memcmp(*pp, path, len) &&
291 (path[len] == '\0' ||
292 (!strict_paths && path[len] == '/')))
293 return path;
296 else {
297 /* be backwards compatible */
298 if (!strict_paths)
299 return path;
302 logerror("'%s': not in directory list", path);
303 return NULL; /* Fallthrough. Deny by default */
306 typedef int (*daemon_service_fn)(const struct strvec *env);
307 struct daemon_service {
308 const char *name;
309 const char *config_name;
310 daemon_service_fn fn;
311 int enabled;
312 int overridable;
315 static int daemon_error(const char *dir, const char *msg)
317 if (!informative_errors)
318 msg = "access denied or repository not exported";
319 packet_write_fmt(1, "ERR %s: %s", msg, dir);
320 return -1;
323 static const char *access_hook;
325 static int run_access_hook(struct daemon_service *service, const char *dir,
326 const char *path, struct hostinfo *hi)
328 struct child_process child = CHILD_PROCESS_INIT;
329 struct strbuf buf = STRBUF_INIT;
330 char *eol;
331 int seen_errors = 0;
333 strvec_push(&child.args, access_hook);
334 strvec_push(&child.args, service->name);
335 strvec_push(&child.args, path);
336 strvec_push(&child.args, hi->hostname.buf);
337 strvec_push(&child.args, get_canon_hostname(hi));
338 strvec_push(&child.args, get_ip_address(hi));
339 strvec_push(&child.args, hi->tcp_port.buf);
341 child.use_shell = 1;
342 child.no_stdin = 1;
343 child.no_stderr = 1;
344 child.out = -1;
345 if (start_command(&child)) {
346 logerror("daemon access hook '%s' failed to start",
347 access_hook);
348 goto error_return;
350 if (strbuf_read(&buf, child.out, 0) < 0) {
351 logerror("failed to read from pipe to daemon access hook '%s'",
352 access_hook);
353 strbuf_reset(&buf);
354 seen_errors = 1;
356 if (close(child.out) < 0) {
357 logerror("failed to close pipe to daemon access hook '%s'",
358 access_hook);
359 seen_errors = 1;
361 if (finish_command(&child))
362 seen_errors = 1;
364 if (!seen_errors) {
365 strbuf_release(&buf);
366 return 0;
369 error_return:
370 strbuf_ltrim(&buf);
371 if (!buf.len)
372 strbuf_addstr(&buf, "service rejected");
373 eol = strchr(buf.buf, '\n');
374 if (eol)
375 *eol = '\0';
376 errno = EACCES;
377 daemon_error(dir, buf.buf);
378 strbuf_release(&buf);
379 return -1;
382 static int run_service(const char *dir, struct daemon_service *service,
383 struct hostinfo *hi, const struct strvec *env)
385 const char *path;
386 int enabled = service->enabled;
387 struct strbuf var = STRBUF_INIT;
389 loginfo("Request %s for '%s'", service->name, dir);
391 if (!enabled && !service->overridable) {
392 logerror("'%s': service not enabled.", service->name);
393 errno = EACCES;
394 return daemon_error(dir, "service not enabled");
397 if (!(path = path_ok(dir, hi)))
398 return daemon_error(dir, "no such repository");
401 * Security on the cheap.
403 * We want a readable HEAD, usable "objects" directory, and
404 * a "git-daemon-export-ok" flag that says that the other side
405 * is ok with us doing this.
407 * path_ok() uses enter_repo() and checks for included directories.
408 * We only need to make sure the repository is exported.
411 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
412 logerror("'%s': repository not exported.", path);
413 errno = EACCES;
414 return daemon_error(dir, "repository not exported");
417 if (service->overridable) {
418 strbuf_addf(&var, "daemon.%s", service->config_name);
419 git_config_get_bool(var.buf, &enabled);
420 strbuf_release(&var);
422 if (!enabled) {
423 logerror("'%s': service not enabled for '%s'",
424 service->name, path);
425 errno = EACCES;
426 return daemon_error(dir, "service not enabled");
430 * Optionally, a hook can choose to deny access to the
431 * repository depending on the phase of the moon.
433 if (access_hook && run_access_hook(service, dir, path, hi))
434 return -1;
437 * We'll ignore SIGTERM from now on, we have a
438 * good client.
440 signal(SIGTERM, SIG_IGN);
442 return service->fn(env);
445 static void copy_to_log(int fd)
447 struct strbuf line = STRBUF_INIT;
448 FILE *fp;
450 fp = fdopen(fd, "r");
451 if (!fp) {
452 logerror("fdopen of error channel failed");
453 close(fd);
454 return;
457 while (strbuf_getline_lf(&line, fp) != EOF) {
458 logerror("%s", line.buf);
459 strbuf_setlen(&line, 0);
462 strbuf_release(&line);
463 fclose(fp);
466 static int run_service_command(struct child_process *cld)
468 strvec_push(&cld->args, ".");
469 cld->git_cmd = 1;
470 cld->err = -1;
471 if (start_command(cld))
472 return -1;
474 close(0);
475 close(1);
477 copy_to_log(cld->err);
479 return finish_command(cld);
482 static int upload_pack(const struct strvec *env)
484 struct child_process cld = CHILD_PROCESS_INIT;
485 strvec_pushl(&cld.args, "upload-pack", "--strict", NULL);
486 strvec_pushf(&cld.args, "--timeout=%u", timeout);
488 strvec_pushv(&cld.env, env->v);
490 return run_service_command(&cld);
493 static int upload_archive(const struct strvec *env)
495 struct child_process cld = CHILD_PROCESS_INIT;
496 strvec_push(&cld.args, "upload-archive");
498 strvec_pushv(&cld.env, env->v);
500 return run_service_command(&cld);
503 static int receive_pack(const struct strvec *env)
505 struct child_process cld = CHILD_PROCESS_INIT;
506 strvec_push(&cld.args, "receive-pack");
508 strvec_pushv(&cld.env, env->v);
510 return run_service_command(&cld);
513 static struct daemon_service daemon_service[] = {
514 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
515 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
516 { "receive-pack", "receivepack", receive_pack, 0, 1 },
519 static void enable_service(const char *name, int ena)
521 int i;
522 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
523 if (!strcmp(daemon_service[i].name, name)) {
524 daemon_service[i].enabled = ena;
525 return;
528 die("No such service %s", name);
531 static void make_service_overridable(const char *name, int ena)
533 int i;
534 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
535 if (!strcmp(daemon_service[i].name, name)) {
536 daemon_service[i].overridable = ena;
537 return;
540 die("No such service %s", name);
543 static void parse_host_and_port(char *hostport, char **host,
544 char **port)
546 if (*hostport == '[') {
547 char *end;
549 end = strchr(hostport, ']');
550 if (!end)
551 die("Invalid request ('[' without ']')");
552 *end = '\0';
553 *host = hostport + 1;
554 if (!end[1])
555 *port = NULL;
556 else if (end[1] == ':')
557 *port = end + 2;
558 else
559 die("Garbage after end of host part");
560 } else {
561 *host = hostport;
562 *port = strrchr(hostport, ':');
563 if (*port) {
564 **port = '\0';
565 ++*port;
571 * Sanitize a string from the client so that it's OK to be inserted into a
572 * filesystem path. Specifically, we disallow directory separators, runs
573 * of "..", and trailing and leading dots, which means that the client
574 * cannot escape our base path via ".." traversal.
576 static void sanitize_client(struct strbuf *out, const char *in)
578 for (; *in; in++) {
579 if (is_dir_sep(*in))
580 continue;
581 if (*in == '.' && (!out->len || out->buf[out->len - 1] == '.'))
582 continue;
583 strbuf_addch(out, *in);
586 while (out->len && out->buf[out->len - 1] == '.')
587 strbuf_setlen(out, out->len - 1);
591 * Like sanitize_client, but we also perform any canonicalization
592 * to make life easier on the admin.
594 static void canonicalize_client(struct strbuf *out, const char *in)
596 sanitize_client(out, in);
597 strbuf_tolower(out);
601 * Read the host as supplied by the client connection.
603 * Returns a pointer to the character after the NUL byte terminating the host
604 * argument, or 'extra_args' if there is no host argument.
606 static char *parse_host_arg(struct hostinfo *hi, char *extra_args, int buflen)
608 char *val;
609 int vallen;
610 char *end = extra_args + buflen;
612 if (extra_args < end && *extra_args) {
613 hi->saw_extended_args = 1;
614 if (strncasecmp("host=", extra_args, 5) == 0) {
615 val = extra_args + 5;
616 vallen = strlen(val) + 1;
617 loginfo("Extended attribute \"host\": %s", val);
618 if (*val) {
619 /* Split <host>:<port> at colon. */
620 char *host;
621 char *port;
622 parse_host_and_port(val, &host, &port);
623 if (port)
624 sanitize_client(&hi->tcp_port, port);
625 canonicalize_client(&hi->hostname, host);
626 hi->hostname_lookup_done = 0;
629 /* On to the next one */
630 extra_args = val + vallen;
632 if (extra_args < end && *extra_args)
633 die("Invalid request");
636 return extra_args;
639 static void parse_extra_args(struct hostinfo *hi, struct strvec *env,
640 char *extra_args, int buflen)
642 const char *end = extra_args + buflen;
643 struct strbuf git_protocol = STRBUF_INIT;
645 /* First look for the host argument */
646 extra_args = parse_host_arg(hi, extra_args, buflen);
648 /* Look for additional arguments places after a second NUL byte */
649 for (; extra_args < end; extra_args += strlen(extra_args) + 1) {
650 const char *arg = extra_args;
653 * Parse the extra arguments, adding most to 'git_protocol'
654 * which will be used to set the 'GIT_PROTOCOL' envvar in the
655 * service that will be run.
657 * If there ends up being a particular arg in the future that
658 * git-daemon needs to parse specifically (like the 'host' arg)
659 * then it can be parsed here and not added to 'git_protocol'.
661 if (*arg) {
662 if (git_protocol.len > 0)
663 strbuf_addch(&git_protocol, ':');
664 strbuf_addstr(&git_protocol, arg);
668 if (git_protocol.len > 0) {
669 loginfo("Extended attribute \"protocol\": %s", git_protocol.buf);
670 strvec_pushf(env, GIT_PROTOCOL_ENVIRONMENT "=%s",
671 git_protocol.buf);
673 strbuf_release(&git_protocol);
677 * Locate canonical hostname and its IP address.
679 static void lookup_hostname(struct hostinfo *hi)
681 if (!hi->hostname_lookup_done && hi->hostname.len) {
682 #ifndef NO_IPV6
683 struct addrinfo hints;
684 struct addrinfo *ai;
685 int gai;
686 static char addrbuf[HOST_NAME_MAX + 1];
688 memset(&hints, 0, sizeof(hints));
689 hints.ai_flags = AI_CANONNAME;
691 gai = getaddrinfo(hi->hostname.buf, NULL, &hints, &ai);
692 if (!gai) {
693 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
695 inet_ntop(AF_INET, &sin_addr->sin_addr,
696 addrbuf, sizeof(addrbuf));
697 strbuf_addstr(&hi->ip_address, addrbuf);
699 if (ai->ai_canonname)
700 sanitize_client(&hi->canon_hostname,
701 ai->ai_canonname);
702 else
703 strbuf_addbuf(&hi->canon_hostname,
704 &hi->ip_address);
706 freeaddrinfo(ai);
708 #else
709 struct hostent *hent;
710 struct sockaddr_in sa;
711 char **ap;
712 static char addrbuf[HOST_NAME_MAX + 1];
714 hent = gethostbyname(hi->hostname.buf);
715 if (hent) {
716 ap = hent->h_addr_list;
717 memset(&sa, 0, sizeof sa);
718 sa.sin_family = hent->h_addrtype;
719 sa.sin_port = htons(0);
720 memcpy(&sa.sin_addr, *ap, hent->h_length);
722 inet_ntop(hent->h_addrtype, &sa.sin_addr,
723 addrbuf, sizeof(addrbuf));
725 sanitize_client(&hi->canon_hostname, hent->h_name);
726 strbuf_addstr(&hi->ip_address, addrbuf);
728 #endif
729 hi->hostname_lookup_done = 1;
733 static void hostinfo_clear(struct hostinfo *hi)
735 strbuf_release(&hi->hostname);
736 strbuf_release(&hi->canon_hostname);
737 strbuf_release(&hi->ip_address);
738 strbuf_release(&hi->tcp_port);
741 static void set_keep_alive(int sockfd)
743 int ka = 1;
745 if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0) {
746 if (errno != ENOTSOCK)
747 logerror("unable to set SO_KEEPALIVE on socket: %s",
748 strerror(errno));
752 static int execute(void)
754 char *line = packet_buffer;
755 int pktlen, len, i;
756 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
757 struct hostinfo hi = HOSTINFO_INIT;
758 struct strvec env = STRVEC_INIT;
760 if (addr)
761 loginfo("Connection from %s:%s", addr, port);
763 set_keep_alive(0);
764 alarm(init_timeout ? init_timeout : timeout);
765 pktlen = packet_read(0, packet_buffer, sizeof(packet_buffer), 0);
766 alarm(0);
768 len = strlen(line);
769 if (len && line[len-1] == '\n')
770 line[len-1] = 0;
772 /* parse additional args hidden behind a NUL byte */
773 if (len != pktlen)
774 parse_extra_args(&hi, &env, line + len + 1, pktlen - len - 1);
776 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
777 struct daemon_service *s = &(daemon_service[i]);
778 const char *arg;
780 if (skip_prefix(line, "git-", &arg) &&
781 skip_prefix(arg, s->name, &arg) &&
782 *arg++ == ' ') {
784 * Note: The directory here is probably context sensitive,
785 * and might depend on the actual service being performed.
787 int rc = run_service(arg, s, &hi, &env);
788 hostinfo_clear(&hi);
789 strvec_clear(&env);
790 return rc;
794 hostinfo_clear(&hi);
795 strvec_clear(&env);
796 logerror("Protocol error: '%s'", line);
797 return -1;
800 static int addrcmp(const struct sockaddr_storage *s1,
801 const struct sockaddr_storage *s2)
803 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
804 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
806 if (sa1->sa_family != sa2->sa_family)
807 return sa1->sa_family - sa2->sa_family;
808 if (sa1->sa_family == AF_INET)
809 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
810 &((struct sockaddr_in *)s2)->sin_addr,
811 sizeof(struct in_addr));
812 #ifndef NO_IPV6
813 if (sa1->sa_family == AF_INET6)
814 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
815 &((struct sockaddr_in6 *)s2)->sin6_addr,
816 sizeof(struct in6_addr));
817 #endif
818 return 0;
821 static int max_connections = 32;
823 static unsigned int live_children;
825 static struct child {
826 struct child *next;
827 struct child_process cld;
828 struct sockaddr_storage address;
829 } *firstborn;
831 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
833 struct child *newborn, **cradle;
835 CALLOC_ARRAY(newborn, 1);
836 live_children++;
837 memcpy(&newborn->cld, cld, sizeof(*cld));
838 memcpy(&newborn->address, addr, addrlen);
839 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
840 if (!addrcmp(&(*cradle)->address, &newborn->address))
841 break;
842 newborn->next = *cradle;
843 *cradle = newborn;
847 * This gets called if the number of connections grows
848 * past "max_connections".
850 * We kill the newest connection from a duplicate IP.
852 static void kill_some_child(void)
854 const struct child *blanket, *next;
856 if (!(blanket = firstborn))
857 return;
859 for (; (next = blanket->next); blanket = next)
860 if (!addrcmp(&blanket->address, &next->address)) {
861 kill(blanket->cld.pid, SIGTERM);
862 break;
866 static void check_dead_children(void)
868 int status;
869 pid_t pid;
871 struct child **cradle, *blanket;
872 for (cradle = &firstborn; (blanket = *cradle);)
873 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
874 const char *dead = "";
875 if (status)
876 dead = " (with error)";
877 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
879 /* remove the child */
880 *cradle = blanket->next;
881 live_children--;
882 child_process_clear(&blanket->cld);
883 free(blanket);
884 } else
885 cradle = &blanket->next;
888 static struct strvec cld_argv = STRVEC_INIT;
889 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
891 struct child_process cld = CHILD_PROCESS_INIT;
893 if (max_connections && live_children >= max_connections) {
894 kill_some_child();
895 sleep(1); /* give it some time to die */
896 check_dead_children();
897 if (live_children >= max_connections) {
898 close(incoming);
899 logerror("Too many children, dropping connection");
900 return;
904 if (addr->sa_family == AF_INET) {
905 char buf[128] = "";
906 struct sockaddr_in *sin_addr = (void *) addr;
907 inet_ntop(addr->sa_family, &sin_addr->sin_addr, buf, sizeof(buf));
908 strvec_pushf(&cld.env, "REMOTE_ADDR=%s", buf);
909 strvec_pushf(&cld.env, "REMOTE_PORT=%d",
910 ntohs(sin_addr->sin_port));
911 #ifndef NO_IPV6
912 } else if (addr->sa_family == AF_INET6) {
913 char buf[128] = "";
914 struct sockaddr_in6 *sin6_addr = (void *) addr;
915 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(buf));
916 strvec_pushf(&cld.env, "REMOTE_ADDR=[%s]", buf);
917 strvec_pushf(&cld.env, "REMOTE_PORT=%d",
918 ntohs(sin6_addr->sin6_port));
919 #endif
922 strvec_pushv(&cld.args, cld_argv.v);
923 cld.in = incoming;
924 cld.out = dup(incoming);
926 if (start_command(&cld))
927 logerror("unable to fork");
928 else
929 add_child(&cld, addr, addrlen);
932 static void child_handler(int signo UNUSED)
935 * Otherwise empty handler because systemcalls will get interrupted
936 * upon signal receipt
937 * SysV needs the handler to be rearmed
939 signal(SIGCHLD, child_handler);
942 static int set_reuse_addr(int sockfd)
944 int on = 1;
946 if (!reuseaddr)
947 return 0;
948 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
949 &on, sizeof(on));
952 struct socketlist {
953 int *list;
954 size_t nr;
955 size_t alloc;
958 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
960 #ifdef NO_IPV6
961 static char ip[INET_ADDRSTRLEN];
962 #else
963 static char ip[INET6_ADDRSTRLEN];
964 #endif
966 switch (family) {
967 #ifndef NO_IPV6
968 case AF_INET6:
969 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
970 break;
971 #endif
972 case AF_INET:
973 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
974 break;
975 default:
976 xsnprintf(ip, sizeof(ip), "<unknown>");
978 return ip;
981 #ifndef NO_IPV6
983 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
985 int socknum = 0;
986 char pbuf[NI_MAXSERV];
987 struct addrinfo hints, *ai0, *ai;
988 int gai;
989 long flags;
991 xsnprintf(pbuf, sizeof(pbuf), "%d", listen_port);
992 memset(&hints, 0, sizeof(hints));
993 hints.ai_family = AF_UNSPEC;
994 hints.ai_socktype = SOCK_STREAM;
995 hints.ai_protocol = IPPROTO_TCP;
996 hints.ai_flags = AI_PASSIVE;
998 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
999 if (gai) {
1000 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
1001 return 0;
1004 for (ai = ai0; ai; ai = ai->ai_next) {
1005 int sockfd;
1007 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1008 if (sockfd < 0)
1009 continue;
1010 if (sockfd >= FD_SETSIZE) {
1011 logerror("Socket descriptor too large");
1012 close(sockfd);
1013 continue;
1016 #ifdef IPV6_V6ONLY
1017 if (ai->ai_family == AF_INET6) {
1018 int on = 1;
1019 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
1020 &on, sizeof(on));
1021 /* Note: error is not fatal */
1023 #endif
1025 if (set_reuse_addr(sockfd)) {
1026 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1027 close(sockfd);
1028 continue;
1031 set_keep_alive(sockfd);
1033 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
1034 logerror("Could not bind to %s: %s",
1035 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
1036 strerror(errno));
1037 close(sockfd);
1038 continue; /* not fatal */
1040 if (listen(sockfd, 5) < 0) {
1041 logerror("Could not listen to %s: %s",
1042 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
1043 strerror(errno));
1044 close(sockfd);
1045 continue; /* not fatal */
1048 flags = fcntl(sockfd, F_GETFD, 0);
1049 if (flags >= 0)
1050 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1052 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1053 socklist->list[socklist->nr++] = sockfd;
1054 socknum++;
1057 freeaddrinfo(ai0);
1059 return socknum;
1062 #else /* NO_IPV6 */
1064 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
1066 struct sockaddr_in sin;
1067 int sockfd;
1068 long flags;
1070 memset(&sin, 0, sizeof sin);
1071 sin.sin_family = AF_INET;
1072 sin.sin_port = htons(listen_port);
1074 if (listen_addr) {
1075 /* Well, host better be an IP address here. */
1076 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
1077 return 0;
1078 } else {
1079 sin.sin_addr.s_addr = htonl(INADDR_ANY);
1082 sockfd = socket(AF_INET, SOCK_STREAM, 0);
1083 if (sockfd < 0)
1084 return 0;
1086 if (set_reuse_addr(sockfd)) {
1087 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1088 close(sockfd);
1089 return 0;
1092 set_keep_alive(sockfd);
1094 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
1095 logerror("Could not bind to %s: %s",
1096 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1097 strerror(errno));
1098 close(sockfd);
1099 return 0;
1102 if (listen(sockfd, 5) < 0) {
1103 logerror("Could not listen to %s: %s",
1104 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1105 strerror(errno));
1106 close(sockfd);
1107 return 0;
1110 flags = fcntl(sockfd, F_GETFD, 0);
1111 if (flags >= 0)
1112 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1114 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1115 socklist->list[socklist->nr++] = sockfd;
1116 return 1;
1119 #endif
1121 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
1123 if (!listen_addr->nr)
1124 setup_named_sock(NULL, listen_port, socklist);
1125 else {
1126 int i, socknum;
1127 for (i = 0; i < listen_addr->nr; i++) {
1128 socknum = setup_named_sock(listen_addr->items[i].string,
1129 listen_port, socklist);
1131 if (socknum == 0)
1132 logerror("unable to allocate any listen sockets for host %s on port %u",
1133 listen_addr->items[i].string, listen_port);
1138 static int service_loop(struct socketlist *socklist)
1140 struct pollfd *pfd;
1141 int i;
1143 CALLOC_ARRAY(pfd, socklist->nr);
1145 for (i = 0; i < socklist->nr; i++) {
1146 pfd[i].fd = socklist->list[i];
1147 pfd[i].events = POLLIN;
1150 signal(SIGCHLD, child_handler);
1152 for (;;) {
1153 int i;
1155 check_dead_children();
1157 if (poll(pfd, socklist->nr, -1) < 0) {
1158 if (errno != EINTR) {
1159 logerror("Poll failed, resuming: %s",
1160 strerror(errno));
1161 sleep(1);
1163 continue;
1166 for (i = 0; i < socklist->nr; i++) {
1167 if (pfd[i].revents & POLLIN) {
1168 union {
1169 struct sockaddr sa;
1170 struct sockaddr_in sai;
1171 #ifndef NO_IPV6
1172 struct sockaddr_in6 sai6;
1173 #endif
1174 } ss;
1175 socklen_t sslen = sizeof(ss);
1176 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1177 if (incoming < 0) {
1178 switch (errno) {
1179 case EAGAIN:
1180 case EINTR:
1181 case ECONNABORTED:
1182 continue;
1183 default:
1184 die_errno("accept returned");
1187 handle(incoming, &ss.sa, sslen);
1193 #ifdef NO_POSIX_GOODIES
1195 struct credentials;
1197 static void drop_privileges(struct credentials *cred)
1199 /* nothing */
1202 static struct credentials *prepare_credentials(const char *user_name,
1203 const char *group_name)
1205 die("--user not supported on this platform");
1208 #else
1210 struct credentials {
1211 struct passwd *pass;
1212 gid_t gid;
1215 static void drop_privileges(struct credentials *cred)
1217 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1218 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1219 die("cannot drop privileges");
1222 static struct credentials *prepare_credentials(const char *user_name,
1223 const char *group_name)
1225 static struct credentials c;
1227 c.pass = getpwnam(user_name);
1228 if (!c.pass)
1229 die("user not found - %s", user_name);
1231 if (!group_name)
1232 c.gid = c.pass->pw_gid;
1233 else {
1234 struct group *group = getgrnam(group_name);
1235 if (!group)
1236 die("group not found - %s", group_name);
1238 c.gid = group->gr_gid;
1241 return &c;
1243 #endif
1245 static int serve(struct string_list *listen_addr, int listen_port,
1246 struct credentials *cred)
1248 struct socketlist socklist = { NULL, 0, 0 };
1250 socksetup(listen_addr, listen_port, &socklist);
1251 if (socklist.nr == 0)
1252 die("unable to allocate any listen sockets on port %u",
1253 listen_port);
1255 drop_privileges(cred);
1257 loginfo("Ready to rumble");
1259 return service_loop(&socklist);
1262 int cmd_main(int argc, const char **argv)
1264 int listen_port = 0;
1265 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1266 int serve_mode = 0, inetd_mode = 0;
1267 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1268 int detach = 0;
1269 struct credentials *cred = NULL;
1270 int i;
1272 for (i = 1; i < argc; i++) {
1273 const char *arg = argv[i];
1274 const char *v;
1276 if (skip_prefix(arg, "--listen=", &v)) {
1277 string_list_append(&listen_addr, xstrdup_tolower(v));
1278 continue;
1280 if (skip_prefix(arg, "--port=", &v)) {
1281 char *end;
1282 unsigned long n;
1283 n = strtoul(v, &end, 0);
1284 if (*v && !*end) {
1285 listen_port = n;
1286 continue;
1289 if (!strcmp(arg, "--serve")) {
1290 serve_mode = 1;
1291 continue;
1293 if (!strcmp(arg, "--inetd")) {
1294 inetd_mode = 1;
1295 continue;
1297 if (!strcmp(arg, "--verbose")) {
1298 verbose = 1;
1299 continue;
1301 if (!strcmp(arg, "--syslog")) {
1302 log_destination = LOG_DESTINATION_SYSLOG;
1303 continue;
1305 if (skip_prefix(arg, "--log-destination=", &v)) {
1306 if (!strcmp(v, "syslog")) {
1307 log_destination = LOG_DESTINATION_SYSLOG;
1308 continue;
1309 } else if (!strcmp(v, "stderr")) {
1310 log_destination = LOG_DESTINATION_STDERR;
1311 continue;
1312 } else if (!strcmp(v, "none")) {
1313 log_destination = LOG_DESTINATION_NONE;
1314 continue;
1315 } else
1316 die("unknown log destination '%s'", v);
1318 if (!strcmp(arg, "--export-all")) {
1319 export_all_trees = 1;
1320 continue;
1322 if (skip_prefix(arg, "--access-hook=", &v)) {
1323 access_hook = v;
1324 continue;
1326 if (skip_prefix(arg, "--timeout=", &v)) {
1327 timeout = atoi(v);
1328 continue;
1330 if (skip_prefix(arg, "--init-timeout=", &v)) {
1331 init_timeout = atoi(v);
1332 continue;
1334 if (skip_prefix(arg, "--max-connections=", &v)) {
1335 max_connections = atoi(v);
1336 if (max_connections < 0)
1337 max_connections = 0; /* unlimited */
1338 continue;
1340 if (!strcmp(arg, "--strict-paths")) {
1341 strict_paths = 1;
1342 continue;
1344 if (skip_prefix(arg, "--base-path=", &v)) {
1345 base_path = v;
1346 continue;
1348 if (!strcmp(arg, "--base-path-relaxed")) {
1349 base_path_relaxed = 1;
1350 continue;
1352 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1353 interpolated_path = v;
1354 continue;
1356 if (!strcmp(arg, "--reuseaddr")) {
1357 reuseaddr = 1;
1358 continue;
1360 if (!strcmp(arg, "--user-path")) {
1361 user_path = "";
1362 continue;
1364 if (skip_prefix(arg, "--user-path=", &v)) {
1365 user_path = v;
1366 continue;
1368 if (skip_prefix(arg, "--pid-file=", &v)) {
1369 pid_file = v;
1370 continue;
1372 if (!strcmp(arg, "--detach")) {
1373 detach = 1;
1374 continue;
1376 if (skip_prefix(arg, "--user=", &v)) {
1377 user_name = v;
1378 continue;
1380 if (skip_prefix(arg, "--group=", &v)) {
1381 group_name = v;
1382 continue;
1384 if (skip_prefix(arg, "--enable=", &v)) {
1385 enable_service(v, 1);
1386 continue;
1388 if (skip_prefix(arg, "--disable=", &v)) {
1389 enable_service(v, 0);
1390 continue;
1392 if (skip_prefix(arg, "--allow-override=", &v)) {
1393 make_service_overridable(v, 1);
1394 continue;
1396 if (skip_prefix(arg, "--forbid-override=", &v)) {
1397 make_service_overridable(v, 0);
1398 continue;
1400 if (!strcmp(arg, "--informative-errors")) {
1401 informative_errors = 1;
1402 continue;
1404 if (!strcmp(arg, "--no-informative-errors")) {
1405 informative_errors = 0;
1406 continue;
1408 if (!strcmp(arg, "--")) {
1409 ok_paths = &argv[i+1];
1410 break;
1411 } else if (arg[0] != '-') {
1412 ok_paths = &argv[i];
1413 break;
1416 usage(daemon_usage);
1419 if (log_destination == LOG_DESTINATION_UNSET) {
1420 if (inetd_mode || detach)
1421 log_destination = LOG_DESTINATION_SYSLOG;
1422 else
1423 log_destination = LOG_DESTINATION_STDERR;
1426 if (log_destination == LOG_DESTINATION_SYSLOG) {
1427 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1428 set_die_routine(daemon_die);
1429 } else
1430 /* avoid splitting a message in the middle */
1431 setvbuf(stderr, NULL, _IOFBF, 4096);
1433 if (inetd_mode && (detach || group_name || user_name))
1434 die("--detach, --user and --group are incompatible with --inetd");
1436 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1437 die("--listen= and --port= are incompatible with --inetd");
1438 else if (listen_port == 0)
1439 listen_port = DEFAULT_GIT_PORT;
1441 if (group_name && !user_name)
1442 die("--group supplied without --user");
1444 if (user_name)
1445 cred = prepare_credentials(user_name, group_name);
1447 if (strict_paths && (!ok_paths || !*ok_paths))
1448 die("option --strict-paths requires '<directory>' arguments");
1450 if (base_path && !is_directory(base_path))
1451 die("base-path '%s' does not exist or is not a directory",
1452 base_path);
1454 if (log_destination != LOG_DESTINATION_STDERR) {
1455 if (!freopen("/dev/null", "w", stderr))
1456 die_errno("failed to redirect stderr to /dev/null");
1459 if (inetd_mode || serve_mode)
1460 return execute();
1462 if (detach) {
1463 if (daemonize())
1464 die("--detach not supported on this platform");
1467 if (pid_file)
1468 write_file(pid_file, "%"PRIuMAX, (uintmax_t) getpid());
1470 /* prepare argv for serving-processes */
1471 strvec_push(&cld_argv, argv[0]); /* git-daemon */
1472 strvec_push(&cld_argv, "--serve");
1473 for (i = 1; i < argc; ++i)
1474 strvec_push(&cld_argv, argv[i]);
1476 return serve(&listen_addr, listen_port, cred);