daemon.con commit xgethostname: handle long hostnames (5781a9a)
   1#include "cache.h"
   2#include "pkt-line.h"
   3#include "run-command.h"
   4#include "strbuf.h"
   5#include "string-list.h"
   6
   7#ifdef NO_INITGROUPS
   8#define initgroups(x, y) (0) /* nothing */
   9#endif
  10
  11static int log_syslog;
  12static int verbose;
  13static int reuseaddr;
  14static int informative_errors;
  15
  16static const char daemon_usage[] =
  17"git daemon [--verbose] [--syslog] [--export-all]\n"
  18"           [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
  19"           [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
  20"           [--user-path | --user-path=<path>]\n"
  21"           [--interpolated-path=<path>]\n"
  22"           [--reuseaddr] [--pid-file=<file>]\n"
  23"           [--(enable|disable|allow-override|forbid-override)=<service>]\n"
  24"           [--access-hook=<path>]\n"
  25"           [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
  26"                      [--detach] [--user=<user> [--group=<group>]]\n"
  27"           [<directory>...]";
  28
  29/* List of acceptable pathname prefixes */
  30static const char **ok_paths;
  31static int strict_paths;
  32
  33/* If this is set, git-daemon-export-ok is not required */
  34static int export_all_trees;
  35
  36/* Take all paths relative to this one if non-NULL */
  37static const char *base_path;
  38static const char *interpolated_path;
  39static int base_path_relaxed;
  40
  41/* If defined, ~user notation is allowed and the string is inserted
  42 * after ~user/.  E.g. a request to git://host/~alice/frotz would
  43 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
  44 */
  45static const char *user_path;
  46
  47/* Timeout, and initial timeout */
  48static unsigned int timeout;
  49static unsigned int init_timeout;
  50
  51struct hostinfo {
  52        struct strbuf hostname;
  53        struct strbuf canon_hostname;
  54        struct strbuf ip_address;
  55        struct strbuf tcp_port;
  56        unsigned int hostname_lookup_done:1;
  57        unsigned int saw_extended_args:1;
  58};
  59
  60static void lookup_hostname(struct hostinfo *hi);
  61
  62static const char *get_canon_hostname(struct hostinfo *hi)
  63{
  64        lookup_hostname(hi);
  65        return hi->canon_hostname.buf;
  66}
  67
  68static const char *get_ip_address(struct hostinfo *hi)
  69{
  70        lookup_hostname(hi);
  71        return hi->ip_address.buf;
  72}
  73
  74static void logreport(int priority, const char *err, va_list params)
  75{
  76        if (log_syslog) {
  77                char buf[1024];
  78                vsnprintf(buf, sizeof(buf), err, params);
  79                syslog(priority, "%s", buf);
  80        } else {
  81                /*
  82                 * Since stderr is set to buffered mode, the
  83                 * logging of different processes will not overlap
  84                 * unless they overflow the (rather big) buffers.
  85                 */
  86                fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
  87                vfprintf(stderr, err, params);
  88                fputc('\n', stderr);
  89                fflush(stderr);
  90        }
  91}
  92
  93__attribute__((format (printf, 1, 2)))
  94static void logerror(const char *err, ...)
  95{
  96        va_list params;
  97        va_start(params, err);
  98        logreport(LOG_ERR, err, params);
  99        va_end(params);
 100}
 101
 102__attribute__((format (printf, 1, 2)))
 103static void loginfo(const char *err, ...)
 104{
 105        va_list params;
 106        if (!verbose)
 107                return;
 108        va_start(params, err);
 109        logreport(LOG_INFO, err, params);
 110        va_end(params);
 111}
 112
 113static void NORETURN daemon_die(const char *err, va_list params)
 114{
 115        logreport(LOG_ERR, err, params);
 116        exit(1);
 117}
 118
 119struct expand_path_context {
 120        const char *directory;
 121        struct hostinfo *hostinfo;
 122};
 123
 124static size_t expand_path(struct strbuf *sb, const char *placeholder, void *ctx)
 125{
 126        struct expand_path_context *context = ctx;
 127        struct hostinfo *hi = context->hostinfo;
 128
 129        switch (placeholder[0]) {
 130        case 'H':
 131                strbuf_addbuf(sb, &hi->hostname);
 132                return 1;
 133        case 'C':
 134                if (placeholder[1] == 'H') {
 135                        strbuf_addstr(sb, get_canon_hostname(hi));
 136                        return 2;
 137                }
 138                break;
 139        case 'I':
 140                if (placeholder[1] == 'P') {
 141                        strbuf_addstr(sb, get_ip_address(hi));
 142                        return 2;
 143                }
 144                break;
 145        case 'P':
 146                strbuf_addbuf(sb, &hi->tcp_port);
 147                return 1;
 148        case 'D':
 149                strbuf_addstr(sb, context->directory);
 150                return 1;
 151        }
 152        return 0;
 153}
 154
 155static const char *path_ok(const char *directory, struct hostinfo *hi)
 156{
 157        static char rpath[PATH_MAX];
 158        static char interp_path[PATH_MAX];
 159        size_t rlen;
 160        const char *path;
 161        const char *dir;
 162
 163        dir = directory;
 164
 165        if (daemon_avoid_alias(dir)) {
 166                logerror("'%s': aliased", dir);
 167                return NULL;
 168        }
 169
 170        if (*dir == '~') {
 171                if (!user_path) {
 172                        logerror("'%s': User-path not allowed", dir);
 173                        return NULL;
 174                }
 175                if (*user_path) {
 176                        /* Got either "~alice" or "~alice/foo";
 177                         * rewrite them to "~alice/%s" or
 178                         * "~alice/%s/foo".
 179                         */
 180                        int namlen, restlen = strlen(dir);
 181                        const char *slash = strchr(dir, '/');
 182                        if (!slash)
 183                                slash = dir + restlen;
 184                        namlen = slash - dir;
 185                        restlen -= namlen;
 186                        loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
 187                        rlen = snprintf(rpath, sizeof(rpath), "%.*s/%s%.*s",
 188                                        namlen, dir, user_path, restlen, slash);
 189                        if (rlen >= sizeof(rpath)) {
 190                                logerror("user-path too large: %s", rpath);
 191                                return NULL;
 192                        }
 193                        dir = rpath;
 194                }
 195        }
 196        else if (interpolated_path && hi->saw_extended_args) {
 197                struct strbuf expanded_path = STRBUF_INIT;
 198                struct expand_path_context context;
 199
 200                context.directory = directory;
 201                context.hostinfo = hi;
 202
 203                if (*dir != '/') {
 204                        /* Allow only absolute */
 205                        logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
 206                        return NULL;
 207                }
 208
 209                strbuf_expand(&expanded_path, interpolated_path,
 210                              expand_path, &context);
 211
 212                rlen = strlcpy(interp_path, expanded_path.buf,
 213                               sizeof(interp_path));
 214                if (rlen >= sizeof(interp_path)) {
 215                        logerror("interpolated path too large: %s",
 216                                 interp_path);
 217                        return NULL;
 218                }
 219
 220                strbuf_release(&expanded_path);
 221                loginfo("Interpolated dir '%s'", interp_path);
 222
 223                dir = interp_path;
 224        }
 225        else if (base_path) {
 226                if (*dir != '/') {
 227                        /* Allow only absolute */
 228                        logerror("'%s': Non-absolute path denied (base-path active)", dir);
 229                        return NULL;
 230                }
 231                rlen = snprintf(rpath, sizeof(rpath), "%s%s", base_path, dir);
 232                if (rlen >= sizeof(rpath)) {
 233                        logerror("base-path too large: %s", rpath);
 234                        return NULL;
 235                }
 236                dir = rpath;
 237        }
 238
 239        path = enter_repo(dir, strict_paths);
 240        if (!path && base_path && base_path_relaxed) {
 241                /*
 242                 * if we fail and base_path_relaxed is enabled, try without
 243                 * prefixing the base path
 244                 */
 245                dir = directory;
 246                path = enter_repo(dir, strict_paths);
 247        }
 248
 249        if (!path) {
 250                logerror("'%s' does not appear to be a git repository", dir);
 251                return NULL;
 252        }
 253
 254        if ( ok_paths && *ok_paths ) {
 255                const char **pp;
 256                int pathlen = strlen(path);
 257
 258                /* The validation is done on the paths after enter_repo
 259                 * appends optional {.git,.git/.git} and friends, but
 260                 * it does not use getcwd().  So if your /pub is
 261                 * a symlink to /mnt/pub, you can whitelist /pub and
 262                 * do not have to say /mnt/pub.
 263                 * Do not say /pub/.
 264                 */
 265                for ( pp = ok_paths ; *pp ; pp++ ) {
 266                        int len = strlen(*pp);
 267                        if (len <= pathlen &&
 268                            !memcmp(*pp, path, len) &&
 269                            (path[len] == '\0' ||
 270                             (!strict_paths && path[len] == '/')))
 271                                return path;
 272                }
 273        }
 274        else {
 275                /* be backwards compatible */
 276                if (!strict_paths)
 277                        return path;
 278        }
 279
 280        logerror("'%s': not in whitelist", path);
 281        return NULL;            /* Fallthrough. Deny by default */
 282}
 283
 284typedef int (*daemon_service_fn)(void);
 285struct daemon_service {
 286        const char *name;
 287        const char *config_name;
 288        daemon_service_fn fn;
 289        int enabled;
 290        int overridable;
 291};
 292
 293static int daemon_error(const char *dir, const char *msg)
 294{
 295        if (!informative_errors)
 296                msg = "access denied or repository not exported";
 297        packet_write(1, "ERR %s: %s", msg, dir);
 298        return -1;
 299}
 300
 301static const char *access_hook;
 302
 303static int run_access_hook(struct daemon_service *service, const char *dir,
 304                           const char *path, struct hostinfo *hi)
 305{
 306        struct child_process child = CHILD_PROCESS_INIT;
 307        struct strbuf buf = STRBUF_INIT;
 308        const char *argv[8];
 309        const char **arg = argv;
 310        char *eol;
 311        int seen_errors = 0;
 312
 313        *arg++ = access_hook;
 314        *arg++ = service->name;
 315        *arg++ = path;
 316        *arg++ = hi->hostname.buf;
 317        *arg++ = get_canon_hostname(hi);
 318        *arg++ = get_ip_address(hi);
 319        *arg++ = hi->tcp_port.buf;
 320        *arg = NULL;
 321
 322        child.use_shell = 1;
 323        child.argv = argv;
 324        child.no_stdin = 1;
 325        child.no_stderr = 1;
 326        child.out = -1;
 327        if (start_command(&child)) {
 328                logerror("daemon access hook '%s' failed to start",
 329                         access_hook);
 330                goto error_return;
 331        }
 332        if (strbuf_read(&buf, child.out, 0) < 0) {
 333                logerror("failed to read from pipe to daemon access hook '%s'",
 334                         access_hook);
 335                strbuf_reset(&buf);
 336                seen_errors = 1;
 337        }
 338        if (close(child.out) < 0) {
 339                logerror("failed to close pipe to daemon access hook '%s'",
 340                         access_hook);
 341                seen_errors = 1;
 342        }
 343        if (finish_command(&child))
 344                seen_errors = 1;
 345
 346        if (!seen_errors) {
 347                strbuf_release(&buf);
 348                return 0;
 349        }
 350
 351error_return:
 352        strbuf_ltrim(&buf);
 353        if (!buf.len)
 354                strbuf_addstr(&buf, "service rejected");
 355        eol = strchr(buf.buf, '\n');
 356        if (eol)
 357                *eol = '\0';
 358        errno = EACCES;
 359        daemon_error(dir, buf.buf);
 360        strbuf_release(&buf);
 361        return -1;
 362}
 363
 364static int run_service(const char *dir, struct daemon_service *service,
 365                       struct hostinfo *hi)
 366{
 367        const char *path;
 368        int enabled = service->enabled;
 369        struct strbuf var = STRBUF_INIT;
 370
 371        loginfo("Request %s for '%s'", service->name, dir);
 372
 373        if (!enabled && !service->overridable) {
 374                logerror("'%s': service not enabled.", service->name);
 375                errno = EACCES;
 376                return daemon_error(dir, "service not enabled");
 377        }
 378
 379        if (!(path = path_ok(dir, hi)))
 380                return daemon_error(dir, "no such repository");
 381
 382        /*
 383         * Security on the cheap.
 384         *
 385         * We want a readable HEAD, usable "objects" directory, and
 386         * a "git-daemon-export-ok" flag that says that the other side
 387         * is ok with us doing this.
 388         *
 389         * path_ok() uses enter_repo() and does whitelist checking.
 390         * We only need to make sure the repository is exported.
 391         */
 392
 393        if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
 394                logerror("'%s': repository not exported.", path);
 395                errno = EACCES;
 396                return daemon_error(dir, "repository not exported");
 397        }
 398
 399        if (service->overridable) {
 400                strbuf_addf(&var, "daemon.%s", service->config_name);
 401                git_config_get_bool(var.buf, &enabled);
 402                strbuf_release(&var);
 403        }
 404        if (!enabled) {
 405                logerror("'%s': service not enabled for '%s'",
 406                         service->name, path);
 407                errno = EACCES;
 408                return daemon_error(dir, "service not enabled");
 409        }
 410
 411        /*
 412         * Optionally, a hook can choose to deny access to the
 413         * repository depending on the phase of the moon.
 414         */
 415        if (access_hook && run_access_hook(service, dir, path, hi))
 416                return -1;
 417
 418        /*
 419         * We'll ignore SIGTERM from now on, we have a
 420         * good client.
 421         */
 422        signal(SIGTERM, SIG_IGN);
 423
 424        return service->fn();
 425}
 426
 427static void copy_to_log(int fd)
 428{
 429        struct strbuf line = STRBUF_INIT;
 430        FILE *fp;
 431
 432        fp = fdopen(fd, "r");
 433        if (fp == NULL) {
 434                logerror("fdopen of error channel failed");
 435                close(fd);
 436                return;
 437        }
 438
 439        while (strbuf_getline_lf(&line, fp) != EOF) {
 440                logerror("%s", line.buf);
 441                strbuf_setlen(&line, 0);
 442        }
 443
 444        strbuf_release(&line);
 445        fclose(fp);
 446}
 447
 448static int run_service_command(const char **argv)
 449{
 450        struct child_process cld = CHILD_PROCESS_INIT;
 451
 452        cld.argv = argv;
 453        cld.git_cmd = 1;
 454        cld.err = -1;
 455        if (start_command(&cld))
 456                return -1;
 457
 458        close(0);
 459        close(1);
 460
 461        copy_to_log(cld.err);
 462
 463        return finish_command(&cld);
 464}
 465
 466static int upload_pack(void)
 467{
 468        /* Timeout as string */
 469        char timeout_buf[64];
 470        const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
 471
 472        argv[2] = timeout_buf;
 473
 474        snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
 475        return run_service_command(argv);
 476}
 477
 478static int upload_archive(void)
 479{
 480        static const char *argv[] = { "upload-archive", ".", NULL };
 481        return run_service_command(argv);
 482}
 483
 484static int receive_pack(void)
 485{
 486        static const char *argv[] = { "receive-pack", ".", NULL };
 487        return run_service_command(argv);
 488}
 489
 490static struct daemon_service daemon_service[] = {
 491        { "upload-archive", "uploadarch", upload_archive, 0, 1 },
 492        { "upload-pack", "uploadpack", upload_pack, 1, 1 },
 493        { "receive-pack", "receivepack", receive_pack, 0, 1 },
 494};
 495
 496static void enable_service(const char *name, int ena)
 497{
 498        int i;
 499        for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
 500                if (!strcmp(daemon_service[i].name, name)) {
 501                        daemon_service[i].enabled = ena;
 502                        return;
 503                }
 504        }
 505        die("No such service %s", name);
 506}
 507
 508static void make_service_overridable(const char *name, int ena)
 509{
 510        int i;
 511        for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
 512                if (!strcmp(daemon_service[i].name, name)) {
 513                        daemon_service[i].overridable = ena;
 514                        return;
 515                }
 516        }
 517        die("No such service %s", name);
 518}
 519
 520static void parse_host_and_port(char *hostport, char **host,
 521        char **port)
 522{
 523        if (*hostport == '[') {
 524                char *end;
 525
 526                end = strchr(hostport, ']');
 527                if (!end)
 528                        die("Invalid request ('[' without ']')");
 529                *end = '\0';
 530                *host = hostport + 1;
 531                if (!end[1])
 532                        *port = NULL;
 533                else if (end[1] == ':')
 534                        *port = end + 2;
 535                else
 536                        die("Garbage after end of host part");
 537        } else {
 538                *host = hostport;
 539                *port = strrchr(hostport, ':');
 540                if (*port) {
 541                        **port = '\0';
 542                        ++*port;
 543                }
 544        }
 545}
 546
 547/*
 548 * Sanitize a string from the client so that it's OK to be inserted into a
 549 * filesystem path. Specifically, we disallow slashes, runs of "..", and
 550 * trailing and leading dots, which means that the client cannot escape
 551 * our base path via ".." traversal.
 552 */
 553static void sanitize_client(struct strbuf *out, const char *in)
 554{
 555        for (; *in; in++) {
 556                if (*in == '/')
 557                        continue;
 558                if (*in == '.' && (!out->len || out->buf[out->len - 1] == '.'))
 559                        continue;
 560                strbuf_addch(out, *in);
 561        }
 562
 563        while (out->len && out->buf[out->len - 1] == '.')
 564                strbuf_setlen(out, out->len - 1);
 565}
 566
 567/*
 568 * Like sanitize_client, but we also perform any canonicalization
 569 * to make life easier on the admin.
 570 */
 571static void canonicalize_client(struct strbuf *out, const char *in)
 572{
 573        sanitize_client(out, in);
 574        strbuf_tolower(out);
 575}
 576
 577/*
 578 * Read the host as supplied by the client connection.
 579 */
 580static void parse_host_arg(struct hostinfo *hi, char *extra_args, int buflen)
 581{
 582        char *val;
 583        int vallen;
 584        char *end = extra_args + buflen;
 585
 586        if (extra_args < end && *extra_args) {
 587                hi->saw_extended_args = 1;
 588                if (strncasecmp("host=", extra_args, 5) == 0) {
 589                        val = extra_args + 5;
 590                        vallen = strlen(val) + 1;
 591                        if (*val) {
 592                                /* Split <host>:<port> at colon. */
 593                                char *host;
 594                                char *port;
 595                                parse_host_and_port(val, &host, &port);
 596                                if (port)
 597                                        sanitize_client(&hi->tcp_port, port);
 598                                canonicalize_client(&hi->hostname, host);
 599                                hi->hostname_lookup_done = 0;
 600                        }
 601
 602                        /* On to the next one */
 603                        extra_args = val + vallen;
 604                }
 605                if (extra_args < end && *extra_args)
 606                        die("Invalid request");
 607        }
 608}
 609
 610/*
 611 * Locate canonical hostname and its IP address.
 612 */
 613static void lookup_hostname(struct hostinfo *hi)
 614{
 615        if (!hi->hostname_lookup_done && hi->hostname.len) {
 616#ifndef NO_IPV6
 617                struct addrinfo hints;
 618                struct addrinfo *ai;
 619                int gai;
 620                static char addrbuf[HOST_NAME_MAX + 1];
 621
 622                memset(&hints, 0, sizeof(hints));
 623                hints.ai_flags = AI_CANONNAME;
 624
 625                gai = getaddrinfo(hi->hostname.buf, NULL, &hints, &ai);
 626                if (!gai) {
 627                        struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
 628
 629                        inet_ntop(AF_INET, &sin_addr->sin_addr,
 630                                  addrbuf, sizeof(addrbuf));
 631                        strbuf_addstr(&hi->ip_address, addrbuf);
 632
 633                        if (ai->ai_canonname)
 634                                sanitize_client(&hi->canon_hostname,
 635                                                ai->ai_canonname);
 636                        else
 637                                strbuf_addbuf(&hi->canon_hostname,
 638                                              &hi->ip_address);
 639
 640                        freeaddrinfo(ai);
 641                }
 642#else
 643                struct hostent *hent;
 644                struct sockaddr_in sa;
 645                char **ap;
 646                static char addrbuf[HOST_NAME_MAX + 1];
 647
 648                hent = gethostbyname(hi->hostname.buf);
 649                if (hent) {
 650                        ap = hent->h_addr_list;
 651                        memset(&sa, 0, sizeof sa);
 652                        sa.sin_family = hent->h_addrtype;
 653                        sa.sin_port = htons(0);
 654                        memcpy(&sa.sin_addr, *ap, hent->h_length);
 655
 656                        inet_ntop(hent->h_addrtype, &sa.sin_addr,
 657                                  addrbuf, sizeof(addrbuf));
 658
 659                        sanitize_client(&hi->canon_hostname, hent->h_name);
 660                        strbuf_addstr(&hi->ip_address, addrbuf);
 661                }
 662#endif
 663                hi->hostname_lookup_done = 1;
 664        }
 665}
 666
 667static void hostinfo_init(struct hostinfo *hi)
 668{
 669        memset(hi, 0, sizeof(*hi));
 670        strbuf_init(&hi->hostname, 0);
 671        strbuf_init(&hi->canon_hostname, 0);
 672        strbuf_init(&hi->ip_address, 0);
 673        strbuf_init(&hi->tcp_port, 0);
 674}
 675
 676static void hostinfo_clear(struct hostinfo *hi)
 677{
 678        strbuf_release(&hi->hostname);
 679        strbuf_release(&hi->canon_hostname);
 680        strbuf_release(&hi->ip_address);
 681        strbuf_release(&hi->tcp_port);
 682}
 683
 684static void set_keep_alive(int sockfd)
 685{
 686        int ka = 1;
 687
 688        if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0) {
 689                if (errno != ENOTSOCK)
 690                        logerror("unable to set SO_KEEPALIVE on socket: %s",
 691                                strerror(errno));
 692        }
 693}
 694
 695static int execute(void)
 696{
 697        char *line = packet_buffer;
 698        int pktlen, len, i;
 699        char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
 700        struct hostinfo hi;
 701
 702        hostinfo_init(&hi);
 703
 704        if (addr)
 705                loginfo("Connection from %s:%s", addr, port);
 706
 707        set_keep_alive(0);
 708        alarm(init_timeout ? init_timeout : timeout);
 709        pktlen = packet_read(0, NULL, NULL, packet_buffer, sizeof(packet_buffer), 0);
 710        alarm(0);
 711
 712        len = strlen(line);
 713        if (pktlen != len)
 714                loginfo("Extended attributes (%d bytes) exist <%.*s>",
 715                        (int) pktlen - len,
 716                        (int) pktlen - len, line + len + 1);
 717        if (len && line[len-1] == '\n') {
 718                line[--len] = 0;
 719                pktlen--;
 720        }
 721
 722        if (len != pktlen)
 723                parse_host_arg(&hi, line + len + 1, pktlen - len - 1);
 724
 725        for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
 726                struct daemon_service *s = &(daemon_service[i]);
 727                const char *arg;
 728
 729                if (skip_prefix(line, "git-", &arg) &&
 730                    skip_prefix(arg, s->name, &arg) &&
 731                    *arg++ == ' ') {
 732                        /*
 733                         * Note: The directory here is probably context sensitive,
 734                         * and might depend on the actual service being performed.
 735                         */
 736                        int rc = run_service(arg, s, &hi);
 737                        hostinfo_clear(&hi);
 738                        return rc;
 739                }
 740        }
 741
 742        hostinfo_clear(&hi);
 743        logerror("Protocol error: '%s'", line);
 744        return -1;
 745}
 746
 747static int addrcmp(const struct sockaddr_storage *s1,
 748    const struct sockaddr_storage *s2)
 749{
 750        const struct sockaddr *sa1 = (const struct sockaddr*) s1;
 751        const struct sockaddr *sa2 = (const struct sockaddr*) s2;
 752
 753        if (sa1->sa_family != sa2->sa_family)
 754                return sa1->sa_family - sa2->sa_family;
 755        if (sa1->sa_family == AF_INET)
 756                return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
 757                    &((struct sockaddr_in *)s2)->sin_addr,
 758                    sizeof(struct in_addr));
 759#ifndef NO_IPV6
 760        if (sa1->sa_family == AF_INET6)
 761                return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
 762                    &((struct sockaddr_in6 *)s2)->sin6_addr,
 763                    sizeof(struct in6_addr));
 764#endif
 765        return 0;
 766}
 767
 768static int max_connections = 32;
 769
 770static unsigned int live_children;
 771
 772static struct child {
 773        struct child *next;
 774        struct child_process cld;
 775        struct sockaddr_storage address;
 776} *firstborn;
 777
 778static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
 779{
 780        struct child *newborn, **cradle;
 781
 782        newborn = xcalloc(1, sizeof(*newborn));
 783        live_children++;
 784        memcpy(&newborn->cld, cld, sizeof(*cld));
 785        memcpy(&newborn->address, addr, addrlen);
 786        for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
 787                if (!addrcmp(&(*cradle)->address, &newborn->address))
 788                        break;
 789        newborn->next = *cradle;
 790        *cradle = newborn;
 791}
 792
 793/*
 794 * This gets called if the number of connections grows
 795 * past "max_connections".
 796 *
 797 * We kill the newest connection from a duplicate IP.
 798 */
 799static void kill_some_child(void)
 800{
 801        const struct child *blanket, *next;
 802
 803        if (!(blanket = firstborn))
 804                return;
 805
 806        for (; (next = blanket->next); blanket = next)
 807                if (!addrcmp(&blanket->address, &next->address)) {
 808                        kill(blanket->cld.pid, SIGTERM);
 809                        break;
 810                }
 811}
 812
 813static void check_dead_children(void)
 814{
 815        int status;
 816        pid_t pid;
 817
 818        struct child **cradle, *blanket;
 819        for (cradle = &firstborn; (blanket = *cradle);)
 820                if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
 821                        const char *dead = "";
 822                        if (status)
 823                                dead = " (with error)";
 824                        loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
 825
 826                        /* remove the child */
 827                        *cradle = blanket->next;
 828                        live_children--;
 829                        child_process_clear(&blanket->cld);
 830                        free(blanket);
 831                } else
 832                        cradle = &blanket->next;
 833}
 834
 835static struct argv_array cld_argv = ARGV_ARRAY_INIT;
 836static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
 837{
 838        struct child_process cld = CHILD_PROCESS_INIT;
 839
 840        if (max_connections && live_children >= max_connections) {
 841                kill_some_child();
 842                sleep(1);  /* give it some time to die */
 843                check_dead_children();
 844                if (live_children >= max_connections) {
 845                        close(incoming);
 846                        logerror("Too many children, dropping connection");
 847                        return;
 848                }
 849        }
 850
 851        if (addr->sa_family == AF_INET) {
 852                char buf[128] = "";
 853                struct sockaddr_in *sin_addr = (void *) addr;
 854                inet_ntop(addr->sa_family, &sin_addr->sin_addr, buf, sizeof(buf));
 855                argv_array_pushf(&cld.env_array, "REMOTE_ADDR=%s", buf);
 856                argv_array_pushf(&cld.env_array, "REMOTE_PORT=%d",
 857                                 ntohs(sin_addr->sin_port));
 858#ifndef NO_IPV6
 859        } else if (addr->sa_family == AF_INET6) {
 860                char buf[128] = "";
 861                struct sockaddr_in6 *sin6_addr = (void *) addr;
 862                inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(buf));
 863                argv_array_pushf(&cld.env_array, "REMOTE_ADDR=[%s]", buf);
 864                argv_array_pushf(&cld.env_array, "REMOTE_PORT=%d",
 865                                 ntohs(sin6_addr->sin6_port));
 866#endif
 867        }
 868
 869        cld.argv = cld_argv.argv;
 870        cld.in = incoming;
 871        cld.out = dup(incoming);
 872
 873        if (start_command(&cld))
 874                logerror("unable to fork");
 875        else
 876                add_child(&cld, addr, addrlen);
 877}
 878
 879static void child_handler(int signo)
 880{
 881        /*
 882         * Otherwise empty handler because systemcalls will get interrupted
 883         * upon signal receipt
 884         * SysV needs the handler to be rearmed
 885         */
 886        signal(SIGCHLD, child_handler);
 887}
 888
 889static int set_reuse_addr(int sockfd)
 890{
 891        int on = 1;
 892
 893        if (!reuseaddr)
 894                return 0;
 895        return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
 896                          &on, sizeof(on));
 897}
 898
 899struct socketlist {
 900        int *list;
 901        size_t nr;
 902        size_t alloc;
 903};
 904
 905static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
 906{
 907#ifdef NO_IPV6
 908        static char ip[INET_ADDRSTRLEN];
 909#else
 910        static char ip[INET6_ADDRSTRLEN];
 911#endif
 912
 913        switch (family) {
 914#ifndef NO_IPV6
 915        case AF_INET6:
 916                inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
 917                break;
 918#endif
 919        case AF_INET:
 920                inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
 921                break;
 922        default:
 923                xsnprintf(ip, sizeof(ip), "<unknown>");
 924        }
 925        return ip;
 926}
 927
 928#ifndef NO_IPV6
 929
 930static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
 931{
 932        int socknum = 0;
 933        char pbuf[NI_MAXSERV];
 934        struct addrinfo hints, *ai0, *ai;
 935        int gai;
 936        long flags;
 937
 938        xsnprintf(pbuf, sizeof(pbuf), "%d", listen_port);
 939        memset(&hints, 0, sizeof(hints));
 940        hints.ai_family = AF_UNSPEC;
 941        hints.ai_socktype = SOCK_STREAM;
 942        hints.ai_protocol = IPPROTO_TCP;
 943        hints.ai_flags = AI_PASSIVE;
 944
 945        gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
 946        if (gai) {
 947                logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
 948                return 0;
 949        }
 950
 951        for (ai = ai0; ai; ai = ai->ai_next) {
 952                int sockfd;
 953
 954                sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
 955                if (sockfd < 0)
 956                        continue;
 957                if (sockfd >= FD_SETSIZE) {
 958                        logerror("Socket descriptor too large");
 959                        close(sockfd);
 960                        continue;
 961                }
 962
 963#ifdef IPV6_V6ONLY
 964                if (ai->ai_family == AF_INET6) {
 965                        int on = 1;
 966                        setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
 967                                   &on, sizeof(on));
 968                        /* Note: error is not fatal */
 969                }
 970#endif
 971
 972                if (set_reuse_addr(sockfd)) {
 973                        logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
 974                        close(sockfd);
 975                        continue;
 976                }
 977
 978                set_keep_alive(sockfd);
 979
 980                if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
 981                        logerror("Could not bind to %s: %s",
 982                                 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
 983                                 strerror(errno));
 984                        close(sockfd);
 985                        continue;       /* not fatal */
 986                }
 987                if (listen(sockfd, 5) < 0) {
 988                        logerror("Could not listen to %s: %s",
 989                                 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
 990                                 strerror(errno));
 991                        close(sockfd);
 992                        continue;       /* not fatal */
 993                }
 994
 995                flags = fcntl(sockfd, F_GETFD, 0);
 996                if (flags >= 0)
 997                        fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
 998
 999                ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1000                socklist->list[socklist->nr++] = sockfd;
