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