4 #include "run-command.h"
 
   6 #include "string-list.h"
 
   9 #define initgroups(x, y) (0) /* nothing */
 
  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;
 
  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"
 
  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;
 
  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;
 
  67 static void lookup_hostname(struct hostinfo *hi);
 
  69 static const char *get_canon_hostname(struct hostinfo *hi)
 
  72         return hi->canon_hostname.buf;
 
  75 static const char *get_ip_address(struct hostinfo *hi)
 
  78         return hi->ip_address.buf;
 
  81 static void logreport(int priority, const char *err, va_list params)
 
  83         switch (log_destination) {
 
  84         case LOG_DESTINATION_SYSLOG: {
 
  86                 vsnprintf(buf, sizeof(buf), err, params);
 
  87                 syslog(priority, "%s", buf);
 
  90         case LOG_DESTINATION_STDERR:
 
  92                  * Since stderr is set to buffered mode, the
 
  93                  * logging of different processes will not overlap
 
  94                  * unless they overflow the (rather big) buffers.
 
  96                 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
 
  97                 vfprintf(stderr, err, params);
 
 101         case LOG_DESTINATION_NONE:
 
 103         case LOG_DESTINATION_UNSET:
 
 104                 BUG("log destination not initialized correctly");
 
 108 __attribute__((format (printf, 1, 2)))
 
 109 static void logerror(const char *err, ...)
 
 112         va_start(params, err);
 
 113         logreport(LOG_ERR, err, params);
 
 117 __attribute__((format (printf, 1, 2)))
 
 118 static void loginfo(const char *err, ...)
 
 123         va_start(params, err);
 
 124         logreport(LOG_INFO, err, params);
 
 128 static void NORETURN daemon_die(const char *err, va_list params)
 
 130         logreport(LOG_ERR, err, params);
 
 134 struct expand_path_context {
 
 135         const char *directory;
 
 136         struct hostinfo *hostinfo;
 
 139 static size_t expand_path(struct strbuf *sb, const char *placeholder, void *ctx)
 
 141         struct expand_path_context *context = ctx;
 
 142         struct hostinfo *hi = context->hostinfo;
 
 144         switch (placeholder[0]) {
 
 146                 strbuf_addbuf(sb, &hi->hostname);
 
 149                 if (placeholder[1] == 'H') {
 
 150                         strbuf_addstr(sb, get_canon_hostname(hi));
 
 155                 if (placeholder[1] == 'P') {
 
 156                         strbuf_addstr(sb, get_ip_address(hi));
 
 161                 strbuf_addbuf(sb, &hi->tcp_port);
 
 164                 strbuf_addstr(sb, context->directory);
 
 170 static const char *path_ok(const char *directory, struct hostinfo *hi)
 
 172         static char rpath[PATH_MAX];
 
 173         static char interp_path[PATH_MAX];
 
 180         if (daemon_avoid_alias(dir)) {
 
 181                 logerror("'%s': aliased", dir);
 
 187                         logerror("'%s': User-path not allowed", dir);
 
 191                         /* Got either "~alice" or "~alice/foo";
 
 192                          * rewrite them to "~alice/%s" or
 
 195                         int namlen, restlen = strlen(dir);
 
 196                         const char *slash = strchr(dir, '/');
 
 198                                 slash = dir + restlen;
 
 199                         namlen = slash - dir;
 
 201                         loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
 
 202                         rlen = snprintf(rpath, sizeof(rpath), "%.*s/%s%.*s",
 
 203                                         namlen, dir, user_path, restlen, slash);
 
 204                         if (rlen >= sizeof(rpath)) {
 
 205                                 logerror("user-path too large: %s", rpath);
 
 211         else if (interpolated_path && hi->saw_extended_args) {
 
 212                 struct strbuf expanded_path = STRBUF_INIT;
 
 213                 struct expand_path_context context;
 
 215                 context.directory = directory;
 
 216                 context.hostinfo = hi;
 
 219                         /* Allow only absolute */
 
 220                         logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
 
 224                 strbuf_expand(&expanded_path, interpolated_path,
 
 225                               expand_path, &context);
 
 227                 rlen = strlcpy(interp_path, expanded_path.buf,
 
 228                                sizeof(interp_path));
 
 229                 if (rlen >= sizeof(interp_path)) {
 
 230                         logerror("interpolated path too large: %s",
 
 235                 strbuf_release(&expanded_path);
 
 236                 loginfo("Interpolated dir '%s'", interp_path);
 
 240         else if (base_path) {
 
 242                         /* Allow only absolute */
 
 243                         logerror("'%s': Non-absolute path denied (base-path active)", dir);
 
 246                 rlen = snprintf(rpath, sizeof(rpath), "%s%s", base_path, dir);
 
 247                 if (rlen >= sizeof(rpath)) {
 
 248                         logerror("base-path too large: %s", rpath);
 
 254         path = enter_repo(dir, strict_paths);
 
 255         if (!path && base_path && base_path_relaxed) {
 
 257                  * if we fail and base_path_relaxed is enabled, try without
 
 258                  * prefixing the base path
 
 261                 path = enter_repo(dir, strict_paths);
 
 265                 logerror("'%s' does not appear to be a git repository", dir);
 
 269         if ( ok_paths && *ok_paths ) {
 
 271                 int pathlen = strlen(path);
 
 273                 /* The validation is done on the paths after enter_repo
 
 274                  * appends optional {.git,.git/.git} and friends, but
 
 275                  * it does not use getcwd().  So if your /pub is
 
 276                  * a symlink to /mnt/pub, you can whitelist /pub and
 
 277                  * do not have to say /mnt/pub.
 
 280                 for ( pp = ok_paths ; *pp ; pp++ ) {
 
 281                         int len = strlen(*pp);
 
 282                         if (len <= pathlen &&
 
 283                             !memcmp(*pp, path, len) &&
 
 284                             (path[len] == '\0' ||
 
 285                              (!strict_paths && path[len] == '/')))
 
 290                 /* be backwards compatible */
 
 295         logerror("'%s': not in whitelist", path);
 
 296         return NULL;            /* Fallthrough. Deny by default */
 
 299 typedef int (*daemon_service_fn)(const struct argv_array *env);
 
 300 struct daemon_service {
 
 302         const char *config_name;
 
 303         daemon_service_fn fn;
 
 308 static int daemon_error(const char *dir, const char *msg)
 
 310         if (!informative_errors)
 
 311                 msg = "access denied or repository not exported";
 
 312         packet_write_fmt(1, "ERR %s: %s", msg, dir);
 
 316 static const char *access_hook;
 
 318 static int run_access_hook(struct daemon_service *service, const char *dir,
 
 319                            const char *path, struct hostinfo *hi)
 
 321         struct child_process child = CHILD_PROCESS_INIT;
 
 322         struct strbuf buf = STRBUF_INIT;
 
 324         const char **arg = argv;
 
 328         *arg++ = access_hook;
 
 329         *arg++ = service->name;
 
 331         *arg++ = hi->hostname.buf;
 
 332         *arg++ = get_canon_hostname(hi);
 
 333         *arg++ = get_ip_address(hi);
 
 334         *arg++ = hi->tcp_port.buf;
 
 342         if (start_command(&child)) {
 
 343                 logerror("daemon access hook '%s' failed to start",
 
 347         if (strbuf_read(&buf, child.out, 0) < 0) {
 
 348                 logerror("failed to read from pipe to daemon access hook '%s'",
 
 353         if (close(child.out) < 0) {
 
 354                 logerror("failed to close pipe to daemon access hook '%s'",
 
 358         if (finish_command(&child))
 
 362                 strbuf_release(&buf);
 
 369                 strbuf_addstr(&buf, "service rejected");
 
 370         eol = strchr(buf.buf, '\n');
 
 374         daemon_error(dir, buf.buf);
 
 375         strbuf_release(&buf);
 
 379 static int run_service(const char *dir, struct daemon_service *service,
 
 380                        struct hostinfo *hi, const struct argv_array *env)
 
 383         int enabled = service->enabled;
 
 384         struct strbuf var = STRBUF_INIT;
 
 386         loginfo("Request %s for '%s'", service->name, dir);
 
 388         if (!enabled && !service->overridable) {
 
 389                 logerror("'%s': service not enabled.", service->name);
 
 391                 return daemon_error(dir, "service not enabled");
 
 394         if (!(path = path_ok(dir, hi)))
 
 395                 return daemon_error(dir, "no such repository");
 
 398          * Security on the cheap.
 
 400          * We want a readable HEAD, usable "objects" directory, and
 
 401          * a "git-daemon-export-ok" flag that says that the other side
 
 402          * is ok with us doing this.
 
 404          * path_ok() uses enter_repo() and does whitelist checking.
 
 405          * We only need to make sure the repository is exported.
 
 408         if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
 
 409                 logerror("'%s': repository not exported.", path);
 
 411                 return daemon_error(dir, "repository not exported");
 
 414         if (service->overridable) {
 
 415                 strbuf_addf(&var, "daemon.%s", service->config_name);
 
 416                 git_config_get_bool(var.buf, &enabled);
 
 417                 strbuf_release(&var);
 
 420                 logerror("'%s': service not enabled for '%s'",
 
 421                          service->name, path);
 
 423                 return daemon_error(dir, "service not enabled");
 
 427          * Optionally, a hook can choose to deny access to the
 
 428          * repository depending on the phase of the moon.
 
 430         if (access_hook && run_access_hook(service, dir, path, hi))
 
 434          * We'll ignore SIGTERM from now on, we have a
 
 437         signal(SIGTERM, SIG_IGN);
 
 439         return service->fn(env);
 
 442 static void copy_to_log(int fd)
 
 444         struct strbuf line = STRBUF_INIT;
 
 447         fp = fdopen(fd, "r");
 
 449                 logerror("fdopen of error channel failed");
 
 454         while (strbuf_getline_lf(&line, fp) != EOF) {
 
 455                 logerror("%s", line.buf);
 
 456                 strbuf_setlen(&line, 0);
 
 459         strbuf_release(&line);
 
 463 static int run_service_command(struct child_process *cld)
 
 465         argv_array_push(&cld->args, ".");
 
 468         if (start_command(cld))
 
 474         copy_to_log(cld->err);
 
 476         return finish_command(cld);
 
 479 static int upload_pack(const struct argv_array *env)
 
 481         struct child_process cld = CHILD_PROCESS_INIT;
 
 482         argv_array_pushl(&cld.args, "upload-pack", "--strict", NULL);
 
 483         argv_array_pushf(&cld.args, "--timeout=%u", timeout);
 
 485         argv_array_pushv(&cld.env_array, env->argv);
 
 487         return run_service_command(&cld);
 
 490 static int upload_archive(const struct argv_array *env)
 
 492         struct child_process cld = CHILD_PROCESS_INIT;
 
 493         argv_array_push(&cld.args, "upload-archive");
 
 495         argv_array_pushv(&cld.env_array, env->argv);
 
 497         return run_service_command(&cld);
 
 500 static int receive_pack(const struct argv_array *env)
 
 502         struct child_process cld = CHILD_PROCESS_INIT;
 
 503         argv_array_push(&cld.args, "receive-pack");
 
 505         argv_array_pushv(&cld.env_array, env->argv);
 
 507         return run_service_command(&cld);
 
 510 static struct daemon_service daemon_service[] = {
 
 511         { "upload-archive", "uploadarch", upload_archive, 0, 1 },
 
 512         { "upload-pack", "uploadpack", upload_pack, 1, 1 },
 
 513         { "receive-pack", "receivepack", receive_pack, 0, 1 },
 
 516 static void enable_service(const char *name, int ena)
 
 519         for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
 
 520                 if (!strcmp(daemon_service[i].name, name)) {
 
 521                         daemon_service[i].enabled = ena;
 
 525         die("No such service %s", name);
 
 528 static void make_service_overridable(const char *name, int ena)
 
 531         for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
 
 532                 if (!strcmp(daemon_service[i].name, name)) {
 
 533                         daemon_service[i].overridable = ena;
 
 537         die("No such service %s", name);
 
 540 static void parse_host_and_port(char *hostport, char **host,
 
 543         if (*hostport == '[') {
 
 546                 end = strchr(hostport, ']');
 
 548                         die("Invalid request ('[' without ']')");
 
 550                 *host = hostport + 1;
 
 553                 else if (end[1] == ':')
 
 556                         die("Garbage after end of host part");
 
 559                 *port = strrchr(hostport, ':');
 
 568  * Sanitize a string from the client so that it's OK to be inserted into a
 
 569  * filesystem path. Specifically, we disallow slashes, runs of "..", and
 
 570  * trailing and leading dots, which means that the client cannot escape
 
 571  * our base path via ".." traversal.
 
 573 static void sanitize_client(struct strbuf *out, const char *in)
 
 578                 if (*in == '.' && (!out->len || out->buf[out->len - 1] == '.'))
 
 580                 strbuf_addch(out, *in);
 
 583         while (out->len && out->buf[out->len - 1] == '.')
 
 584                 strbuf_setlen(out, out->len - 1);
 
 588  * Like sanitize_client, but we also perform any canonicalization
 
 589  * to make life easier on the admin.
 
 591 static void canonicalize_client(struct strbuf *out, const char *in)
 
 593         sanitize_client(out, in);
 
 598  * Read the host as supplied by the client connection.
 
 600  * Returns a pointer to the character after the NUL byte terminating the host
 
 601  * arguemnt, or 'extra_args' if there is no host arguemnt.
 
 603 static char *parse_host_arg(struct hostinfo *hi, char *extra_args, int buflen)
 
 607         char *end = extra_args + buflen;
 
 609         if (extra_args < end && *extra_args) {
 
 610                 hi->saw_extended_args = 1;
 
 611                 if (strncasecmp("host=", extra_args, 5) == 0) {
 
 612                         val = extra_args + 5;
 
 613                         vallen = strlen(val) + 1;
 
 614                         loginfo("Extended attribute \"host\": %s", val);
 
 616                                 /* Split <host>:<port> at colon. */
 
 619                                 parse_host_and_port(val, &host, &port);
 
 621                                         sanitize_client(&hi->tcp_port, port);
 
 622                                 canonicalize_client(&hi->hostname, host);
 
 623                                 hi->hostname_lookup_done = 0;
 
 626                         /* On to the next one */
 
 627                         extra_args = val + vallen;
 
 629                 if (extra_args < end && *extra_args)
 
 630                         die("Invalid request");
 
 636 static void parse_extra_args(struct hostinfo *hi, struct argv_array *env,
 
 637                              char *extra_args, int buflen)
 
 639         const char *end = extra_args + buflen;
 
 640         struct strbuf git_protocol = STRBUF_INIT;
 
 642         /* First look for the host argument */
 
 643         extra_args = parse_host_arg(hi, extra_args, buflen);
 
 645         /* Look for additional arguments places after a second NUL byte */
 
 646         for (; extra_args < end; extra_args += strlen(extra_args) + 1) {
 
 647                 const char *arg = extra_args;
 
 650                  * Parse the extra arguments, adding most to 'git_protocol'
 
 651                  * which will be used to set the 'GIT_PROTOCOL' envvar in the
 
 652                  * service that will be run.
 
 654                  * If there ends up being a particular arg in the future that
 
 655                  * git-daemon needs to parse specificly (like the 'host' arg)
 
 656                  * then it can be parsed here and not added to 'git_protocol'.
 
 659                         if (git_protocol.len > 0)
 
 660                                 strbuf_addch(&git_protocol, ':');
 
 661                         strbuf_addstr(&git_protocol, arg);
 
 665         if (git_protocol.len > 0) {
 
 666                 loginfo("Extended attribute \"protocol\": %s", git_protocol.buf);
 
 667                 argv_array_pushf(env, GIT_PROTOCOL_ENVIRONMENT "=%s",
 
 670         strbuf_release(&git_protocol);
 
 674  * Locate canonical hostname and its IP address.
 
 676 static void lookup_hostname(struct hostinfo *hi)
 
 678         if (!hi->hostname_lookup_done && hi->hostname.len) {
 
 680                 struct addrinfo hints;
 
 683                 static char addrbuf[HOST_NAME_MAX + 1];
 
 685                 memset(&hints, 0, sizeof(hints));
 
 686                 hints.ai_flags = AI_CANONNAME;
 
 688                 gai = getaddrinfo(hi->hostname.buf, NULL, &hints, &ai);
 
 690                         struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
 
 692                         inet_ntop(AF_INET, &sin_addr->sin_addr,
 
 693                                   addrbuf, sizeof(addrbuf));
 
 694                         strbuf_addstr(&hi->ip_address, addrbuf);
 
 696                         if (ai->ai_canonname)
 
 697                                 sanitize_client(&hi->canon_hostname,
 
 700                                 strbuf_addbuf(&hi->canon_hostname,
 
 706                 struct hostent *hent;
 
 707                 struct sockaddr_in sa;
 
 709                 static char addrbuf[HOST_NAME_MAX + 1];
 
 711                 hent = gethostbyname(hi->hostname.buf);
 
 713                         ap = hent->h_addr_list;
 
 714                         memset(&sa, 0, sizeof sa);
 
 715                         sa.sin_family = hent->h_addrtype;
 
 716                         sa.sin_port = htons(0);
 
 717                         memcpy(&sa.sin_addr, *ap, hent->h_length);
 
 719                         inet_ntop(hent->h_addrtype, &sa.sin_addr,
 
 720                                   addrbuf, sizeof(addrbuf));
 
 722                         sanitize_client(&hi->canon_hostname, hent->h_name);
 
 723                         strbuf_addstr(&hi->ip_address, addrbuf);
 
 726                 hi->hostname_lookup_done = 1;
 
 730 static void hostinfo_init(struct hostinfo *hi)
 
 732         memset(hi, 0, sizeof(*hi));
 
 733         strbuf_init(&hi->hostname, 0);
 
 734         strbuf_init(&hi->canon_hostname, 0);
 
 735         strbuf_init(&hi->ip_address, 0);
 
 736         strbuf_init(&hi->tcp_port, 0);
 
 739 static void hostinfo_clear(struct hostinfo *hi)
 
 741         strbuf_release(&hi->hostname);
 
 742         strbuf_release(&hi->canon_hostname);
 
 743         strbuf_release(&hi->ip_address);
 
 744         strbuf_release(&hi->tcp_port);
 
 747 static void set_keep_alive(int sockfd)
 
 751         if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0) {
 
 752                 if (errno != ENOTSOCK)
 
 753                         logerror("unable to set SO_KEEPALIVE on socket: %s",
 
 758 static int execute(void)
 
 760         char *line = packet_buffer;
 
 762         char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
 
 764         struct argv_array env = ARGV_ARRAY_INIT;
 
 769                 loginfo("Connection from %s:%s", addr, port);
 
 772         alarm(init_timeout ? init_timeout : timeout);
 
 773         pktlen = packet_read(0, NULL, NULL, packet_buffer, sizeof(packet_buffer), 0);
 
 777         if (len && line[len-1] == '\n')
 
 780         /* parse additional args hidden behind a NUL byte */
 
 782                 parse_extra_args(&hi, &env, line + len + 1, pktlen - len - 1);
 
 784         for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
 
 785                 struct daemon_service *s = &(daemon_service[i]);
 
 788                 if (skip_prefix(line, "git-", &arg) &&
 
 789                     skip_prefix(arg, s->name, &arg) &&
 
 792                          * Note: The directory here is probably context sensitive,
 
 793                          * and might depend on the actual service being performed.
 
 795                         int rc = run_service(arg, s, &hi, &env);
 
 797                         argv_array_clear(&env);
 
 803         argv_array_clear(&env);
 
 804         logerror("Protocol error: '%s'", line);
 
 808 static int addrcmp(const struct sockaddr_storage *s1,
 
 809     const struct sockaddr_storage *s2)
 
 811         const struct sockaddr *sa1 = (const struct sockaddr*) s1;
 
 812         const struct sockaddr *sa2 = (const struct sockaddr*) s2;
 
 814         if (sa1->sa_family != sa2->sa_family)
 
 815                 return sa1->sa_family - sa2->sa_family;
 
 816         if (sa1->sa_family == AF_INET)
 
 817                 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
 
 818                     &((struct sockaddr_in *)s2)->sin_addr,
 
 819                     sizeof(struct in_addr));
 
 821         if (sa1->sa_family == AF_INET6)
 
 822                 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
 
 823                     &((struct sockaddr_in6 *)s2)->sin6_addr,
 
 824                     sizeof(struct in6_addr));
 
 829 static int max_connections = 32;
 
 831 static unsigned int live_children;
 
 833 static struct child {
 
 835         struct child_process cld;
 
 836         struct sockaddr_storage address;
 
 839 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
 
 841         struct child *newborn, **cradle;
 
 843         newborn = xcalloc(1, sizeof(*newborn));
 
 845         memcpy(&newborn->cld, cld, sizeof(*cld));
 
 846         memcpy(&newborn->address, addr, addrlen);
 
 847         for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
 
 848                 if (!addrcmp(&(*cradle)->address, &newborn->address))
 
 850         newborn->next = *cradle;
 
 855  * This gets called if the number of connections grows
 
 856  * past "max_connections".
 
 858  * We kill the newest connection from a duplicate IP.
 
 860 static void kill_some_child(void)
 
 862         const struct child *blanket, *next;
 
 864         if (!(blanket = firstborn))
 
 867         for (; (next = blanket->next); blanket = next)
 
 868                 if (!addrcmp(&blanket->address, &next->address)) {
 
 869                         kill(blanket->cld.pid, SIGTERM);
 
 874 static void check_dead_children(void)
 
 879         struct child **cradle, *blanket;
 
 880         for (cradle = &firstborn; (blanket = *cradle);)
 
 881                 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
 
 882                         const char *dead = "";
 
 884                                 dead = " (with error)";
 
 885                         loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
 
 887                         /* remove the child */
 
 888                         *cradle = blanket->next;
 
 890                         child_process_clear(&blanket->cld);
 
 893                         cradle = &blanket->next;
 
 896 static struct argv_array cld_argv = ARGV_ARRAY_INIT;
 
 897 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
 
 899         struct child_process cld = CHILD_PROCESS_INIT;
 
 901         if (max_connections && live_children >= max_connections) {
 
 903                 sleep(1);  /* give it some time to die */
 
 904                 check_dead_children();
 
 905                 if (live_children >= max_connections) {
 
 907                         logerror("Too many children, dropping connection");
 
 912         if (addr->sa_family == AF_INET) {
 
 914                 struct sockaddr_in *sin_addr = (void *) addr;
 
 915                 inet_ntop(addr->sa_family, &sin_addr->sin_addr, buf, sizeof(buf));
 
 916                 argv_array_pushf(&cld.env_array, "REMOTE_ADDR=%s", buf);
 
 917                 argv_array_pushf(&cld.env_array, "REMOTE_PORT=%d",
 
 918                                  ntohs(sin_addr->sin_port));
 
 920         } else if (addr->sa_family == AF_INET6) {
 
 922                 struct sockaddr_in6 *sin6_addr = (void *) addr;
 
 923                 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(buf));
 
 924                 argv_array_pushf(&cld.env_array, "REMOTE_ADDR=[%s]", buf);
 
 925                 argv_array_pushf(&cld.env_array, "REMOTE_PORT=%d",
 
 926                                  ntohs(sin6_addr->sin6_port));
 
 930         cld.argv = cld_argv.argv;
 
 932         cld.out = dup(incoming);
 
 934         if (start_command(&cld))
 
 935                 logerror("unable to fork");
 
 937                 add_child(&cld, addr, addrlen);
 
 940 static void child_handler(int signo)
 
 943          * Otherwise empty handler because systemcalls will get interrupted
 
 944          * upon signal receipt
 
 945          * SysV needs the handler to be rearmed
 
 947         signal(SIGCHLD, child_handler);
 
 950 static int set_reuse_addr(int sockfd)
 
 956         return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
 
 966 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
 
 969         static char ip[INET_ADDRSTRLEN];
 
 971         static char ip[INET6_ADDRSTRLEN];
 
 977                 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
 
 981                 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
 
 984                 xsnprintf(ip, sizeof(ip), "<unknown>");
 
 991 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
 
 994         char pbuf[NI_MAXSERV];
 
 995         struct addrinfo hints, *ai0, *ai;
 
 999         xsnprintf(pbuf, sizeof(pbuf), "%d", listen_port);
 
1000         memset(&hints, 0, sizeof(hints));
 
1001         hints.ai_family = AF_UNSPEC;
 
1002         hints.ai_socktype = SOCK_STREAM;
 
1003         hints.ai_protocol = IPPROTO_TCP;
 
1004         hints.ai_flags = AI_PASSIVE;
 
1006         gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
 
1008                 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
 
1012         for (ai = ai0; ai; ai = ai->ai_next) {
 
1015                 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
 
1018                 if (sockfd >= FD_SETSIZE) {
 
1019                         logerror("Socket descriptor too large");
 
1025                 if (ai->ai_family == AF_INET6) {
 
1027                         setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
 
1029                         /* Note: error is not fatal */
 
1033                 if (set_reuse_addr(sockfd)) {
 
1034                         logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
 
1039                 set_keep_alive(sockfd);
 
1041                 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
 
1042                         logerror("Could not bind to %s: %s",
 
1043                                  ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
 
1046                         continue;       /* not fatal */
 
1048                 if (listen(sockfd, 5) < 0) {
 
1049                         logerror("Could not listen to %s: %s",
 
1050                                  ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
 
1053                         continue;       /* not fatal */
 
1056                 flags = fcntl(sockfd, F_GETFD, 0);
 
1058                         fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
 
1060                 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
 
1061                 socklist->list[socklist->nr++] = sockfd;
 
1072 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
 
1074         struct sockaddr_in sin;
 
1078         memset(&sin, 0, sizeof sin);
 
1079         sin.sin_family = AF_INET;
 
1080         sin.sin_port = htons(listen_port);
 
1083                 /* Well, host better be an IP address here. */
 
1084                 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
 
1087                 sin.sin_addr.s_addr = htonl(INADDR_ANY);
 
1090         sockfd = socket(AF_INET, SOCK_STREAM, 0);
 
1094         if (set_reuse_addr(sockfd)) {
 
1095                 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
 
1100         set_keep_alive(sockfd);
 
1102         if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
 
1103                 logerror("Could not bind to %s: %s",
 
1104                          ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
 
1110         if (listen(sockfd, 5) < 0) {
 
1111                 logerror("Could not listen to %s: %s",
 
1112                          ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
 
1118         flags = fcntl(sockfd, F_GETFD, 0);
 
1120                 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
 
1122         ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
 
1123         socklist->list[socklist->nr++] = sockfd;
 
1129 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
 
1131         if (!listen_addr->nr)
 
1132                 setup_named_sock(NULL, listen_port, socklist);
 
1135                 for (i = 0; i < listen_addr->nr; i++) {
 
1136                         socknum = setup_named_sock(listen_addr->items[i].string,
 
1137                                                    listen_port, socklist);
 
1140                                 logerror("unable to allocate any listen sockets for host %s on port %u",
 
1141                                          listen_addr->items[i].string, listen_port);
 
1146 static int service_loop(struct socketlist *socklist)
 
1151         pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
 
1153         for (i = 0; i < socklist->nr; i++) {
 
1154                 pfd[i].fd = socklist->list[i];
 
1155                 pfd[i].events = POLLIN;
 
1158         signal(SIGCHLD, child_handler);
 
1163                 check_dead_children();
 
1165                 if (poll(pfd, socklist->nr, -1) < 0) {
 
1166                         if (errno != EINTR) {
 
1167                                 logerror("Poll failed, resuming: %s",
 
1174                 for (i = 0; i < socklist->nr; i++) {
 
1175                         if (pfd[i].revents & POLLIN) {
 
1178                                         struct sockaddr_in sai;
 
1180                                         struct sockaddr_in6 sai6;
 
1183                                 socklen_t sslen = sizeof(ss);
 
1184                                 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
 
1192                                                 die_errno("accept returned");
 
1195                                 handle(incoming, &ss.sa, sslen);
 
1201 #ifdef NO_POSIX_GOODIES
 
1205 static void drop_privileges(struct credentials *cred)
 
1210 static struct credentials *prepare_credentials(const char *user_name,
 
1211     const char *group_name)
 
1213         die("--user not supported on this platform");
 
1218 struct credentials {
 
1219         struct passwd *pass;
 
1223 static void drop_privileges(struct credentials *cred)
 
1225         if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
 
1226             setgid (cred->gid) || setuid(cred->pass->pw_uid)))
 
1227                 die("cannot drop privileges");
 
1230 static struct credentials *prepare_credentials(const char *user_name,
 
1231     const char *group_name)
 
1233         static struct credentials c;
 
1235         c.pass = getpwnam(user_name);
 
1237                 die("user not found - %s", user_name);
 
1240                 c.gid = c.pass->pw_gid;
 
1242                 struct group *group = getgrnam(group_name);
 
1244                         die("group not found - %s", group_name);
 
1246                 c.gid = group->gr_gid;
 
1253 static int serve(struct string_list *listen_addr, int listen_port,
 
1254     struct credentials *cred)
 
1256         struct socketlist socklist = { NULL, 0, 0 };
 
1258         socksetup(listen_addr, listen_port, &socklist);
 
1259         if (socklist.nr == 0)
 
1260                 die("unable to allocate any listen sockets on port %u",
 
1263         drop_privileges(cred);
 
1265         loginfo("Ready to rumble");
 
1267         return service_loop(&socklist);
 
1270 int cmd_main(int argc, const char **argv)
 
1272         int listen_port = 0;
 
1273         struct string_list listen_addr = STRING_LIST_INIT_NODUP;
 
1274         int serve_mode = 0, inetd_mode = 0;
 
1275         const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
 
1277         struct credentials *cred = NULL;
 
1280         for (i = 1; i < argc; i++) {
 
1281                 const char *arg = argv[i];
 
1284                 if (skip_prefix(arg, "--listen=", &v)) {
 
1285                         string_list_append(&listen_addr, xstrdup_tolower(v));
 
1288                 if (skip_prefix(arg, "--port=", &v)) {
 
1291                         n = strtoul(v, &end, 0);
 
1297                 if (!strcmp(arg, "--serve")) {
 
1301                 if (!strcmp(arg, "--inetd")) {
 
1305                 if (!strcmp(arg, "--verbose")) {
 
1309                 if (!strcmp(arg, "--syslog")) {
 
1310                         log_destination = LOG_DESTINATION_SYSLOG;
 
1313                 if (skip_prefix(arg, "--log-destination=", &v)) {
 
1314                         if (!strcmp(v, "syslog")) {
 
1315                                 log_destination = LOG_DESTINATION_SYSLOG;
 
1317                         } else if (!strcmp(v, "stderr")) {
 
1318                                 log_destination = LOG_DESTINATION_STDERR;
 
1320                         } else if (!strcmp(v, "none")) {
 
1321                                 log_destination = LOG_DESTINATION_NONE;
 
1324                                 die("unknown log destination '%s'", v);
 
1326                 if (!strcmp(arg, "--export-all")) {
 
1327                         export_all_trees = 1;
 
1330                 if (skip_prefix(arg, "--access-hook=", &v)) {
 
1334                 if (skip_prefix(arg, "--timeout=", &v)) {
 
1338                 if (skip_prefix(arg, "--init-timeout=", &v)) {
 
1339                         init_timeout = atoi(v);
 
1342                 if (skip_prefix(arg, "--max-connections=", &v)) {
 
1343                         max_connections = atoi(v);
 
1344                         if (max_connections < 0)
 
1345                                 max_connections = 0;            /* unlimited */
 
1348                 if (!strcmp(arg, "--strict-paths")) {
 
1352                 if (skip_prefix(arg, "--base-path=", &v)) {
 
1356                 if (!strcmp(arg, "--base-path-relaxed")) {
 
1357                         base_path_relaxed = 1;
 
1360                 if (skip_prefix(arg, "--interpolated-path=", &v)) {
 
1361                         interpolated_path = v;
 
1364                 if (!strcmp(arg, "--reuseaddr")) {
 
1368                 if (!strcmp(arg, "--user-path")) {
 
1372                 if (skip_prefix(arg, "--user-path=", &v)) {
 
1376                 if (skip_prefix(arg, "--pid-file=", &v)) {
 
1380                 if (!strcmp(arg, "--detach")) {
 
1384                 if (skip_prefix(arg, "--user=", &v)) {
 
1388                 if (skip_prefix(arg, "--group=", &v)) {
 
1392                 if (skip_prefix(arg, "--enable=", &v)) {
 
1393                         enable_service(v, 1);
 
1396                 if (skip_prefix(arg, "--disable=", &v)) {
 
1397                         enable_service(v, 0);
 
1400                 if (skip_prefix(arg, "--allow-override=", &v)) {
 
1401                         make_service_overridable(v, 1);
 
1404                 if (skip_prefix(arg, "--forbid-override=", &v)) {
 
1405                         make_service_overridable(v, 0);
 
1408                 if (!strcmp(arg, "--informative-errors")) {
 
1409                         informative_errors = 1;
 
1412                 if (!strcmp(arg, "--no-informative-errors")) {
 
1413                         informative_errors = 0;
 
1416                 if (!strcmp(arg, "--")) {
 
1417                         ok_paths = &argv[i+1];
 
1419                 } else if (arg[0] != '-') {
 
1420                         ok_paths = &argv[i];
 
1424                 usage(daemon_usage);
 
1427         if (log_destination == LOG_DESTINATION_UNSET) {
 
1428                 if (inetd_mode || detach)
 
1429                         log_destination = LOG_DESTINATION_SYSLOG;
 
1431                         log_destination = LOG_DESTINATION_STDERR;
 
1434         if (log_destination == LOG_DESTINATION_SYSLOG) {
 
1435                 openlog("git-daemon", LOG_PID, LOG_DAEMON);
 
1436                 set_die_routine(daemon_die);
 
1438                 /* avoid splitting a message in the middle */
 
1439                 setvbuf(stderr, NULL, _IOFBF, 4096);
 
1441         if (inetd_mode && (detach || group_name || user_name))
 
1442                 die("--detach, --user and --group are incompatible with --inetd");
 
1444         if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
 
1445                 die("--listen= and --port= are incompatible with --inetd");
 
1446         else if (listen_port == 0)
 
1447                 listen_port = DEFAULT_GIT_PORT;
 
1449         if (group_name && !user_name)
 
1450                 die("--group supplied without --user");
 
1453                 cred = prepare_credentials(user_name, group_name);
 
1455         if (strict_paths && (!ok_paths || !*ok_paths))
 
1456                 die("option --strict-paths requires a whitelist");
 
1458         if (base_path && !is_directory(base_path))
 
1459                 die("base-path '%s' does not exist or is not a directory",
 
1462         if (log_destination != LOG_DESTINATION_STDERR) {
 
1463                 if (!freopen("/dev/null", "w", stderr))
 
1464                         die_errno("failed to redirect stderr to /dev/null");
 
1467         if (inetd_mode || serve_mode)
 
1472                         die("--detach not supported on this platform");
 
1476                 write_file(pid_file, "%"PRIuMAX, (uintmax_t) getpid());
 
1478         /* prepare argv for serving-processes */
 
1479         argv_array_push(&cld_argv, argv[0]); /* git-daemon */
 
1480         argv_array_push(&cld_argv, "--serve");
 
1481         for (i = 1; i < argc; ++i)
 
1482                 argv_array_push(&cld_argv, argv[i]);
 
1484         return serve(&listen_addr, listen_port, cred);