1001                socknum++;
1002        }
1003
1004        freeaddrinfo(ai0);
1005
1006        return socknum;
1007}
1008
1009#else /* NO_IPV6 */
1010
1011static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
1012{
1013        struct sockaddr_in sin;
1014        int sockfd;
1015        long flags;
1016
1017        memset(&sin, 0, sizeof sin);
1018        sin.sin_family = AF_INET;
1019        sin.sin_port = htons(listen_port);
1020
1021        if (listen_addr) {
1022                /* Well, host better be an IP address here. */
1023                if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
1024                        return 0;
1025        } else {
1026                sin.sin_addr.s_addr = htonl(INADDR_ANY);
1027        }
1028
1029        sockfd = socket(AF_INET, SOCK_STREAM, 0);
1030        if (sockfd < 0)
1031                return 0;
1032
1033        if (set_reuse_addr(sockfd)) {
1034                logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
1035                close(sockfd);
1036                return 0;
1037        }
1038
1039        set_keep_alive(sockfd);
1040
1041        if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
1042                logerror("Could not bind to %s: %s",
1043                         ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1044                         strerror(errno));
1045                close(sockfd);
1046                return 0;
1047        }
1048
1049        if (listen(sockfd, 5) < 0) {
1050                logerror("Could not listen to %s: %s",
1051                         ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1052                         strerror(errno));
1053                close(sockfd);
1054                return 0;
1055        }
1056
1057        flags = fcntl(sockfd, F_GETFD, 0);
1058        if (flags >= 0)
1059                fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1060
1061        ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1062        socklist->list[socklist->nr++] = sockfd;
1063        return 1;
1064}
1065
1066#endif
1067
1068static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
1069{
1070        if (!listen_addr->nr)
1071                setup_named_sock(NULL, listen_port, socklist);
1072        else {
1073                int i, socknum;
1074                for (i = 0; i < listen_addr->nr; i++) {
1075                        socknum = setup_named_sock(listen_addr->items[i].string,
1076                                                   listen_port, socklist);
1077
1078                        if (socknum == 0)
1079                                logerror("unable to allocate any listen sockets for host %s on port %u",
1080                                         listen_addr->items[i].string, listen_port);
1081                }
1082        }
1083}
1084
1085static int service_loop(struct socketlist *socklist)
1086{
1087        struct pollfd *pfd;
1088        int i;
1089
1090        pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
1091
1092        for (i = 0; i < socklist->nr; i++) {
1093                pfd[i].fd = socklist->list[i];
1094                pfd[i].events = POLLIN;
1095        }
1096
1097        signal(SIGCHLD, child_handler);
1098
1099        for (;;) {
1100                int i;
1101
1102                check_dead_children();
1103
1104                if (poll(pfd, socklist->nr, -1) < 0) {
1105                        if (errno != EINTR) {
1106                                logerror("Poll failed, resuming: %s",
1107                                      strerror(errno));
1108                                sleep(1);
1109                        }
1110                        continue;
1111                }
1112
1113                for (i = 0; i < socklist->nr; i++) {
1114                        if (pfd[i].revents & POLLIN) {
1115                                union {
1116                                        struct sockaddr sa;
1117                                        struct sockaddr_in sai;
1118#ifndef NO_IPV6
1119                                        struct sockaddr_in6 sai6;
1120#endif
1121                                } ss;
1122                                socklen_t sslen = sizeof(ss);
1123                                int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1124                                if (incoming < 0) {
1125                                        switch (errno) {
1126                                        case EAGAIN:
1127                                        case EINTR:
1128                                        case ECONNABORTED:
1129                                                continue;
1130                                        default:
1131                                                die_errno("accept returned");
1132                                        }
1133                                }
1134                                handle(incoming, &ss.sa, sslen);
1135                        }
1136                }
1137        }
1138}
1139
1140#ifdef NO_POSIX_GOODIES
1141
1142struct credentials;
1143
1144static void drop_privileges(struct credentials *cred)
1145{
1146        /* nothing */
1147}
1148
1149static struct credentials *prepare_credentials(const char *user_name,
1150    const char *group_name)
1151{
1152        die("--user not supported on this platform");
1153}
1154
1155#else
1156
1157struct credentials {
1158        struct passwd *pass;
1159        gid_t gid;
1160};
1161
1162static void drop_privileges(struct credentials *cred)
1163{
1164        if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1165            setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1166                die("cannot drop privileges");
1167}
1168
1169static struct credentials *prepare_credentials(const char *user_name,
1170    const char *group_name)
1171{
1172        static struct credentials c;
1173
1174        c.pass = getpwnam(user_name);
1175        if (!c.pass)
1176                die("user not found - %s", user_name);
1177
1178        if (!group_name)
1179                c.gid = c.pass->pw_gid;
1180        else {
1181                struct group *group = getgrnam(group_name);
1182                if (!group)
1183                        die("group not found - %s", group_name);
1184
1185                c.gid = group->gr_gid;
1186        }
1187
1188        return &c;
1189}
1190#endif
1191
1192static int serve(struct string_list *listen_addr, int listen_port,
1193    struct credentials *cred)
1194{
1195        struct socketlist socklist = { NULL, 0, 0 };
1196
1197        socksetup(listen_addr, listen_port, &socklist);
1198        if (socklist.nr == 0)
1199                die("unable to allocate any listen sockets on port %u",
1200                    listen_port);
1201
1202        drop_privileges(cred);
1203
1204        loginfo("Ready to rumble");
1205
1206        return service_loop(&socklist);
1207}
1208
1209int cmd_main(int argc, const char **argv)
1210{
1211        int listen_port = 0;
1212        struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1213        int serve_mode = 0, inetd_mode = 0;
1214        const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1215        int detach = 0;
1216        struct credentials *cred = NULL;
1217        int i;
1218
1219        for (i = 1; i < argc; i++) {
1220                const char *arg = argv[i];
1221                const char *v;
1222
1223                if (skip_prefix(arg, "--listen=", &v)) {
1224                        string_list_append(&listen_addr, xstrdup_tolower(v));
1225                        continue;
1226                }
1227                if (skip_prefix(arg, "--port=", &v)) {
1228                        char *end;
1229                        unsigned long n;
1230                        n = strtoul(v, &end, 0);
1231                        if (*v && !*end) {
1232                                listen_port = n;
1233                                continue;
1234                        }
1235                }
1236                if (!strcmp(arg, "--serve")) {
1237                        serve_mode = 1;
1238                        continue;
1239                }
1240                if (!strcmp(arg, "--inetd")) {
1241                        inetd_mode = 1;
1242                        log_syslog = 1;
1243                        continue;
1244                }
1245                if (!strcmp(arg, "--verbose")) {
1246                        verbose = 1;
1247                        continue;
1248                }
1249                if (!strcmp(arg, "--syslog")) {
1250                        log_syslog = 1;
1251                        continue;
1252                }
1253                if (!strcmp(arg, "--export-all")) {
1254                        export_all_trees = 1;
1255                        continue;
1256                }
1257                if (skip_prefix(arg, "--access-hook=", &v)) {
1258                        access_hook = v;
1259                        continue;
1260                }
1261                if (skip_prefix(arg, "--timeout=", &v)) {
1262                        timeout = atoi(v);
1263                        continue;
1264                }
1265                if (skip_prefix(arg, "--init-timeout=", &v)) {
1266                        init_timeout = atoi(v);
1267                        continue;
1268                }
1269                if (skip_prefix(arg, "--max-connections=", &v)) {
1270                        max_connections = atoi(v);
1271                        if (max_connections < 0)
1272                                max_connections = 0;            /* unlimited */
1273                        continue;
1274                }
1275                if (!strcmp(arg, "--strict-paths")) {
1276                        strict_paths = 1;
1277                        continue;
1278                }
1279                if (skip_prefix(arg, "--base-path=", &v)) {
1280                        base_path = v;
1281                        continue;
1282                }
1283                if (!strcmp(arg, "--base-path-relaxed")) {
1284                        base_path_relaxed = 1;
1285                        continue;
1286                }
1287                if (skip_prefix(arg, "--interpolated-path=", &v)) {
1288                        interpolated_path = v;
1289                        continue;
1290                }
1291                if (!strcmp(arg, "--reuseaddr")) {
1292                        reuseaddr = 1;
1293                        continue;
1294                }
1295                if (!strcmp(arg, "--user-path")) {
1296                        user_path = "";
1297                        continue;
1298                }
1299                if (skip_prefix(arg, "--user-path=", &v)) {
1300                        user_path = v;
1301                        continue;
1302                }
1303                if (skip_prefix(arg, "--pid-file=", &v)) {
1304                        pid_file = v;
1305                        continue;
1306                }
1307                if (!strcmp(arg, "--detach")) {
1308                        detach = 1;
1309                        log_syslog = 1;
1310                        continue;
1311                }
1312                if (skip_prefix(arg, "--user=", &v)) {
1313                        user_name = v;
1314                        continue;
1315                }
1316                if (skip_prefix(arg, "--group=", &v)) {
1317                        group_name = v;
1318                        continue;
1319                }
1320                if (skip_prefix(arg, "--enable=", &v)) {
1321                        enable_service(v, 1);
1322                        continue;
1323                }
1324                if (skip_prefix(arg, "--disable=", &v)) {
1325                        enable_service(v, 0);
1326                        continue;
1327                }
1328                if (skip_prefix(arg, "--allow-override=", &v)) {
1329                        make_service_overridable(v, 1);
1330                        continue;
1331                }
1332                if (skip_prefix(arg, "--forbid-override=", &v)) {
1333                        make_service_overridable(v, 0);
1334                        continue;
1335                }
1336                if (!strcmp(arg, "--informative-errors")) {
1337                        informative_errors = 1;
1338                        continue;
1339                }
1340                if (!strcmp(arg, "--no-informative-errors")) {
1341                        informative_errors = 0;
1342                        continue;
1343                }
1344                if (!strcmp(arg, "--")) {
1345                        ok_paths = &argv[i+1];
1346                        break;
1347                } else if (arg[0] != '-') {
1348                        ok_paths = &argv[i];
1349                        break;
1350                }
1351
1352                usage(daemon_usage);
1353        }
1354
1355        if (log_syslog) {
1356                openlog("git-daemon", LOG_PID, LOG_DAEMON);
1357                set_die_routine(daemon_die);
1358        } else
1359                /* avoid splitting a message in the middle */
1360                setvbuf(stderr, NULL, _IOFBF, 4096);
1361
1362        if (inetd_mode && (detach || group_name || user_name))
1363                die("--detach, --user and --group are incompatible with --inetd");
1364
1365        if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1366                die("--listen= and --port= are incompatible with --inetd");
1367        else if (listen_port == 0)
1368                listen_port = DEFAULT_GIT_PORT;
1369
1370        if (group_name && !user_name)
1371                die("--group supplied without --user");
1372
1373        if (user_name)
1374                cred = prepare_credentials(user_name, group_name);
1375
1376        if (strict_paths && (!ok_paths || !*ok_paths))
1377                die("option --strict-paths requires a whitelist");
1378
1379        if (base_path && !is_directory(base_path))
1380                die("base-path '%s' does not exist or is not a directory",
1381                    base_path);
1382
1383        if (inetd_mode) {
1384                if (!freopen("/dev/null", "w", stderr))
1385                        die_errno("failed to redirect stderr to /dev/null");
1386        }
1387
1388        if (inetd_mode || serve_mode)
1389                return execute();
1390
1391        if (detach) {
1392                if (daemonize())
1393                        die("--detach not supported on this platform");
1394        }
1395
1396        if (pid_file)
1397                write_file(pid_file, "%"PRIuMAX, (uintmax_t) getpid());
1398
1399        /* prepare argv for serving-processes */
1400        argv_array_push(&cld_argv, argv[0]); /* git-daemon */
1401        argv_array_push(&cld_argv, "--serve");
1402        for (i = 1; i < argc; ++i)
1403                argv_array_push(&cld_argv, argv[i]);
1404
1405        return serve(&listen_addr, listen_port, cred);
1406}