daemon.con commit Bisect: refactor "bisect_{bad,good,skip}" into "bisect_state". (155fc79)
   1#include "cache.h"
   2#include "pkt-line.h"
   3#include "exec_cmd.h"
   4#include "interpolate.h"
   5
   6#include <syslog.h>
   7
   8#ifndef HOST_NAME_MAX
   9#define HOST_NAME_MAX 256
  10#endif
  11
  12#ifndef NI_MAXSERV
  13#define NI_MAXSERV 32
  14#endif
  15
  16static int log_syslog;
  17static int verbose;
  18static int reuseaddr;
  19
  20static const char daemon_usage[] =
  21"git-daemon [--verbose] [--syslog] [--export-all]\n"
  22"           [--timeout=n] [--init-timeout=n] [--strict-paths]\n"
  23"           [--base-path=path] [--base-path-relaxed]\n"
  24"           [--user-path | --user-path=path]\n"
  25"           [--interpolated-path=path]\n"
  26"           [--reuseaddr] [--detach] [--pid-file=file]\n"
  27"           [--[enable|disable|allow-override|forbid-override]=service]\n"
  28"           [--inetd | [--listen=host_or_ipaddr] [--port=n]\n"
  29"                      [--user=user [--group=group]]\n"
  30"           [directory...]";
  31
  32/* List of acceptable pathname prefixes */
  33static char **ok_paths;
  34static int strict_paths;
  35
  36/* If this is set, git-daemon-export-ok is not required */
  37static int export_all_trees;
  38
  39/* Take all paths relative to this one if non-NULL */
  40static char *base_path;
  41static char *interpolated_path;
  42static int base_path_relaxed;
  43
  44/* Flag indicating client sent extra args. */
  45static int saw_extended_args;
  46
  47/* If defined, ~user notation is allowed and the string is inserted
  48 * after ~user/.  E.g. a request to git://host/~alice/frotz would
  49 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
  50 */
  51static const char *user_path;
  52
  53/* Timeout, and initial timeout */
  54static unsigned int timeout;
  55static unsigned int init_timeout;
  56
  57/*
  58 * Static table for now.  Ugh.
  59 * Feel free to make dynamic as needed.
  60 */
  61#define INTERP_SLOT_HOST        (0)
  62#define INTERP_SLOT_CANON_HOST  (1)
  63#define INTERP_SLOT_IP          (2)
  64#define INTERP_SLOT_PORT        (3)
  65#define INTERP_SLOT_DIR         (4)
  66#define INTERP_SLOT_PERCENT     (5)
  67
  68static struct interp interp_table[] = {
  69        { "%H", 0},
  70        { "%CH", 0},
  71        { "%IP", 0},
  72        { "%P", 0},
  73        { "%D", 0},
  74        { "%%", 0},
  75};
  76
  77
  78static void logreport(int priority, const char *err, va_list params)
  79{
  80        /* We should do a single write so that it is atomic and output
  81         * of several processes do not get intermingled. */
  82        char buf[1024];
  83        int buflen;
  84        int maxlen, msglen;
  85
  86        /* sizeof(buf) should be big enough for "[pid] \n" */
  87        buflen = snprintf(buf, sizeof(buf), "[%ld] ", (long) getpid());
  88
  89        maxlen = sizeof(buf) - buflen - 1; /* -1 for our own LF */
  90        msglen = vsnprintf(buf + buflen, maxlen, err, params);
  91
  92        if (log_syslog) {
  93                syslog(priority, "%s", buf);
  94                return;
  95        }
  96
  97        /* maxlen counted our own LF but also counts space given to
  98         * vsnprintf for the terminating NUL.  We want to make sure that
  99         * we have space for our own LF and NUL after the "meat" of the
 100         * message, so truncate it at maxlen - 1.
 101         */
 102        if (msglen > maxlen - 1)
 103                msglen = maxlen - 1;
 104        else if (msglen < 0)
 105                msglen = 0; /* Protect against weird return values. */
 106        buflen += msglen;
 107
 108        buf[buflen++] = '\n';
 109        buf[buflen] = '\0';
 110
 111        write_in_full(2, buf, buflen);
 112}
 113
 114static void logerror(const char *err, ...)
 115{
 116        va_list params;
 117        va_start(params, err);
 118        logreport(LOG_ERR, err, params);
 119        va_end(params);
 120}
 121
 122static void loginfo(const char *err, ...)
 123{
 124        va_list params;
 125        if (!verbose)
 126                return;
 127        va_start(params, err);
 128        logreport(LOG_INFO, err, params);
 129        va_end(params);
 130}
 131
 132static void NORETURN daemon_die(const char *err, va_list params)
 133{
 134        logreport(LOG_ERR, err, params);
 135        exit(1);
 136}
 137
 138static int avoid_alias(char *p)
 139{
 140        int sl, ndot;
 141
 142        /*
 143         * This resurrects the belts and suspenders paranoia check by HPA
 144         * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
 145         * does not do getcwd() based path canonicalizations.
 146         *
 147         * sl becomes true immediately after seeing '/' and continues to
 148         * be true as long as dots continue after that without intervening
 149         * non-dot character.
 150         */
 151        if (!p || (*p != '/' && *p != '~'))
 152                return -1;
 153        sl = 1; ndot = 0;
 154        p++;
 155
 156        while (1) {
 157                char ch = *p++;
 158                if (sl) {
 159                        if (ch == '.')
 160                                ndot++;
 161                        else if (ch == '/') {
 162                                if (ndot < 3)
 163                                        /* reject //, /./ and /../ */
 164                                        return -1;
 165                                ndot = 0;
 166                        }
 167                        else if (ch == 0) {
 168                                if (0 < ndot && ndot < 3)
 169                                        /* reject /.$ and /..$ */
 170                                        return -1;
 171                                return 0;
 172                        }
 173                        else
 174                                sl = ndot = 0;
 175                }
 176                else if (ch == 0)
 177                        return 0;
 178                else if (ch == '/') {
 179                        sl = 1;
 180                        ndot = 0;
 181                }
 182        }
 183}
 184
 185static char *path_ok(struct interp *itable)
 186{
 187        static char rpath[PATH_MAX];
 188        static char interp_path[PATH_MAX];
 189        int retried_path = 0;
 190        char *path;
 191        char *dir;
 192
 193        dir = itable[INTERP_SLOT_DIR].value;
 194
 195        if (avoid_alias(dir)) {
 196                logerror("'%s': aliased", dir);
 197                return NULL;
 198        }
 199
 200        if (*dir == '~') {
 201                if (!user_path) {
 202                        logerror("'%s': User-path not allowed", dir);
 203                        return NULL;
 204                }
 205                if (*user_path) {
 206                        /* Got either "~alice" or "~alice/foo";
 207                         * rewrite them to "~alice/%s" or
 208                         * "~alice/%s/foo".
 209                         */
 210                        int namlen, restlen = strlen(dir);
 211                        char *slash = strchr(dir, '/');
 212                        if (!slash)
 213                                slash = dir + restlen;
 214                        namlen = slash - dir;
 215                        restlen -= namlen;
 216                        loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
 217                        snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
 218                                 namlen, dir, user_path, restlen, slash);
 219                        dir = rpath;
 220                }
 221        }
 222        else if (interpolated_path && saw_extended_args) {
 223                if (*dir != '/') {
 224                        /* Allow only absolute */
 225                        logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
 226                        return NULL;
 227                }
 228
 229                interpolate(interp_path, PATH_MAX, interpolated_path,
 230                            interp_table, ARRAY_SIZE(interp_table));
 231                loginfo("Interpolated dir '%s'", interp_path);
 232
 233                dir = interp_path;
 234        }
 235        else if (base_path) {
 236                if (*dir != '/') {
 237                        /* Allow only absolute */
 238                        logerror("'%s': Non-absolute path denied (base-path active)", dir);
 239                        return NULL;
 240                }
 241                snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
 242                dir = rpath;
 243        }
 244
 245        do {
 246                path = enter_repo(dir, strict_paths);
 247                if (path)
 248                        break;
 249
 250                /*
 251                 * if we fail and base_path_relaxed is enabled, try without
 252                 * prefixing the base path
 253                 */
 254                if (base_path && base_path_relaxed && !retried_path) {
 255                        dir = itable[INTERP_SLOT_DIR].value;
 256                        retried_path = 1;
 257                        continue;
 258                }
 259                break;
 260        } while (1);
 261
 262        if (!path) {
 263                logerror("'%s': unable to chdir or not a git archive", dir);
 264                return NULL;
 265        }
 266
 267        if ( ok_paths && *ok_paths ) {
 268                char **pp;
 269                int pathlen = strlen(path);
 270
 271                /* The validation is done on the paths after enter_repo
 272                 * appends optional {.git,.git/.git} and friends, but
 273                 * it does not use getcwd().  So if your /pub is
 274                 * a symlink to /mnt/pub, you can whitelist /pub and
 275                 * do not have to say /mnt/pub.
 276                 * Do not say /pub/.
 277                 */
 278                for ( pp = ok_paths ; *pp ; pp++ ) {
 279                        int len = strlen(*pp);
 280                        if (len <= pathlen &&
 281                            !memcmp(*pp, path, len) &&
 282                            (path[len] == '\0' ||
 283                             (!strict_paths && path[len] == '/')))
 284                                return path;
 285                }
 286        }
 287        else {
 288                /* be backwards compatible */
 289                if (!strict_paths)
 290                        return path;
 291        }
 292
 293        logerror("'%s': not in whitelist", path);
 294        return NULL;            /* Fallthrough. Deny by default */
 295}
 296
 297typedef int (*daemon_service_fn)(void);
 298struct daemon_service {
 299        const char *name;
 300        const char *config_name;
 301        daemon_service_fn fn;
 302        int enabled;
 303        int overridable;
 304};
 305
 306static struct daemon_service *service_looking_at;
 307static int service_enabled;
 308
 309static int git_daemon_config(const char *var, const char *value)
 310{
 311        if (!prefixcmp(var, "daemon.") &&
 312            !strcmp(var + 7, service_looking_at->config_name)) {
 313                service_enabled = git_config_bool(var, value);
 314                return 0;
 315        }
 316
 317        /* we are not interested in parsing any other configuration here */
 318        return 0;
 319}
 320
 321static int run_service(struct interp *itable, struct daemon_service *service)
 322{
 323        const char *path;
 324        int enabled = service->enabled;
 325
 326        loginfo("Request %s for '%s'",
 327                service->name,
 328                itable[INTERP_SLOT_DIR].value);
 329
 330        if (!enabled && !service->overridable) {
 331                logerror("'%s': service not enabled.", service->name);
 332                errno = EACCES;
 333                return -1;
 334        }
 335
 336        if (!(path = path_ok(itable)))
 337                return -1;
 338
 339        /*
 340         * Security on the cheap.
 341         *
 342         * We want a readable HEAD, usable "objects" directory, and
 343         * a "git-daemon-export-ok" flag that says that the other side
 344         * is ok with us doing this.
 345         *
 346         * path_ok() uses enter_repo() and does whitelist checking.
 347         * We only need to make sure the repository is exported.
 348         */
 349
 350        if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
 351                logerror("'%s': repository not exported.", path);
 352                errno = EACCES;
 353                return -1;
 354        }
 355
 356        if (service->overridable) {
 357                service_looking_at = service;
 358                service_enabled = -1;
 359                git_config(git_daemon_config);
 360                if (0 <= service_enabled)
 361                        enabled = service_enabled;
 362        }
 363        if (!enabled) {
 364                logerror("'%s': service not enabled for '%s'",
 365                         service->name, path);
 366                errno = EACCES;
 367                return -1;
 368        }
 369
 370        /*
 371         * We'll ignore SIGTERM from now on, we have a
 372         * good client.
 373         */
 374        signal(SIGTERM, SIG_IGN);
 375
 376        return service->fn();
 377}
 378
 379static int upload_pack(void)
 380{
 381        /* Timeout as string */
 382        char timeout_buf[64];
 383
 384        snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
 385
 386        /* git-upload-pack only ever reads stuff, so this is safe */
 387        execl_git_cmd("upload-pack", "--strict", timeout_buf, ".", NULL);
 388        return -1;
 389}
 390
 391static int upload_archive(void)
 392{
 393        execl_git_cmd("upload-archive", ".", NULL);
 394        return -1;
 395}
 396
 397static int receive_pack(void)
 398{
 399        execl_git_cmd("receive-pack", ".", NULL);
 400        return -1;
 401}
 402
 403static struct daemon_service daemon_service[] = {
 404        { "upload-archive", "uploadarch", upload_archive, 0, 1 },
 405        { "upload-pack", "uploadpack", upload_pack, 1, 1 },
 406        { "receive-pack", "receivepack", receive_pack, 0, 1 },
 407};
 408
 409static void enable_service(const char *name, int ena) {
 410        int i;
 411        for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
 412                if (!strcmp(daemon_service[i].name, name)) {
 413                        daemon_service[i].enabled = ena;
 414                        return;
 415                }
 416        }
 417        die("No such service %s", name);
 418}
 419
 420static void make_service_overridable(const char *name, int ena) {
 421        int i;
 422        for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
 423                if (!strcmp(daemon_service[i].name, name)) {
 424                        daemon_service[i].overridable = ena;
 425                        return;
 426                }
 427        }
 428        die("No such service %s", name);
 429}
 430
 431/*
 432 * Separate the "extra args" information as supplied by the client connection.
 433 * Any resulting data is squirreled away in the given interpolation table.
 434 */
 435static void parse_extra_args(struct interp *table, char *extra_args, int buflen)
 436{
 437        char *val;
 438        int vallen;
 439        char *end = extra_args + buflen;
 440
 441        while (extra_args < end && *extra_args) {
 442                saw_extended_args = 1;
 443                if (strncasecmp("host=", extra_args, 5) == 0) {
 444                        val = extra_args + 5;
 445                        vallen = strlen(val) + 1;
 446                        if (*val) {
 447                                /* Split <host>:<port> at colon. */
 448                                char *host = val;
 449                                char *port = strrchr(host, ':');
 450                                if (port) {
 451                                        *port = 0;
 452                                        port++;
 453                                        interp_set_entry(table, INTERP_SLOT_PORT, port);
 454                                }
 455                                interp_set_entry(table, INTERP_SLOT_HOST, host);
 456                        }
 457
 458                        /* On to the next one */
 459                        extra_args = val + vallen;
 460                }
 461        }
 462}
 463
 464static void fill_in_extra_table_entries(struct interp *itable)
 465{
 466        char *hp;
 467
 468        /*
 469         * Replace literal host with lowercase-ized hostname.
 470         */
 471        hp = interp_table[INTERP_SLOT_HOST].value;
 472        if (!hp)
 473                return;
 474        for ( ; *hp; hp++)
 475                *hp = tolower(*hp);
 476
 477        /*
 478         * Locate canonical hostname and its IP address.
 479         */
 480#ifndef NO_IPV6
 481        {
 482                struct addrinfo hints;
 483                struct addrinfo *ai, *ai0;
 484                int gai;
 485                static char addrbuf[HOST_NAME_MAX + 1];
 486
 487                memset(&hints, 0, sizeof(hints));
 488                hints.ai_flags = AI_CANONNAME;
 489
 490                gai = getaddrinfo(interp_table[INTERP_SLOT_HOST].value, 0, &hints, &ai0);
 491                if (!gai) {
 492                        for (ai = ai0; ai; ai = ai->ai_next) {
 493                                struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
 494
 495                                inet_ntop(AF_INET, &sin_addr->sin_addr,
 496                                          addrbuf, sizeof(addrbuf));
 497                                interp_set_entry(interp_table,
 498                                                 INTERP_SLOT_CANON_HOST, ai->ai_canonname);
 499                                interp_set_entry(interp_table,
 500                                                 INTERP_SLOT_IP, addrbuf);
 501                                break;
 502                        }
 503                        freeaddrinfo(ai0);
 504                }
 505        }
 506#else
 507        {
 508                struct hostent *hent;
 509                struct sockaddr_in sa;
 510                char **ap;
 511                static char addrbuf[HOST_NAME_MAX + 1];
 512
 513                hent = gethostbyname(interp_table[INTERP_SLOT_HOST].value);
 514
 515                ap = hent->h_addr_list;
 516                memset(&sa, 0, sizeof sa);
 517                sa.sin_family = hent->h_addrtype;
 518                sa.sin_port = htons(0);
 519                memcpy(&sa.sin_addr, *ap, hent->h_length);
 520
 521                inet_ntop(hent->h_addrtype, &sa.sin_addr,
 522                          addrbuf, sizeof(addrbuf));
 523
 524                interp_set_entry(interp_table, INTERP_SLOT_CANON_HOST, hent->h_name);
 525                interp_set_entry(interp_table, INTERP_SLOT_IP, addrbuf);
 526        }
 527#endif
 528}
 529
 530
 531static int execute(struct sockaddr *addr)
 532{
 533        static char line[1000];
 534        int pktlen, len, i;
 535
 536        if (addr) {
 537                char addrbuf[256] = "";
 538                int port = -1;
 539
 540                if (addr->sa_family == AF_INET) {
 541                        struct sockaddr_in *sin_addr = (void *) addr;
 542                        inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
 543                        port = sin_addr->sin_port;
 544#ifndef NO_IPV6
 545                } else if (addr && addr->sa_family == AF_INET6) {
 546                        struct sockaddr_in6 *sin6_addr = (void *) addr;
 547
 548                        char *buf = addrbuf;
 549                        *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
 550                        inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
 551                        strcat(buf, "]");
 552
 553                        port = sin6_addr->sin6_port;
 554#endif
 555                }
 556                loginfo("Connection from %s:%d", addrbuf, port);
 557        }
 558
 559        alarm(init_timeout ? init_timeout : timeout);
 560        pktlen = packet_read_line(0, line, sizeof(line));
 561        alarm(0);
 562
 563        len = strlen(line);
 564        if (pktlen != len)
 565                loginfo("Extended attributes (%d bytes) exist <%.*s>",
 566                        (int) pktlen - len,
 567                        (int) pktlen - len, line + len + 1);
 568        if (len && line[len-1] == '\n') {
 569                line[--len] = 0;
 570                pktlen--;
 571        }
 572
 573        /*
 574         * Initialize the path interpolation table for this connection.
 575         */
 576        interp_clear_table(interp_table, ARRAY_SIZE(interp_table));
 577        interp_set_entry(interp_table, INTERP_SLOT_PERCENT, "%");
 578
 579        if (len != pktlen) {
 580            parse_extra_args(interp_table, line + len + 1, pktlen - len - 1);
 581            fill_in_extra_table_entries(interp_table);
 582        }
 583
 584        for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
 585                struct daemon_service *s = &(daemon_service[i]);
 586                int namelen = strlen(s->name);
 587                if (!prefixcmp(line, "git-") &&
 588                    !strncmp(s->name, line + 4, namelen) &&
 589                    line[namelen + 4] == ' ') {
 590                        /*
 591                         * Note: The directory here is probably context sensitive,
 592                         * and might depend on the actual service being performed.
 593                         */
 594                        interp_set_entry(interp_table,
 595                                         INTERP_SLOT_DIR, line + namelen + 5);
 596                        return run_service(interp_table, s);
 597                }
 598        }
 599
 600        logerror("Protocol error: '%s'", line);
 601        return -1;
 602}
 603
 604
 605/*
 606 * We count spawned/reaped separately, just to avoid any
 607 * races when updating them from signals. The SIGCHLD handler
 608 * will only update children_reaped, and the fork logic will
 609 * only update children_spawned.
 610 *
 611 * MAX_CHILDREN should be a power-of-two to make the modulus
 612 * operation cheap. It should also be at least twice
 613 * the maximum number of connections we will ever allow.
 614 */
 615#define MAX_CHILDREN 128
 616
 617static int max_connections = 25;
 618
 619/* These are updated by the signal handler */
 620static volatile unsigned int children_reaped;
 621static pid_t dead_child[MAX_CHILDREN];
 622
 623/* These are updated by the main loop */
 624static unsigned int children_spawned;
 625static unsigned int children_deleted;
 626
 627static struct child {
 628        pid_t pid;
 629        int addrlen;
 630        struct sockaddr_storage address;
 631} live_child[MAX_CHILDREN];
 632
 633static void add_child(int idx, pid_t pid, struct sockaddr *addr, int addrlen)
 634{
 635        live_child[idx].pid = pid;
 636        live_child[idx].addrlen = addrlen;
 637        memcpy(&live_child[idx].address, addr, addrlen);
 638}
 639
 640/*
 641 * Walk from "deleted" to "spawned", and remove child "pid".
 642 *
 643 * We move everything up by one, since the new "deleted" will
 644 * be one higher.
 645 */
 646static void remove_child(pid_t pid, unsigned deleted, unsigned spawned)
 647{
 648        struct child n;
 649
 650        deleted %= MAX_CHILDREN;
 651        spawned %= MAX_CHILDREN;
 652        if (live_child[deleted].pid == pid) {
 653                live_child[deleted].pid = -1;
 654                return;
 655        }
 656        n = live_child[deleted];
 657        for (;;) {
 658                struct child m;
 659                deleted = (deleted + 1) % MAX_CHILDREN;
 660                if (deleted == spawned)
 661                        die("could not find dead child %d\n", pid);
 662                m = live_child[deleted];
 663                live_child[deleted] = n;
 664                if (m.pid == pid)
 665                        return;
 666                n = m;
 667        }
 668}
 669
 670/*
 671 * This gets called if the number of connections grows
 672 * past "max_connections".
 673 *
 674 * We _should_ start off by searching for connections
 675 * from the same IP, and if there is some address wth
 676 * multiple connections, we should kill that first.
 677 *
 678 * As it is, we just "randomly" kill 25% of the connections,
 679 * and our pseudo-random generator sucks too. I have no
 680 * shame.
 681 *
 682 * Really, this is just a place-holder for a _real_ algorithm.
 683 */
 684static void kill_some_children(int signo, unsigned start, unsigned stop)
 685{
 686        start %= MAX_CHILDREN;
 687        stop %= MAX_CHILDREN;
 688        while (start != stop) {
 689                if (!(start & 3))
 690                        kill(live_child[start].pid, signo);
 691                start = (start + 1) % MAX_CHILDREN;
 692        }
 693}
 694
 695static void check_max_connections(void)
 696{
 697        for (;;) {
 698                int active;
 699                unsigned spawned, reaped, deleted;
 700
 701                spawned = children_spawned;
 702                reaped = children_reaped;
 703                deleted = children_deleted;
 704
 705                while (deleted < reaped) {
 706                        pid_t pid = dead_child[deleted % MAX_CHILDREN];
 707                        remove_child(pid, deleted, spawned);
 708                        deleted++;
 709                }
 710                children_deleted = deleted;
 711
 712                active = spawned - deleted;
 713                if (active <= max_connections)
 714                        break;
 715
 716                /* Kill some unstarted connections with SIGTERM */
 717                kill_some_children(SIGTERM, deleted, spawned);
 718                if (active <= max_connections << 1)
 719                        break;
 720
 721                /* If the SIGTERM thing isn't helping use SIGKILL */
 722                kill_some_children(SIGKILL, deleted, spawned);
 723                sleep(1);
 724        }
 725}
 726
 727static void handle(int incoming, struct sockaddr *addr, int addrlen)
 728{
 729        pid_t pid = fork();
 730
 731        if (pid) {
 732                unsigned idx;
 733
 734                close(incoming);
 735                if (pid < 0)
 736                        return;
 737
 738                idx = children_spawned % MAX_CHILDREN;
 739                children_spawned++;
 740                add_child(idx, pid, addr, addrlen);
 741
 742                check_max_connections();
 743                return;
 744        }
 745
 746        dup2(incoming, 0);
 747        dup2(incoming, 1);
 748        close(incoming);
 749
 750        exit(execute(addr));
 751}
 752
 753static void child_handler(int signo)
 754{
 755        for (;;) {
 756                int status;
 757                pid_t pid = waitpid(-1, &status, WNOHANG);
 758
 759                if (pid > 0) {
 760                        unsigned reaped = children_reaped;
 761                        dead_child[reaped % MAX_CHILDREN] = pid;
 762                        children_reaped = reaped + 1;
 763                        /* XXX: Custom logging, since we don't wanna getpid() */
 764                        if (verbose) {
 765                                const char *dead = "";
 766                                if (!WIFEXITED(status) || WEXITSTATUS(status) > 0)
 767                                        dead = " (with error)";
 768                                if (log_syslog)
 769                                        syslog(LOG_INFO, "[%d] Disconnected%s", pid, dead);
 770                                else
 771                                        fprintf(stderr, "[%d] Disconnected%s\n", pid, dead);
 772                        }
 773                        continue;
 774                }
 775                break;
 776        }
 777}
 778
 779static int set_reuse_addr(int sockfd)
 780{
 781        int on = 1;
 782
 783        if (!reuseaddr)
 784                return 0;
 785        return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
 786                          &on, sizeof(on));
 787}
 788
 789#ifndef NO_IPV6
 790
 791static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
 792{
 793        int socknum = 0, *socklist = NULL;
 794        int maxfd = -1;
 795        char pbuf[NI_MAXSERV];
 796        struct addrinfo hints, *ai0, *ai;
 797        int gai;
 798        long flags;
 799
 800        sprintf(pbuf, "%d", listen_port);
 801        memset(&hints, 0, sizeof(hints));
 802        hints.ai_family = AF_UNSPEC;
 803        hints.ai_socktype = SOCK_STREAM;
 804        hints.ai_protocol = IPPROTO_TCP;
 805        hints.ai_flags = AI_PASSIVE;
 806
 807        gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
 808        if (gai)
 809                die("getaddrinfo() failed: %s\n", gai_strerror(gai));
 810
 811        for (ai = ai0; ai; ai = ai->ai_next) {
 812                int sockfd;
 813
 814                sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
 815                if (sockfd < 0)
 816                        continue;
 817                if (sockfd >= FD_SETSIZE) {
 818                        error("too large socket descriptor.");
 819                        close(sockfd);
 820                        continue;
 821                }
 822
 823#ifdef IPV6_V6ONLY
 824                if (ai->ai_family == AF_INET6) {
 825                        int on = 1;
 826                        setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
 827                                   &on, sizeof(on));
 828                        /* Note: error is not fatal */
 829                }
 830#endif
 831
 832                if (set_reuse_addr(sockfd)) {
 833                        close(sockfd);
 834                        continue;
 835                }
 836
 837                if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
 838                        close(sockfd);
 839                        continue;       /* not fatal */
 840                }
 841                if (listen(sockfd, 5) < 0) {
 842                        close(sockfd);
 843                        continue;       /* not fatal */
 844                }
 845
 846                flags = fcntl(sockfd, F_GETFD, 0);
 847                if (flags >= 0)
 848                        fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
 849
 850                socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
 851                socklist[socknum++] = sockfd;
 852
 853                if (maxfd < sockfd)
 854                        maxfd = sockfd;
 855        }
 856
 857        freeaddrinfo(ai0);
 858
 859        *socklist_p = socklist;
 860        return socknum;
 861}
 862
 863#else /* NO_IPV6 */
 864
 865static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
 866{
 867        struct sockaddr_in sin;
 868        int sockfd;
 869        long flags;
 870
 871        memset(&sin, 0, sizeof sin);
 872        sin.sin_family = AF_INET;
 873        sin.sin_port = htons(listen_port);
 874
 875        if (listen_addr) {
 876                /* Well, host better be an IP address here. */
 877                if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
 878                        return 0;
 879        } else {
 880                sin.sin_addr.s_addr = htonl(INADDR_ANY);
 881        }
 882
 883        sockfd = socket(AF_INET, SOCK_STREAM, 0);
 884        if (sockfd < 0)
 885                return 0;
 886
 887        if (set_reuse_addr(sockfd)) {
 888                close(sockfd);
 889                return 0;
 890        }
 891
 892        if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
 893                close(sockfd);
 894                return 0;
 895        }
 896
 897        if (listen(sockfd, 5) < 0) {
 898                close(sockfd);
 899                return 0;
 900        }
 901
 902        flags = fcntl(sockfd, F_GETFD, 0);
 903        if (flags >= 0)
 904                fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
 905
 906        *socklist_p = xmalloc(sizeof(int));
 907        **socklist_p = sockfd;
 908        return 1;
 909}
 910
 911#endif
 912
 913static int service_loop(int socknum, int *socklist)
 914{
 915        struct pollfd *pfd;
 916        int i;
 917
 918        pfd = xcalloc(socknum, sizeof(struct pollfd));
 919
 920        for (i = 0; i < socknum; i++) {
 921                pfd[i].fd = socklist[i];
 922                pfd[i].events = POLLIN;
 923        }
 924
 925        signal(SIGCHLD, child_handler);
 926
 927        for (;;) {
 928                int i;
 929
 930                if (poll(pfd, socknum, -1) < 0) {
 931                        if (errno != EINTR) {
 932                                error("poll failed, resuming: %s",
 933                                      strerror(errno));
 934                                sleep(1);
 935                        }
 936                        continue;
 937                }
 938
 939                for (i = 0; i < socknum; i++) {
 940                        if (pfd[i].revents & POLLIN) {
 941                                struct sockaddr_storage ss;
 942                                unsigned int sslen = sizeof(ss);
 943                                int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
 944                                if (incoming < 0) {
 945                                        switch (errno) {
 946                                        case EAGAIN:
 947                                        case EINTR:
 948                                        case ECONNABORTED:
 949                                                continue;
 950                                        default:
 951                                                die("accept returned %s", strerror(errno));
 952                                        }
 953                                }
 954                                handle(incoming, (struct sockaddr *)&ss, sslen);
 955                        }
 956                }
 957        }
 958}
 959
 960/* if any standard file descriptor is missing open it to /dev/null */
 961static void sanitize_stdfds(void)
 962{
 963        int fd = open("/dev/null", O_RDWR, 0);
 964        while (fd != -1 && fd < 2)
 965                fd = dup(fd);
 966        if (fd == -1)
 967                die("open /dev/null or dup failed: %s", strerror(errno));
 968        if (fd > 2)
 969                close(fd);
 970}
 971
 972static void daemonize(void)
 973{
 974        switch (fork()) {
 975                case 0:
 976                        break;
 977                case -1:
 978                        die("fork failed: %s", strerror(errno));
 979                default:
 980                        exit(0);
 981        }
 982        if (setsid() == -1)
 983                die("setsid failed: %s", strerror(errno));
 984        close(0);
 985        close(1);
 986        close(2);
 987        sanitize_stdfds();
 988}
 989
 990static void store_pid(const char *path)
 991{
 992        FILE *f = fopen(path, "w");
 993        if (!f)
 994                die("cannot open pid file %s: %s", path, strerror(errno));
 995        if (fprintf(f, "%d\n", getpid()) < 0 || fclose(f) != 0)
 996                die("failed to write pid file %s: %s", path, strerror(errno));
 997}
 998
 999static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
1000{
1001        int socknum, *socklist;
1002
1003        socknum = socksetup(listen_addr, listen_port, &socklist);
1004        if (socknum == 0)
1005                die("unable to allocate any listen sockets on host %s port %u",
1006                    listen_addr, listen_port);
1007
1008        if (pass && gid &&
1009            (initgroups(pass->pw_name, gid) || setgid (gid) ||
1010             setuid(pass->pw_uid)))
1011                die("cannot drop privileges");
1012
1013        return service_loop(socknum, socklist);
1014}
1015
1016int main(int argc, char **argv)
1017{
1018        int listen_port = 0;
1019        char *listen_addr = NULL;
1020        int inetd_mode = 0;
1021        const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1022        int detach = 0;
1023        struct passwd *pass = NULL;
1024        struct group *group;
1025        gid_t gid = 0;
1026        int i;
1027
1028        /* Without this we cannot rely on waitpid() to tell
1029         * what happened to our children.
1030         */
1031        signal(SIGCHLD, SIG_DFL);
1032
1033        for (i = 1; i < argc; i++) {
1034                char *arg = argv[i];
1035
1036                if (!prefixcmp(arg, "--listen=")) {
1037                    char *p = arg + 9;
1038                    char *ph = listen_addr = xmalloc(strlen(arg + 9) + 1);
1039                    while (*p)
1040                        *ph++ = tolower(*p++);
1041                    *ph = 0;
1042                    continue;
1043                }
1044                if (!prefixcmp(arg, "--port=")) {
1045                        char *end;
1046                        unsigned long n;
1047                        n = strtoul(arg+7, &end, 0);
1048                        if (arg[7] && !*end) {
1049                                listen_port = n;
1050                                continue;
1051                        }
1052                }
1053                if (!strcmp(arg, "--inetd")) {
1054                        inetd_mode = 1;
1055                        log_syslog = 1;
1056                        continue;
1057                }
1058                if (!strcmp(arg, "--verbose")) {
1059                        verbose = 1;
1060                        continue;
1061                }
1062                if (!strcmp(arg, "--syslog")) {
1063                        log_syslog = 1;
1064                        continue;
1065                }
1066                if (!strcmp(arg, "--export-all")) {
1067                        export_all_trees = 1;
1068                        continue;
1069                }
1070                if (!prefixcmp(arg, "--timeout=")) {
1071                        timeout = atoi(arg+10);
1072                        continue;
1073                }
1074                if (!prefixcmp(arg, "--init-timeout=")) {
1075                        init_timeout = atoi(arg+15);
1076                        continue;
1077                }
1078                if (!strcmp(arg, "--strict-paths")) {
1079                        strict_paths = 1;
1080                        continue;
1081                }
1082                if (!prefixcmp(arg, "--base-path=")) {
1083                        base_path = arg+12;
1084                        continue;
1085                }
1086                if (!strcmp(arg, "--base-path-relaxed")) {
1087                        base_path_relaxed = 1;
1088                        continue;
1089                }
1090                if (!prefixcmp(arg, "--interpolated-path=")) {
1091                        interpolated_path = arg+20;
1092                        continue;
1093                }
1094                if (!strcmp(arg, "--reuseaddr")) {
1095                        reuseaddr = 1;
1096                        continue;
1097                }
1098                if (!strcmp(arg, "--user-path")) {
1099                        user_path = "";
1100                        continue;
1101                }
1102                if (!prefixcmp(arg, "--user-path=")) {
1103                        user_path = arg + 12;
1104                        continue;
1105                }
1106                if (!prefixcmp(arg, "--pid-file=")) {
1107                        pid_file = arg + 11;
1108                        continue;
1109                }
1110                if (!strcmp(arg, "--detach")) {
1111                        detach = 1;
1112                        log_syslog = 1;
1113                        continue;
1114                }
1115                if (!prefixcmp(arg, "--user=")) {
1116                        user_name = arg + 7;
1117                        continue;
1118                }
1119                if (!prefixcmp(arg, "--group=")) {
1120                        group_name = arg + 8;
1121                        continue;
1122                }
1123                if (!prefixcmp(arg, "--enable=")) {
1124                        enable_service(arg + 9, 1);
1125                        continue;
1126                }
1127                if (!prefixcmp(arg, "--disable=")) {
1128                        enable_service(arg + 10, 0);
1129                        continue;
1130                }
1131                if (!prefixcmp(arg, "--allow-override=")) {
1132                        make_service_overridable(arg + 17, 1);
1133                        continue;
1134                }
1135                if (!prefixcmp(arg, "--forbid-override=")) {
1136                        make_service_overridable(arg + 18, 0);
1137                        continue;
1138                }
1139                if (!strcmp(arg, "--")) {
1140                        ok_paths = &argv[i+1];
1141                        break;
1142                } else if (arg[0] != '-') {
1143                        ok_paths = &argv[i];
1144                        break;
1145                }
1146
1147                usage(daemon_usage);
1148        }
1149
1150        if (inetd_mode && (group_name || user_name))
1151                die("--user and --group are incompatible with --inetd");
1152
1153        if (inetd_mode && (listen_port || listen_addr))
1154                die("--listen= and --port= are incompatible with --inetd");
1155        else if (listen_port == 0)
1156                listen_port = DEFAULT_GIT_PORT;
1157
1158        if (group_name && !user_name)
1159                die("--group supplied without --user");
1160
1161        if (user_name) {
1162                pass = getpwnam(user_name);
1163                if (!pass)
1164                        die("user not found - %s", user_name);
1165
1166                if (!group_name)
1167                        gid = pass->pw_gid;
1168                else {
1169                        group = getgrnam(group_name);
1170                        if (!group)
1171                                die("group not found - %s", group_name);
1172
1173                        gid = group->gr_gid;
1174                }
1175        }
1176
1177        if (log_syslog) {
1178                openlog("git-daemon", 0, LOG_DAEMON);
1179                set_die_routine(daemon_die);
1180        }
1181
1182        if (strict_paths && (!ok_paths || !*ok_paths))
1183                die("option --strict-paths requires a whitelist");
1184
1185        if (inetd_mode) {
1186                struct sockaddr_storage ss;
1187                struct sockaddr *peer = (struct sockaddr *)&ss;
1188                socklen_t slen = sizeof(ss);
1189
1190                freopen("/dev/null", "w", stderr);
1191
1192                if (getpeername(0, peer, &slen))
1193                        peer = NULL;
1194
1195                return execute(peer);
1196        }
1197
1198        if (detach)
1199                daemonize();
1200        else
1201                sanitize_stdfds();
1202
1203        if (pid_file)
1204                store_pid(pid_file);
1205
1206        return serve(listen_addr, listen_port, pass, gid);
1207}